zone-mix.umd.js 163 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331
  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. /** Object.create */
  696. var ObjectCreate = Object.create;
  697. /** Array.prototype.slice */
  698. var ArraySlice = Array.prototype.slice;
  699. /** addEventListener string const */
  700. var ADD_EVENT_LISTENER_STR = 'addEventListener';
  701. /** removeEventListener string const */
  702. var REMOVE_EVENT_LISTENER_STR = 'removeEventListener';
  703. /** zoneSymbol addEventListener */
  704. var ZONE_SYMBOL_ADD_EVENT_LISTENER = __symbol__(ADD_EVENT_LISTENER_STR);
  705. /** zoneSymbol removeEventListener */
  706. var ZONE_SYMBOL_REMOVE_EVENT_LISTENER = __symbol__(REMOVE_EVENT_LISTENER_STR);
  707. /** true string const */
  708. var TRUE_STR = 'true';
  709. /** false string const */
  710. var FALSE_STR = 'false';
  711. /** Zone symbol prefix string const. */
  712. var ZONE_SYMBOL_PREFIX = __symbol__('');
  713. function wrapWithCurrentZone(callback, source) {
  714. return Zone.current.wrap(callback, source);
  715. }
  716. function scheduleMacroTaskWithCurrentZone(source, callback, data, customSchedule, customCancel) {
  717. return Zone.current.scheduleMacroTask(source, callback, data, customSchedule, customCancel);
  718. }
  719. var zoneSymbol = __symbol__;
  720. var isWindowExists = typeof window !== 'undefined';
  721. var internalWindow = isWindowExists ? window : undefined;
  722. var _global = (isWindowExists && internalWindow) || globalThis;
  723. var REMOVE_ATTRIBUTE = 'removeAttribute';
  724. function bindArguments(args, source) {
  725. for (var i = args.length - 1; i >= 0; i--) {
  726. if (typeof args[i] === 'function') {
  727. args[i] = wrapWithCurrentZone(args[i], source + '_' + i);
  728. }
  729. }
  730. return args;
  731. }
  732. function patchPrototype(prototype, fnNames) {
  733. var source = prototype.constructor['name'];
  734. var _loop_1 = function (i) {
  735. var name_1 = fnNames[i];
  736. var delegate = prototype[name_1];
  737. if (delegate) {
  738. var prototypeDesc = ObjectGetOwnPropertyDescriptor(prototype, name_1);
  739. if (!isPropertyWritable(prototypeDesc)) {
  740. return "continue";
  741. }
  742. prototype[name_1] = (function (delegate) {
  743. var patched = function () {
  744. return delegate.apply(this, bindArguments(arguments, source + '.' + name_1));
  745. };
  746. attachOriginToPatched(patched, delegate);
  747. return patched;
  748. })(delegate);
  749. }
  750. };
  751. for (var i = 0; i < fnNames.length; i++) {
  752. _loop_1(i);
  753. }
  754. }
  755. function isPropertyWritable(propertyDesc) {
  756. if (!propertyDesc) {
  757. return true;
  758. }
  759. if (propertyDesc.writable === false) {
  760. return false;
  761. }
  762. return !(typeof propertyDesc.get === 'function' && typeof propertyDesc.set === 'undefined');
  763. }
  764. var isWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
  765. // Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
  766. // this code.
  767. var isNode = !('nw' in _global) &&
  768. typeof _global.process !== 'undefined' &&
  769. _global.process.toString() === '[object process]';
  770. var isBrowser = !isNode && !isWebWorker && !!(isWindowExists && internalWindow['HTMLElement']);
  771. // we are in electron of nw, so we are both browser and nodejs
  772. // Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
  773. // this code.
  774. var isMix = typeof _global.process !== 'undefined' &&
  775. _global.process.toString() === '[object process]' &&
  776. !isWebWorker &&
  777. !!(isWindowExists && internalWindow['HTMLElement']);
  778. var zoneSymbolEventNames$1 = {};
  779. var enableBeforeunloadSymbol = zoneSymbol('enable_beforeunload');
  780. var wrapFn = function (event) {
  781. // https://github.com/angular/zone.js/issues/911, in IE, sometimes
  782. // event will be undefined, so we need to use window.event
  783. event = event || _global.event;
  784. if (!event) {
  785. return;
  786. }
  787. var eventNameSymbol = zoneSymbolEventNames$1[event.type];
  788. if (!eventNameSymbol) {
  789. eventNameSymbol = zoneSymbolEventNames$1[event.type] = zoneSymbol('ON_PROPERTY' + event.type);
  790. }
  791. var target = this || event.target || _global;
  792. var listener = target[eventNameSymbol];
  793. var result;
  794. if (isBrowser && target === internalWindow && event.type === 'error') {
  795. // window.onerror have different signature
  796. // https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror#window.onerror
  797. // and onerror callback will prevent default when callback return true
  798. var errorEvent = event;
  799. result =
  800. listener &&
  801. listener.call(this, errorEvent.message, errorEvent.filename, errorEvent.lineno, errorEvent.colno, errorEvent.error);
  802. if (result === true) {
  803. event.preventDefault();
  804. }
  805. }
  806. else {
  807. result = listener && listener.apply(this, arguments);
  808. if (
  809. // https://github.com/angular/angular/issues/47579
  810. // https://www.w3.org/TR/2011/WD-html5-20110525/history.html#beforeunloadevent
  811. // This is the only specific case we should check for. The spec defines that the
  812. // `returnValue` attribute represents the message to show the user. When the event
  813. // is created, this attribute must be set to the empty string.
  814. event.type === 'beforeunload' &&
  815. // To prevent any breaking changes resulting from this change, given that
  816. // it was already causing a significant number of failures in G3, we have hidden
  817. // that behavior behind a global configuration flag. Consumers can enable this
  818. // flag explicitly if they want the `beforeunload` event to be handled as defined
  819. // in the specification.
  820. _global[enableBeforeunloadSymbol] &&
  821. // The IDL event definition is `attribute DOMString returnValue`, so we check whether
  822. // `typeof result` is a string.
  823. typeof result === 'string') {
  824. event.returnValue = result;
  825. }
  826. else if (result != undefined && !result) {
  827. event.preventDefault();
  828. }
  829. }
  830. return result;
  831. };
  832. function patchProperty(obj, prop, prototype) {
  833. var desc = ObjectGetOwnPropertyDescriptor(obj, prop);
  834. if (!desc && prototype) {
  835. // when patch window object, use prototype to check prop exist or not
  836. var prototypeDesc = ObjectGetOwnPropertyDescriptor(prototype, prop);
  837. if (prototypeDesc) {
  838. desc = { enumerable: true, configurable: true };
  839. }
  840. }
  841. // if the descriptor not exists or is not configurable
  842. // just return
  843. if (!desc || !desc.configurable) {
  844. return;
  845. }
  846. var onPropPatchedSymbol = zoneSymbol('on' + prop + 'patched');
  847. if (obj.hasOwnProperty(onPropPatchedSymbol) && obj[onPropPatchedSymbol]) {
  848. return;
  849. }
  850. // A property descriptor cannot have getter/setter and be writable
  851. // deleting the writable and value properties avoids this error:
  852. //
  853. // TypeError: property descriptors must not specify a value or be writable when a
  854. // getter or setter has been specified
  855. delete desc.writable;
  856. delete desc.value;
  857. var originalDescGet = desc.get;
  858. var originalDescSet = desc.set;
  859. // slice(2) cuz 'onclick' -> 'click', etc
  860. var eventName = prop.slice(2);
  861. var eventNameSymbol = zoneSymbolEventNames$1[eventName];
  862. if (!eventNameSymbol) {
  863. eventNameSymbol = zoneSymbolEventNames$1[eventName] = zoneSymbol('ON_PROPERTY' + eventName);
  864. }
  865. desc.set = function (newValue) {
  866. // In some versions of Windows, the `this` context may be undefined
  867. // in on-property callbacks.
  868. // To handle this edge case, we check if `this` is falsy and
  869. // fallback to `_global` if needed.
  870. var target = this;
  871. if (!target && obj === _global) {
  872. target = _global;
  873. }
  874. if (!target) {
  875. return;
  876. }
  877. var previousValue = target[eventNameSymbol];
  878. if (typeof previousValue === 'function') {
  879. target.removeEventListener(eventName, wrapFn);
  880. }
  881. // https://github.com/angular/zone.js/issues/978
  882. // If an inline handler (like `onload`) was defined before zone.js was loaded,
  883. // call the original descriptor's setter to clean it up.
  884. originalDescSet === null || originalDescSet === void 0 ? void 0 : originalDescSet.call(target, null);
  885. target[eventNameSymbol] = newValue;
  886. if (typeof newValue === 'function') {
  887. target.addEventListener(eventName, wrapFn, false);
  888. }
  889. };
  890. // The getter would return undefined for unassigned properties but the default value of an
  891. // unassigned property is null
  892. desc.get = function () {
  893. // in some of windows's onproperty callback, this is undefined
  894. // so we need to check it
  895. var target = this;
  896. if (!target && obj === _global) {
  897. target = _global;
  898. }
  899. if (!target) {
  900. return null;
  901. }
  902. var listener = target[eventNameSymbol];
  903. if (listener) {
  904. return listener;
  905. }
  906. else if (originalDescGet) {
  907. // result will be null when use inline event attribute,
  908. // such as <button onclick="func();">OK</button>
  909. // because the onclick function is internal raw uncompiled handler
  910. // the onclick will be evaluated when first time event was triggered or
  911. // the property is accessed, https://github.com/angular/zone.js/issues/525
  912. // so we should use original native get to retrieve the handler
  913. var value = originalDescGet.call(this);
  914. if (value) {
  915. desc.set.call(this, value);
  916. if (typeof target[REMOVE_ATTRIBUTE] === 'function') {
  917. target.removeAttribute(prop);
  918. }
  919. return value;
  920. }
  921. }
  922. return null;
  923. };
  924. ObjectDefineProperty(obj, prop, desc);
  925. obj[onPropPatchedSymbol] = true;
  926. }
  927. function patchOnProperties(obj, properties, prototype) {
  928. if (properties) {
  929. for (var i = 0; i < properties.length; i++) {
  930. patchProperty(obj, 'on' + properties[i], prototype);
  931. }
  932. }
  933. else {
  934. var onProperties = [];
  935. for (var prop in obj) {
  936. if (prop.slice(0, 2) == 'on') {
  937. onProperties.push(prop);
  938. }
  939. }
  940. for (var j = 0; j < onProperties.length; j++) {
  941. patchProperty(obj, onProperties[j], prototype);
  942. }
  943. }
  944. }
  945. var originalInstanceKey = zoneSymbol('originalInstance');
  946. // wrap some native API on `window`
  947. function patchClass(className) {
  948. var OriginalClass = _global[className];
  949. if (!OriginalClass)
  950. return;
  951. // keep original class in global
  952. _global[zoneSymbol(className)] = OriginalClass;
  953. _global[className] = function () {
  954. var a = bindArguments(arguments, className);
  955. switch (a.length) {
  956. case 0:
  957. this[originalInstanceKey] = new OriginalClass();
  958. break;
  959. case 1:
  960. this[originalInstanceKey] = new OriginalClass(a[0]);
  961. break;
  962. case 2:
  963. this[originalInstanceKey] = new OriginalClass(a[0], a[1]);
  964. break;
  965. case 3:
  966. this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2]);
  967. break;
  968. case 4:
  969. this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2], a[3]);
  970. break;
  971. default:
  972. throw new Error('Arg list too long.');
  973. }
  974. };
  975. // attach original delegate to patched function
  976. attachOriginToPatched(_global[className], OriginalClass);
  977. var instance = new OriginalClass(function () { });
  978. var prop;
  979. for (prop in instance) {
  980. // https://bugs.webkit.org/show_bug.cgi?id=44721
  981. if (className === 'XMLHttpRequest' && prop === 'responseBlob')
  982. continue;
  983. (function (prop) {
  984. if (typeof instance[prop] === 'function') {
  985. _global[className].prototype[prop] = function () {
  986. return this[originalInstanceKey][prop].apply(this[originalInstanceKey], arguments);
  987. };
  988. }
  989. else {
  990. ObjectDefineProperty(_global[className].prototype, prop, {
  991. set: function (fn) {
  992. if (typeof fn === 'function') {
  993. this[originalInstanceKey][prop] = wrapWithCurrentZone(fn, className + '.' + prop);
  994. // keep callback in wrapped function so we can
  995. // use it in Function.prototype.toString to return
  996. // the native one.
  997. attachOriginToPatched(this[originalInstanceKey][prop], fn);
  998. }
  999. else {
  1000. this[originalInstanceKey][prop] = fn;
  1001. }
  1002. },
  1003. get: function () {
  1004. return this[originalInstanceKey][prop];
  1005. },
  1006. });
  1007. }
  1008. })(prop);
  1009. }
  1010. for (prop in OriginalClass) {
  1011. if (prop !== 'prototype' && OriginalClass.hasOwnProperty(prop)) {
  1012. _global[className][prop] = OriginalClass[prop];
  1013. }
  1014. }
  1015. }
  1016. function copySymbolProperties(src, dest) {
  1017. if (typeof Object.getOwnPropertySymbols !== 'function') {
  1018. return;
  1019. }
  1020. var symbols = Object.getOwnPropertySymbols(src);
  1021. symbols.forEach(function (symbol) {
  1022. var desc = Object.getOwnPropertyDescriptor(src, symbol);
  1023. Object.defineProperty(dest, symbol, {
  1024. get: function () {
  1025. return src[symbol];
  1026. },
  1027. set: function (value) {
  1028. if (desc && (!desc.writable || typeof desc.set !== 'function')) {
  1029. // if src[symbol] is not writable or not have a setter, just return
  1030. return;
  1031. }
  1032. src[symbol] = value;
  1033. },
  1034. enumerable: desc ? desc.enumerable : true,
  1035. configurable: desc ? desc.configurable : true,
  1036. });
  1037. });
  1038. }
  1039. var shouldCopySymbolProperties = false;
  1040. function setShouldCopySymbolProperties(flag) {
  1041. shouldCopySymbolProperties = flag;
  1042. }
  1043. function patchMethod(target, name, patchFn) {
  1044. var proto = target;
  1045. while (proto && !proto.hasOwnProperty(name)) {
  1046. proto = ObjectGetPrototypeOf(proto);
  1047. }
  1048. if (!proto && target[name]) {
  1049. // somehow we did not find it, but we can see it. This happens on IE for Window properties.
  1050. proto = target;
  1051. }
  1052. var delegateName = zoneSymbol(name);
  1053. var delegate = null;
  1054. if (proto && (!(delegate = proto[delegateName]) || !proto.hasOwnProperty(delegateName))) {
  1055. delegate = proto[delegateName] = proto[name];
  1056. // check whether proto[name] is writable
  1057. // some property is readonly in safari, such as HtmlCanvasElement.prototype.toBlob
  1058. var desc = proto && ObjectGetOwnPropertyDescriptor(proto, name);
  1059. if (isPropertyWritable(desc)) {
  1060. var patchDelegate_1 = patchFn(delegate, delegateName, name);
  1061. proto[name] = function () {
  1062. return patchDelegate_1(this, arguments);
  1063. };
  1064. attachOriginToPatched(proto[name], delegate);
  1065. if (shouldCopySymbolProperties) {
  1066. copySymbolProperties(delegate, proto[name]);
  1067. }
  1068. }
  1069. }
  1070. return delegate;
  1071. }
  1072. // TODO: @JiaLiPassion, support cancel task later if necessary
  1073. function patchMacroTask(obj, funcName, metaCreator) {
  1074. var setNative = null;
  1075. function scheduleTask(task) {
  1076. var data = task.data;
  1077. data.args[data.cbIdx] = function () {
  1078. task.invoke.apply(this, arguments);
  1079. };
  1080. setNative.apply(data.target, data.args);
  1081. return task;
  1082. }
  1083. setNative = patchMethod(obj, funcName, function (delegate) { return function (self, args) {
  1084. var meta = metaCreator(self, args);
  1085. if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
  1086. return scheduleMacroTaskWithCurrentZone(meta.name, args[meta.cbIdx], meta, scheduleTask);
  1087. }
  1088. else {
  1089. // cause an error by calling it directly.
  1090. return delegate.apply(self, args);
  1091. }
  1092. }; });
  1093. }
  1094. function patchMicroTask(obj, funcName, metaCreator) {
  1095. var setNative = null;
  1096. function scheduleTask(task) {
  1097. var data = task.data;
  1098. data.args[data.cbIdx] = function () {
  1099. task.invoke.apply(this, arguments);
  1100. };
  1101. setNative.apply(data.target, data.args);
  1102. return task;
  1103. }
  1104. setNative = patchMethod(obj, funcName, function (delegate) { return function (self, args) {
  1105. var meta = metaCreator(self, args);
  1106. if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
  1107. return Zone.current.scheduleMicroTask(meta.name, args[meta.cbIdx], meta, scheduleTask);
  1108. }
  1109. else {
  1110. // cause an error by calling it directly.
  1111. return delegate.apply(self, args);
  1112. }
  1113. }; });
  1114. }
  1115. function attachOriginToPatched(patched, original) {
  1116. patched[zoneSymbol('OriginalDelegate')] = original;
  1117. }
  1118. var isDetectedIEOrEdge = false;
  1119. var ieOrEdge = false;
  1120. function isIEOrEdge() {
  1121. if (isDetectedIEOrEdge) {
  1122. return ieOrEdge;
  1123. }
  1124. isDetectedIEOrEdge = true;
  1125. try {
  1126. var ua = internalWindow.navigator.userAgent;
  1127. if (ua.indexOf('MSIE ') !== -1 || ua.indexOf('Trident/') !== -1 || ua.indexOf('Edge/') !== -1) {
  1128. ieOrEdge = true;
  1129. }
  1130. }
  1131. catch (error) { }
  1132. return ieOrEdge;
  1133. }
  1134. function isFunction(value) {
  1135. return typeof value === 'function';
  1136. }
  1137. function isNumber(value) {
  1138. return typeof value === 'number';
  1139. }
  1140. /**
  1141. * @fileoverview
  1142. * @suppress {missingRequire}
  1143. */
  1144. // an identifier to tell ZoneTask do not create a new invoke closure
  1145. var OPTIMIZED_ZONE_EVENT_TASK_DATA = {
  1146. useG: true,
  1147. };
  1148. var zoneSymbolEventNames = {};
  1149. var globalSources = {};
  1150. var EVENT_NAME_SYMBOL_REGX = new RegExp('^' + ZONE_SYMBOL_PREFIX + '(\\w+)(true|false)$');
  1151. var IMMEDIATE_PROPAGATION_SYMBOL = zoneSymbol('propagationStopped');
  1152. function prepareEventNames(eventName, eventNameToString) {
  1153. var falseEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + FALSE_STR;
  1154. var trueEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + TRUE_STR;
  1155. var symbol = ZONE_SYMBOL_PREFIX + falseEventName;
  1156. var symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
  1157. zoneSymbolEventNames[eventName] = {};
  1158. zoneSymbolEventNames[eventName][FALSE_STR] = symbol;
  1159. zoneSymbolEventNames[eventName][TRUE_STR] = symbolCapture;
  1160. }
  1161. function patchEventTarget(_global, api, apis, patchOptions) {
  1162. var ADD_EVENT_LISTENER = (patchOptions && patchOptions.add) || ADD_EVENT_LISTENER_STR;
  1163. var REMOVE_EVENT_LISTENER = (patchOptions && patchOptions.rm) || REMOVE_EVENT_LISTENER_STR;
  1164. var LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.listeners) || 'eventListeners';
  1165. var REMOVE_ALL_LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.rmAll) || 'removeAllListeners';
  1166. var zoneSymbolAddEventListener = zoneSymbol(ADD_EVENT_LISTENER);
  1167. var ADD_EVENT_LISTENER_SOURCE = '.' + ADD_EVENT_LISTENER + ':';
  1168. var PREPEND_EVENT_LISTENER = 'prependListener';
  1169. var PREPEND_EVENT_LISTENER_SOURCE = '.' + PREPEND_EVENT_LISTENER + ':';
  1170. var invokeTask = function (task, target, event) {
  1171. // for better performance, check isRemoved which is set
  1172. // by removeEventListener
  1173. if (task.isRemoved) {
  1174. return;
  1175. }
  1176. var delegate = task.callback;
  1177. if (typeof delegate === 'object' && delegate.handleEvent) {
  1178. // create the bind version of handleEvent when invoke
  1179. task.callback = function (event) { return delegate.handleEvent(event); };
  1180. task.originalDelegate = delegate;
  1181. }
  1182. // invoke static task.invoke
  1183. // need to try/catch error here, otherwise, the error in one event listener
  1184. // will break the executions of the other event listeners. Also error will
  1185. // not remove the event listener when `once` options is true.
  1186. var error;
  1187. try {
  1188. task.invoke(task, target, [event]);
  1189. }
  1190. catch (err) {
  1191. error = err;
  1192. }
  1193. var options = task.options;
  1194. if (options && typeof options === 'object' && options.once) {
  1195. // if options.once is true, after invoke once remove listener here
  1196. // only browser need to do this, nodejs eventEmitter will cal removeListener
  1197. // inside EventEmitter.once
  1198. var delegate_1 = task.originalDelegate ? task.originalDelegate : task.callback;
  1199. target[REMOVE_EVENT_LISTENER].call(target, event.type, delegate_1, options);
  1200. }
  1201. return error;
  1202. };
  1203. function globalCallback(context, event, isCapture) {
  1204. // https://github.com/angular/zone.js/issues/911, in IE, sometimes
  1205. // event will be undefined, so we need to use window.event
  1206. event = event || _global.event;
  1207. if (!event) {
  1208. return;
  1209. }
  1210. // event.target is needed for Samsung TV and SourceBuffer
  1211. // || global is needed https://github.com/angular/zone.js/issues/190
  1212. var target = context || event.target || _global;
  1213. var tasks = target[zoneSymbolEventNames[event.type][isCapture ? TRUE_STR : FALSE_STR]];
  1214. if (tasks) {
  1215. var errors = [];
  1216. // invoke all tasks which attached to current target with given event.type and capture = false
  1217. // for performance concern, if task.length === 1, just invoke
  1218. if (tasks.length === 1) {
  1219. var err = invokeTask(tasks[0], target, event);
  1220. err && errors.push(err);
  1221. }
  1222. else {
  1223. // https://github.com/angular/zone.js/issues/836
  1224. // copy the tasks array before invoke, to avoid
  1225. // the callback will remove itself or other listener
  1226. var copyTasks = tasks.slice();
  1227. for (var i = 0; i < copyTasks.length; i++) {
  1228. if (event && event[IMMEDIATE_PROPAGATION_SYMBOL] === true) {
  1229. break;
  1230. }
  1231. var err = invokeTask(copyTasks[i], target, event);
  1232. err && errors.push(err);
  1233. }
  1234. }
  1235. // Since there is only one error, we don't need to schedule microTask
  1236. // to throw the error.
  1237. if (errors.length === 1) {
  1238. throw errors[0];
  1239. }
  1240. else {
  1241. var _loop_2 = function (i) {
  1242. var err = errors[i];
  1243. api.nativeScheduleMicroTask(function () {
  1244. throw err;
  1245. });
  1246. };
  1247. for (var i = 0; i < errors.length; i++) {
  1248. _loop_2(i);
  1249. }
  1250. }
  1251. }
  1252. }
  1253. // global shared zoneAwareCallback to handle all event callback with capture = false
  1254. var globalZoneAwareCallback = function (event) {
  1255. return globalCallback(this, event, false);
  1256. };
  1257. // global shared zoneAwareCallback to handle all event callback with capture = true
  1258. var globalZoneAwareCaptureCallback = function (event) {
  1259. return globalCallback(this, event, true);
  1260. };
  1261. function patchEventTargetMethods(obj, patchOptions) {
  1262. if (!obj) {
  1263. return false;
  1264. }
  1265. var useGlobalCallback = true;
  1266. if (patchOptions && patchOptions.useG !== undefined) {
  1267. useGlobalCallback = patchOptions.useG;
  1268. }
  1269. var validateHandler = patchOptions && patchOptions.vh;
  1270. var checkDuplicate = true;
  1271. if (patchOptions && patchOptions.chkDup !== undefined) {
  1272. checkDuplicate = patchOptions.chkDup;
  1273. }
  1274. var returnTarget = false;
  1275. if (patchOptions && patchOptions.rt !== undefined) {
  1276. returnTarget = patchOptions.rt;
  1277. }
  1278. var proto = obj;
  1279. while (proto && !proto.hasOwnProperty(ADD_EVENT_LISTENER)) {
  1280. proto = ObjectGetPrototypeOf(proto);
  1281. }
  1282. if (!proto && obj[ADD_EVENT_LISTENER]) {
  1283. // somehow we did not find it, but we can see it. This happens on IE for Window properties.
  1284. proto = obj;
  1285. }
  1286. if (!proto) {
  1287. return false;
  1288. }
  1289. if (proto[zoneSymbolAddEventListener]) {
  1290. return false;
  1291. }
  1292. var eventNameToString = patchOptions && patchOptions.eventNameToString;
  1293. // We use a shared global `taskData` to pass data for `scheduleEventTask`,
  1294. // eliminating the need to create a new object solely for passing data.
  1295. // WARNING: This object has a static lifetime, meaning it is not created
  1296. // each time `addEventListener` is called. It is instantiated only once
  1297. // and captured by reference inside the `addEventListener` and
  1298. // `removeEventListener` functions. Do not add any new properties to this
  1299. // object, as doing so would necessitate maintaining the information
  1300. // between `addEventListener` calls.
  1301. var taskData = {};
  1302. var nativeAddEventListener = (proto[zoneSymbolAddEventListener] = proto[ADD_EVENT_LISTENER]);
  1303. var nativeRemoveEventListener = (proto[zoneSymbol(REMOVE_EVENT_LISTENER)] =
  1304. proto[REMOVE_EVENT_LISTENER]);
  1305. var nativeListeners = (proto[zoneSymbol(LISTENERS_EVENT_LISTENER)] =
  1306. proto[LISTENERS_EVENT_LISTENER]);
  1307. var nativeRemoveAllListeners = (proto[zoneSymbol(REMOVE_ALL_LISTENERS_EVENT_LISTENER)] =
  1308. proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER]);
  1309. var nativePrependEventListener;
  1310. if (patchOptions && patchOptions.prepend) {
  1311. nativePrependEventListener = proto[zoneSymbol(patchOptions.prepend)] =
  1312. proto[patchOptions.prepend];
  1313. }
  1314. /**
  1315. * This util function will build an option object with passive option
  1316. * to handle all possible input from the user.
  1317. */
  1318. function buildEventListenerOptions(options, passive) {
  1319. if (!passive) {
  1320. return options;
  1321. }
  1322. if (typeof options === 'boolean') {
  1323. return { capture: options, passive: true };
  1324. }
  1325. if (!options) {
  1326. return { passive: true };
  1327. }
  1328. if (typeof options === 'object' && options.passive !== false) {
  1329. return __assign(__assign({}, options), { passive: true });
  1330. }
  1331. return options;
  1332. }
  1333. var customScheduleGlobal = function (task) {
  1334. // if there is already a task for the eventName + capture,
  1335. // just return, because we use the shared globalZoneAwareCallback here.
  1336. if (taskData.isExisting) {
  1337. return;
  1338. }
  1339. return nativeAddEventListener.call(taskData.target, taskData.eventName, taskData.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, taskData.options);
  1340. };
  1341. /**
  1342. * In the context of events and listeners, this function will be
  1343. * called at the end by `cancelTask`, which, in turn, calls `task.cancelFn`.
  1344. * Cancelling a task is primarily used to remove event listeners from
  1345. * the task target.
  1346. */
  1347. var customCancelGlobal = function (task) {
  1348. // if task is not marked as isRemoved, this call is directly
  1349. // from Zone.prototype.cancelTask, we should remove the task
  1350. // from tasksList of target first
  1351. if (!task.isRemoved) {
  1352. var symbolEventNames = zoneSymbolEventNames[task.eventName];
  1353. var symbolEventName = void 0;
  1354. if (symbolEventNames) {
  1355. symbolEventName = symbolEventNames[task.capture ? TRUE_STR : FALSE_STR];
  1356. }
  1357. var existingTasks = symbolEventName && task.target[symbolEventName];
  1358. if (existingTasks) {
  1359. for (var i = 0; i < existingTasks.length; i++) {
  1360. var existingTask = existingTasks[i];
  1361. if (existingTask === task) {
  1362. existingTasks.splice(i, 1);
  1363. // set isRemoved to data for faster invokeTask check
  1364. task.isRemoved = true;
  1365. if (task.removeAbortListener) {
  1366. task.removeAbortListener();
  1367. task.removeAbortListener = null;
  1368. }
  1369. if (existingTasks.length === 0) {
  1370. // all tasks for the eventName + capture have gone,
  1371. // remove globalZoneAwareCallback and remove the task cache from target
  1372. task.allRemoved = true;
  1373. task.target[symbolEventName] = null;
  1374. }
  1375. break;
  1376. }
  1377. }
  1378. }
  1379. }
  1380. // if all tasks for the eventName + capture have gone,
  1381. // we will really remove the global event callback,
  1382. // if not, return
  1383. if (!task.allRemoved) {
  1384. return;
  1385. }
  1386. return nativeRemoveEventListener.call(task.target, task.eventName, task.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, task.options);
  1387. };
  1388. var customScheduleNonGlobal = function (task) {
  1389. return nativeAddEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
  1390. };
  1391. var customSchedulePrepend = function (task) {
  1392. return nativePrependEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
  1393. };
  1394. var customCancelNonGlobal = function (task) {
  1395. return nativeRemoveEventListener.call(task.target, task.eventName, task.invoke, task.options);
  1396. };
  1397. var customSchedule = useGlobalCallback ? customScheduleGlobal : customScheduleNonGlobal;
  1398. var customCancel = useGlobalCallback ? customCancelGlobal : customCancelNonGlobal;
  1399. var compareTaskCallbackVsDelegate = function (task, delegate) {
  1400. var typeOfDelegate = typeof delegate;
  1401. return ((typeOfDelegate === 'function' && task.callback === delegate) ||
  1402. (typeOfDelegate === 'object' && task.originalDelegate === delegate));
  1403. };
  1404. var compare = (patchOptions === null || patchOptions === void 0 ? void 0 : patchOptions.diff) || compareTaskCallbackVsDelegate;
  1405. var unpatchedEvents = Zone[zoneSymbol('UNPATCHED_EVENTS')];
  1406. var passiveEvents = _global[zoneSymbol('PASSIVE_EVENTS')];
  1407. function copyEventListenerOptions(options) {
  1408. if (typeof options === 'object' && options !== null) {
  1409. // We need to destructure the target `options` object since it may
  1410. // be frozen or sealed (possibly provided implicitly by a third-party
  1411. // library), or its properties may be readonly.
  1412. var newOptions = __assign({}, options);
  1413. // The `signal` option was recently introduced, which caused regressions in
  1414. // third-party scenarios where `AbortController` was directly provided to
  1415. // `addEventListener` as options. For instance, in cases like
  1416. // `document.addEventListener('keydown', callback, abortControllerInstance)`,
  1417. // which is valid because `AbortController` includes a `signal` getter, spreading
  1418. // `{...options}` wouldn't copy the `signal`. Additionally, using `Object.create`
  1419. // isn't feasible since `AbortController` is a built-in object type, and attempting
  1420. // to create a new object directly with it as the prototype might result in
  1421. // unexpected behavior.
  1422. if (options.signal) {
  1423. newOptions.signal = options.signal;
  1424. }
  1425. return newOptions;
  1426. }
  1427. return options;
  1428. }
  1429. var makeAddListener = function (nativeListener, addSource, customScheduleFn, customCancelFn, returnTarget, prepend) {
  1430. if (returnTarget === void 0) { returnTarget = false; }
  1431. if (prepend === void 0) { prepend = false; }
  1432. return function () {
  1433. var target = this || _global;
  1434. var eventName = arguments[0];
  1435. if (patchOptions && patchOptions.transferEventName) {
  1436. eventName = patchOptions.transferEventName(eventName);
  1437. }
  1438. var delegate = arguments[1];
  1439. if (!delegate) {
  1440. return nativeListener.apply(this, arguments);
  1441. }
  1442. if (isNode && eventName === 'uncaughtException') {
  1443. // don't patch uncaughtException of nodejs to prevent endless loop
  1444. return nativeListener.apply(this, arguments);
  1445. }
  1446. // To improve `addEventListener` performance, we will create the callback
  1447. // for the task later when the task is invoked.
  1448. var isEventListenerObject = false;
  1449. if (typeof delegate !== 'function') {
  1450. // This checks whether the provided listener argument is an object with
  1451. // a `handleEvent` method (since we can call `addEventListener` with a
  1452. // function `event => ...` or with an object `{ handleEvent: event => ... }`).
  1453. if (!delegate.handleEvent) {
  1454. return nativeListener.apply(this, arguments);
  1455. }
  1456. isEventListenerObject = true;
  1457. }
  1458. if (validateHandler && !validateHandler(nativeListener, delegate, target, arguments)) {
  1459. return;
  1460. }
  1461. var passive = !!passiveEvents && passiveEvents.indexOf(eventName) !== -1;
  1462. var options = copyEventListenerOptions(buildEventListenerOptions(arguments[2], passive));
  1463. var signal = options === null || options === void 0 ? void 0 : options.signal;
  1464. if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
  1465. // the signal is an aborted one, just return without attaching the event listener.
  1466. return;
  1467. }
  1468. if (unpatchedEvents) {
  1469. // check unpatched list
  1470. for (var i = 0; i < unpatchedEvents.length; i++) {
  1471. if (eventName === unpatchedEvents[i]) {
  1472. if (passive) {
  1473. return nativeListener.call(target, eventName, delegate, options);
  1474. }
  1475. else {
  1476. return nativeListener.apply(this, arguments);
  1477. }
  1478. }
  1479. }
  1480. }
  1481. var capture = !options ? false : typeof options === 'boolean' ? true : options.capture;
  1482. var once = options && typeof options === 'object' ? options.once : false;
  1483. var zone = Zone.current;
  1484. var symbolEventNames = zoneSymbolEventNames[eventName];
  1485. if (!symbolEventNames) {
  1486. prepareEventNames(eventName, eventNameToString);
  1487. symbolEventNames = zoneSymbolEventNames[eventName];
  1488. }
  1489. var symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
  1490. var existingTasks = target[symbolEventName];
  1491. var isExisting = false;
  1492. if (existingTasks) {
  1493. // already have task registered
  1494. isExisting = true;
  1495. if (checkDuplicate) {
  1496. for (var i = 0; i < existingTasks.length; i++) {
  1497. if (compare(existingTasks[i], delegate)) {
  1498. // same callback, same capture, same event name, just return
  1499. return;
  1500. }
  1501. }
  1502. }
  1503. }
  1504. else {
  1505. existingTasks = target[symbolEventName] = [];
  1506. }
  1507. var source;
  1508. var constructorName = target.constructor['name'];
  1509. var targetSource = globalSources[constructorName];
  1510. if (targetSource) {
  1511. source = targetSource[eventName];
  1512. }
  1513. if (!source) {
  1514. source =
  1515. constructorName +
  1516. addSource +
  1517. (eventNameToString ? eventNameToString(eventName) : eventName);
  1518. }
  1519. // In the code below, `options` should no longer be reassigned; instead, it
  1520. // should only be mutated. This is because we pass that object to the native
  1521. // `addEventListener`.
  1522. // It's generally recommended to use the same object reference for options.
  1523. // This ensures consistency and avoids potential issues.
  1524. taskData.options = options;
  1525. if (once) {
  1526. // When using `addEventListener` with the `once` option, we don't pass
  1527. // the `once` option directly to the native `addEventListener` method.
  1528. // Instead, we keep the `once` setting and handle it ourselves.
  1529. taskData.options.once = false;
  1530. }
  1531. taskData.target = target;
  1532. taskData.capture = capture;
  1533. taskData.eventName = eventName;
  1534. taskData.isExisting = isExisting;
  1535. var data = useGlobalCallback ? OPTIMIZED_ZONE_EVENT_TASK_DATA : undefined;
  1536. // keep taskData into data to allow onScheduleEventTask to access the task information
  1537. if (data) {
  1538. data.taskData = taskData;
  1539. }
  1540. if (signal) {
  1541. // When using `addEventListener` with the `signal` option, we don't pass
  1542. // the `signal` option directly to the native `addEventListener` method.
  1543. // Instead, we keep the `signal` setting and handle it ourselves.
  1544. taskData.options.signal = undefined;
  1545. }
  1546. // The `scheduleEventTask` function will ultimately call `customScheduleGlobal`,
  1547. // which in turn calls the native `addEventListener`. This is why `taskData.options`
  1548. // is updated before scheduling the task, as `customScheduleGlobal` uses
  1549. // `taskData.options` to pass it to the native `addEventListener`.
  1550. var task = zone.scheduleEventTask(source, delegate, data, customScheduleFn, customCancelFn);
  1551. if (signal) {
  1552. // after task is scheduled, we need to store the signal back to task.options
  1553. taskData.options.signal = signal;
  1554. // Wrapping `task` in a weak reference would not prevent memory leaks. Weak references are
  1555. // primarily used for preventing strong references cycles. `onAbort` is always reachable
  1556. // as it's an event listener, so its closure retains a strong reference to the `task`.
  1557. var onAbort_1 = function () { return task.zone.cancelTask(task); };
  1558. nativeListener.call(signal, 'abort', onAbort_1, { once: true });
  1559. // We need to remove the `abort` listener when the event listener is going to be removed,
  1560. // as it creates a closure that captures `task`. This closure retains a reference to the
  1561. // `task` object even after it goes out of scope, preventing `task` from being garbage
  1562. // collected.
  1563. task.removeAbortListener = function () { return signal.removeEventListener('abort', onAbort_1); };
  1564. }
  1565. // should clear taskData.target to avoid memory leak
  1566. // issue, https://github.com/angular/angular/issues/20442
  1567. taskData.target = null;
  1568. // need to clear up taskData because it is a global object
  1569. if (data) {
  1570. data.taskData = null;
  1571. }
  1572. // have to save those information to task in case
  1573. // application may call task.zone.cancelTask() directly
  1574. if (once) {
  1575. taskData.options.once = true;
  1576. }
  1577. if (typeof task.options !== 'boolean') {
  1578. // We should save the options on the task (if it's an object) because
  1579. // we'll be using `task.options` later when removing the event listener
  1580. // and passing it back to `removeEventListener`.
  1581. task.options = options;
  1582. }
  1583. task.target = target;
  1584. task.capture = capture;
  1585. task.eventName = eventName;
  1586. if (isEventListenerObject) {
  1587. // save original delegate for compare to check duplicate
  1588. task.originalDelegate = delegate;
  1589. }
  1590. if (!prepend) {
  1591. existingTasks.push(task);
  1592. }
  1593. else {
  1594. existingTasks.unshift(task);
  1595. }
  1596. if (returnTarget) {
  1597. return target;
  1598. }
  1599. };
  1600. };
  1601. proto[ADD_EVENT_LISTENER] = makeAddListener(nativeAddEventListener, ADD_EVENT_LISTENER_SOURCE, customSchedule, customCancel, returnTarget);
  1602. if (nativePrependEventListener) {
  1603. proto[PREPEND_EVENT_LISTENER] = makeAddListener(nativePrependEventListener, PREPEND_EVENT_LISTENER_SOURCE, customSchedulePrepend, customCancel, returnTarget, true);
  1604. }
  1605. proto[REMOVE_EVENT_LISTENER] = function () {
  1606. var target = this || _global;
  1607. var eventName = arguments[0];
  1608. if (patchOptions && patchOptions.transferEventName) {
  1609. eventName = patchOptions.transferEventName(eventName);
  1610. }
  1611. var options = arguments[2];
  1612. var capture = !options ? false : typeof options === 'boolean' ? true : options.capture;
  1613. var delegate = arguments[1];
  1614. if (!delegate) {
  1615. return nativeRemoveEventListener.apply(this, arguments);
  1616. }
  1617. if (validateHandler &&
  1618. !validateHandler(nativeRemoveEventListener, delegate, target, arguments)) {
  1619. return;
  1620. }
  1621. var symbolEventNames = zoneSymbolEventNames[eventName];
  1622. var symbolEventName;
  1623. if (symbolEventNames) {
  1624. symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
  1625. }
  1626. var existingTasks = symbolEventName && target[symbolEventName];
  1627. // `existingTasks` may not exist if the `addEventListener` was called before
  1628. // it was patched by zone.js. Please refer to the attached issue for
  1629. // clarification, particularly after the `if` condition, before calling
  1630. // the native `removeEventListener`.
  1631. if (existingTasks) {
  1632. for (var i = 0; i < existingTasks.length; i++) {
  1633. var existingTask = existingTasks[i];
  1634. if (compare(existingTask, delegate)) {
  1635. existingTasks.splice(i, 1);
  1636. // set isRemoved to data for faster invokeTask check
  1637. existingTask.isRemoved = true;
  1638. if (existingTasks.length === 0) {
  1639. // all tasks for the eventName + capture have gone,
  1640. // remove globalZoneAwareCallback and remove the task cache from target
  1641. existingTask.allRemoved = true;
  1642. target[symbolEventName] = null;
  1643. // in the target, we have an event listener which is added by on_property
  1644. // such as target.onclick = function() {}, so we need to clear this internal
  1645. // property too if all delegates with capture=false were removed
  1646. // https:// github.com/angular/angular/issues/31643
  1647. // https://github.com/angular/angular/issues/54581
  1648. if (!capture && typeof eventName === 'string') {
  1649. var onPropertySymbol = ZONE_SYMBOL_PREFIX + 'ON_PROPERTY' + eventName;
  1650. target[onPropertySymbol] = null;
  1651. }
  1652. }
  1653. // In all other conditions, when `addEventListener` is called after being
  1654. // patched by zone.js, we would always find an event task on the `EventTarget`.
  1655. // This will trigger `cancelFn` on the `existingTask`, leading to `customCancelGlobal`,
  1656. // which ultimately removes an event listener and cleans up the abort listener
  1657. // (if an `AbortSignal` was provided when scheduling a task).
  1658. existingTask.zone.cancelTask(existingTask);
  1659. if (returnTarget) {
  1660. return target;
  1661. }
  1662. return;
  1663. }
  1664. }
  1665. }
  1666. // https://github.com/angular/zone.js/issues/930
  1667. // We may encounter a situation where the `addEventListener` was
  1668. // called on the event target before zone.js is loaded, resulting
  1669. // in no task being stored on the event target due to its invocation
  1670. // of the native implementation. In this scenario, we simply need to
  1671. // invoke the native `removeEventListener`.
  1672. return nativeRemoveEventListener.apply(this, arguments);
  1673. };
  1674. proto[LISTENERS_EVENT_LISTENER] = function () {
  1675. var target = this || _global;
  1676. var eventName = arguments[0];
  1677. if (patchOptions && patchOptions.transferEventName) {
  1678. eventName = patchOptions.transferEventName(eventName);
  1679. }
  1680. var listeners = [];
  1681. var tasks = findEventTasks(target, eventNameToString ? eventNameToString(eventName) : eventName);
  1682. for (var i = 0; i < tasks.length; i++) {
  1683. var task = tasks[i];
  1684. var delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  1685. listeners.push(delegate);
  1686. }
  1687. return listeners;
  1688. };
  1689. proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER] = function () {
  1690. var target = this || _global;
  1691. var eventName = arguments[0];
  1692. if (!eventName) {
  1693. var keys = Object.keys(target);
  1694. for (var i = 0; i < keys.length; i++) {
  1695. var prop = keys[i];
  1696. var match = EVENT_NAME_SYMBOL_REGX.exec(prop);
  1697. var evtName = match && match[1];
  1698. // in nodejs EventEmitter, removeListener event is
  1699. // used for monitoring the removeListener call,
  1700. // so just keep removeListener eventListener until
  1701. // all other eventListeners are removed
  1702. if (evtName && evtName !== 'removeListener') {
  1703. this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, evtName);
  1704. }
  1705. }
  1706. // remove removeListener listener finally
  1707. this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, 'removeListener');
  1708. }
  1709. else {
  1710. if (patchOptions && patchOptions.transferEventName) {
  1711. eventName = patchOptions.transferEventName(eventName);
  1712. }
  1713. var symbolEventNames = zoneSymbolEventNames[eventName];
  1714. if (symbolEventNames) {
  1715. var symbolEventName = symbolEventNames[FALSE_STR];
  1716. var symbolCaptureEventName = symbolEventNames[TRUE_STR];
  1717. var tasks = target[symbolEventName];
  1718. var captureTasks = target[symbolCaptureEventName];
  1719. if (tasks) {
  1720. var removeTasks = tasks.slice();
  1721. for (var i = 0; i < removeTasks.length; i++) {
  1722. var task = removeTasks[i];
  1723. var delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  1724. this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
  1725. }
  1726. }
  1727. if (captureTasks) {
  1728. var removeTasks = captureTasks.slice();
  1729. for (var i = 0; i < removeTasks.length; i++) {
  1730. var task = removeTasks[i];
  1731. var delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  1732. this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
  1733. }
  1734. }
  1735. }
  1736. }
  1737. if (returnTarget) {
  1738. return this;
  1739. }
  1740. };
  1741. // for native toString patch
  1742. attachOriginToPatched(proto[ADD_EVENT_LISTENER], nativeAddEventListener);
  1743. attachOriginToPatched(proto[REMOVE_EVENT_LISTENER], nativeRemoveEventListener);
  1744. if (nativeRemoveAllListeners) {
  1745. attachOriginToPatched(proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER], nativeRemoveAllListeners);
  1746. }
  1747. if (nativeListeners) {
  1748. attachOriginToPatched(proto[LISTENERS_EVENT_LISTENER], nativeListeners);
  1749. }
  1750. return true;
  1751. }
  1752. var results = [];
  1753. for (var i = 0; i < apis.length; i++) {
  1754. results[i] = patchEventTargetMethods(apis[i], patchOptions);
  1755. }
  1756. return results;
  1757. }
  1758. function findEventTasks(target, eventName) {
  1759. if (!eventName) {
  1760. var foundTasks = [];
  1761. for (var prop in target) {
  1762. var match = EVENT_NAME_SYMBOL_REGX.exec(prop);
  1763. var evtName = match && match[1];
  1764. if (evtName && (!eventName || evtName === eventName)) {
  1765. var tasks = target[prop];
  1766. if (tasks) {
  1767. for (var i = 0; i < tasks.length; i++) {
  1768. foundTasks.push(tasks[i]);
  1769. }
  1770. }
  1771. }
  1772. }
  1773. return foundTasks;
  1774. }
  1775. var symbolEventName = zoneSymbolEventNames[eventName];
  1776. if (!symbolEventName) {
  1777. prepareEventNames(eventName);
  1778. symbolEventName = zoneSymbolEventNames[eventName];
  1779. }
  1780. var captureFalseTasks = target[symbolEventName[FALSE_STR]];
  1781. var captureTrueTasks = target[symbolEventName[TRUE_STR]];
  1782. if (!captureFalseTasks) {
  1783. return captureTrueTasks ? captureTrueTasks.slice() : [];
  1784. }
  1785. else {
  1786. return captureTrueTasks
  1787. ? captureFalseTasks.concat(captureTrueTasks)
  1788. : captureFalseTasks.slice();
  1789. }
  1790. }
  1791. function patchEventPrototype(global, api) {
  1792. var Event = global['Event'];
  1793. if (Event && Event.prototype) {
  1794. api.patchMethod(Event.prototype, 'stopImmediatePropagation', function (delegate) { return function (self, args) {
  1795. self[IMMEDIATE_PROPAGATION_SYMBOL] = true;
  1796. // we need to call the native stopImmediatePropagation
  1797. // in case in some hybrid application, some part of
  1798. // application will be controlled by zone, some are not
  1799. delegate && delegate.apply(self, args);
  1800. }; });
  1801. }
  1802. }
  1803. /**
  1804. * @fileoverview
  1805. * @suppress {missingRequire}
  1806. */
  1807. function patchQueueMicrotask(global, api) {
  1808. api.patchMethod(global, 'queueMicrotask', function (delegate) {
  1809. return function (self, args) {
  1810. Zone.current.scheduleMicroTask('queueMicrotask', args[0]);
  1811. };
  1812. });
  1813. }
  1814. /**
  1815. * @fileoverview
  1816. * @suppress {missingRequire}
  1817. */
  1818. var taskSymbol = zoneSymbol('zoneTask');
  1819. function patchTimer(window, setName, cancelName, nameSuffix) {
  1820. var setNative = null;
  1821. var clearNative = null;
  1822. setName += nameSuffix;
  1823. cancelName += nameSuffix;
  1824. var tasksByHandleId = {};
  1825. function scheduleTask(task) {
  1826. var data = task.data;
  1827. data.args[0] = function () {
  1828. return task.invoke.apply(this, arguments);
  1829. };
  1830. var handleOrId = setNative.apply(window, data.args);
  1831. // Whlist on Node.js when get can the ID by using `[Symbol.toPrimitive]()` we do
  1832. // to this so that we do not cause potentally leaks when using `setTimeout`
  1833. // since this can be periodic when using `.refresh`.
  1834. if (isNumber(handleOrId)) {
  1835. data.handleId = handleOrId;
  1836. }
  1837. else {
  1838. data.handle = handleOrId;
  1839. // On Node.js a timeout and interval can be restarted over and over again by using the `.refresh` method.
  1840. data.isRefreshable = isFunction(handleOrId.refresh);
  1841. }
  1842. return task;
  1843. }
  1844. function clearTask(task) {
  1845. var _a = task.data, handle = _a.handle, handleId = _a.handleId;
  1846. return clearNative.call(window, handle !== null && handle !== void 0 ? handle : handleId);
  1847. }
  1848. setNative = patchMethod(window, setName, function (delegate) { return function (self, args) {
  1849. var _a;
  1850. if (isFunction(args[0])) {
  1851. var options_1 = {
  1852. isRefreshable: false,
  1853. isPeriodic: nameSuffix === 'Interval',
  1854. delay: nameSuffix === 'Timeout' || nameSuffix === 'Interval' ? args[1] || 0 : undefined,
  1855. args: args,
  1856. };
  1857. var callback_1 = args[0];
  1858. args[0] = function timer() {
  1859. try {
  1860. return callback_1.apply(this, arguments);
  1861. }
  1862. finally {
  1863. // issue-934, task will be cancelled
  1864. // even it is a periodic task such as
  1865. // setInterval
  1866. // https://github.com/angular/angular/issues/40387
  1867. // Cleanup tasksByHandleId should be handled before scheduleTask
  1868. // Since some zoneSpec may intercept and doesn't trigger
  1869. // scheduleFn(scheduleTask) provided here.
  1870. var handle_1 = options_1.handle, handleId_1 = options_1.handleId, isPeriodic_1 = options_1.isPeriodic, isRefreshable_1 = options_1.isRefreshable;
  1871. if (!isPeriodic_1 && !isRefreshable_1) {
  1872. if (handleId_1) {
  1873. // in non-nodejs env, we remove timerId
  1874. // from local cache
  1875. delete tasksByHandleId[handleId_1];
  1876. }
  1877. else if (handle_1) {
  1878. // Node returns complex objects as handleIds
  1879. // we remove task reference from timer object
  1880. handle_1[taskSymbol] = null;
  1881. }
  1882. }
  1883. }
  1884. };
  1885. var task_1 = scheduleMacroTaskWithCurrentZone(setName, args[0], options_1, scheduleTask, clearTask);
  1886. if (!task_1) {
  1887. return task_1;
  1888. }
  1889. // Node.js must additionally support the ref and unref functions.
  1890. var _b = task_1.data, handleId = _b.handleId, handle = _b.handle, isRefreshable = _b.isRefreshable, isPeriodic = _b.isPeriodic;
  1891. if (handleId) {
  1892. // for non nodejs env, we save handleId: task
  1893. // mapping in local cache for clearTimeout
  1894. tasksByHandleId[handleId] = task_1;
  1895. }
  1896. else if (handle) {
  1897. // for nodejs env, we save task
  1898. // reference in timerId Object for clearTimeout
  1899. handle[taskSymbol] = task_1;
  1900. if (isRefreshable && !isPeriodic) {
  1901. var originalRefresh_1 = handle.refresh;
  1902. handle.refresh = function () {
  1903. var zone = task_1.zone, state = task_1.state;
  1904. if (state === 'notScheduled') {
  1905. task_1._state = 'scheduled';
  1906. zone._updateTaskCount(task_1, 1);
  1907. }
  1908. else if (state === 'running') {
  1909. task_1._state = 'scheduling';
  1910. }
  1911. return originalRefresh_1.call(this);
  1912. };
  1913. }
  1914. }
  1915. return (_a = handle !== null && handle !== void 0 ? handle : handleId) !== null && _a !== void 0 ? _a : task_1;
  1916. }
  1917. else {
  1918. // cause an error by calling it directly.
  1919. return delegate.apply(window, args);
  1920. }
  1921. }; });
  1922. clearNative = patchMethod(window, cancelName, function (delegate) { return function (self, args) {
  1923. var id = args[0];
  1924. var task;
  1925. if (isNumber(id)) {
  1926. // non nodejs env.
  1927. task = tasksByHandleId[id];
  1928. delete tasksByHandleId[id];
  1929. }
  1930. else {
  1931. // nodejs env ?? other environments.
  1932. task = id === null || id === void 0 ? void 0 : id[taskSymbol];
  1933. if (task) {
  1934. id[taskSymbol] = null;
  1935. }
  1936. else {
  1937. task = id;
  1938. }
  1939. }
  1940. if (task === null || task === void 0 ? void 0 : task.type) {
  1941. if (task.cancelFn) {
  1942. // Do not cancel already canceled functions
  1943. task.zone.cancelTask(task);
  1944. }
  1945. }
  1946. else {
  1947. // cause an error by calling it directly.
  1948. delegate.apply(window, args);
  1949. }
  1950. }; });
  1951. }
  1952. function patchCustomElements(_global, api) {
  1953. var _a = api.getGlobalObjects(), isBrowser = _a.isBrowser, isMix = _a.isMix;
  1954. if ((!isBrowser && !isMix) || !_global['customElements'] || !('customElements' in _global)) {
  1955. return;
  1956. }
  1957. // https://html.spec.whatwg.org/multipage/custom-elements.html#concept-custom-element-definition-lifecycle-callbacks
  1958. var callbacks = [
  1959. 'connectedCallback',
  1960. 'disconnectedCallback',
  1961. 'adoptedCallback',
  1962. 'attributeChangedCallback',
  1963. 'formAssociatedCallback',
  1964. 'formDisabledCallback',
  1965. 'formResetCallback',
  1966. 'formStateRestoreCallback',
  1967. ];
  1968. api.patchCallbacks(api, _global.customElements, 'customElements', 'define', callbacks);
  1969. }
  1970. function eventTargetPatch(_global, api) {
  1971. if (Zone[api.symbol('patchEventTarget')]) {
  1972. // EventTarget is already patched.
  1973. return;
  1974. }
  1975. var _a = api.getGlobalObjects(), eventNames = _a.eventNames, zoneSymbolEventNames = _a.zoneSymbolEventNames, TRUE_STR = _a.TRUE_STR, FALSE_STR = _a.FALSE_STR, ZONE_SYMBOL_PREFIX = _a.ZONE_SYMBOL_PREFIX;
  1976. // predefine all __zone_symbol__ + eventName + true/false string
  1977. for (var i = 0; i < eventNames.length; i++) {
  1978. var eventName = eventNames[i];
  1979. var falseEventName = eventName + FALSE_STR;
  1980. var trueEventName = eventName + TRUE_STR;
  1981. var symbol = ZONE_SYMBOL_PREFIX + falseEventName;
  1982. var symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
  1983. zoneSymbolEventNames[eventName] = {};
  1984. zoneSymbolEventNames[eventName][FALSE_STR] = symbol;
  1985. zoneSymbolEventNames[eventName][TRUE_STR] = symbolCapture;
  1986. }
  1987. var EVENT_TARGET = _global['EventTarget'];
  1988. if (!EVENT_TARGET || !EVENT_TARGET.prototype) {
  1989. return;
  1990. }
  1991. api.patchEventTarget(_global, api, [EVENT_TARGET && EVENT_TARGET.prototype]);
  1992. return true;
  1993. }
  1994. function patchEvent(global, api) {
  1995. api.patchEventPrototype(global, api);
  1996. }
  1997. /**
  1998. * @fileoverview
  1999. * @suppress {globalThis}
  2000. */
  2001. function filterProperties(target, onProperties, ignoreProperties) {
  2002. if (!ignoreProperties || ignoreProperties.length === 0) {
  2003. return onProperties;
  2004. }
  2005. var tip = ignoreProperties.filter(function (ip) { return ip.target === target; });
  2006. if (tip.length === 0) {
  2007. return onProperties;
  2008. }
  2009. var targetIgnoreProperties = tip[0].ignoreProperties;
  2010. return onProperties.filter(function (op) { return targetIgnoreProperties.indexOf(op) === -1; });
  2011. }
  2012. function patchFilteredProperties(target, onProperties, ignoreProperties, prototype) {
  2013. // check whether target is available, sometimes target will be undefined
  2014. // because different browser or some 3rd party plugin.
  2015. if (!target) {
  2016. return;
  2017. }
  2018. var filteredProperties = filterProperties(target, onProperties, ignoreProperties);
  2019. patchOnProperties(target, filteredProperties, prototype);
  2020. }
  2021. /**
  2022. * Get all event name properties which the event name startsWith `on`
  2023. * from the target object itself, inherited properties are not considered.
  2024. */
  2025. function getOnEventNames(target) {
  2026. return Object.getOwnPropertyNames(target)
  2027. .filter(function (name) { return name.startsWith('on') && name.length > 2; })
  2028. .map(function (name) { return name.substring(2); });
  2029. }
  2030. function propertyDescriptorPatch(api, _global) {
  2031. if (isNode && !isMix) {
  2032. return;
  2033. }
  2034. if (Zone[api.symbol('patchEvents')]) {
  2035. // events are already been patched by legacy patch.
  2036. return;
  2037. }
  2038. var ignoreProperties = _global['__Zone_ignore_on_properties'];
  2039. // for browsers that we can patch the descriptor: Chrome & Firefox
  2040. var patchTargets = [];
  2041. if (isBrowser) {
  2042. var internalWindow_1 = window;
  2043. patchTargets = patchTargets.concat([
  2044. 'Document',
  2045. 'SVGElement',
  2046. 'Element',
  2047. 'HTMLElement',
  2048. 'HTMLBodyElement',
  2049. 'HTMLMediaElement',
  2050. 'HTMLFrameSetElement',
  2051. 'HTMLFrameElement',
  2052. 'HTMLIFrameElement',
  2053. 'HTMLMarqueeElement',
  2054. 'Worker',
  2055. ]);
  2056. var ignoreErrorProperties = [];
  2057. // In older browsers like IE or Edge, event handler properties (e.g., `onclick`)
  2058. // may not be defined directly on the `window` object but on its prototype (`WindowPrototype`).
  2059. // To ensure complete coverage, we use the prototype when checking
  2060. // for and patching these properties.
  2061. patchFilteredProperties(internalWindow_1, getOnEventNames(internalWindow_1), ignoreProperties ? ignoreProperties.concat(ignoreErrorProperties) : ignoreProperties, ObjectGetPrototypeOf(internalWindow_1));
  2062. }
  2063. patchTargets = patchTargets.concat([
  2064. 'XMLHttpRequest',
  2065. 'XMLHttpRequestEventTarget',
  2066. 'IDBIndex',
  2067. 'IDBRequest',
  2068. 'IDBOpenDBRequest',
  2069. 'IDBDatabase',
  2070. 'IDBTransaction',
  2071. 'IDBCursor',
  2072. 'WebSocket',
  2073. ]);
  2074. for (var i = 0; i < patchTargets.length; i++) {
  2075. var target = _global[patchTargets[i]];
  2076. (target === null || target === void 0 ? void 0 : target.prototype) &&
  2077. patchFilteredProperties(target.prototype, getOnEventNames(target.prototype), ignoreProperties);
  2078. }
  2079. }
  2080. /**
  2081. * @fileoverview
  2082. * @suppress {missingRequire}
  2083. */
  2084. function patchBrowser(Zone) {
  2085. Zone.__load_patch('legacy', function (global) {
  2086. var legacyPatch = global[Zone.__symbol__('legacyPatch')];
  2087. if (legacyPatch) {
  2088. legacyPatch();
  2089. }
  2090. });
  2091. Zone.__load_patch('timers', function (global) {
  2092. var set = 'set';
  2093. var clear = 'clear';
  2094. patchTimer(global, set, clear, 'Timeout');
  2095. patchTimer(global, set, clear, 'Interval');
  2096. patchTimer(global, set, clear, 'Immediate');
  2097. });
  2098. Zone.__load_patch('requestAnimationFrame', function (global) {
  2099. patchTimer(global, 'request', 'cancel', 'AnimationFrame');
  2100. patchTimer(global, 'mozRequest', 'mozCancel', 'AnimationFrame');
  2101. patchTimer(global, 'webkitRequest', 'webkitCancel', 'AnimationFrame');
  2102. });
  2103. Zone.__load_patch('blocking', function (global, Zone) {
  2104. var blockingMethods = ['alert', 'prompt', 'confirm'];
  2105. for (var i = 0; i < blockingMethods.length; i++) {
  2106. var name_2 = blockingMethods[i];
  2107. patchMethod(global, name_2, function (delegate, symbol, name) {
  2108. return function (s, args) {
  2109. return Zone.current.run(delegate, global, args, name);
  2110. };
  2111. });
  2112. }
  2113. });
  2114. Zone.__load_patch('EventTarget', function (global, Zone, api) {
  2115. patchEvent(global, api);
  2116. eventTargetPatch(global, api);
  2117. // patch XMLHttpRequestEventTarget's addEventListener/removeEventListener
  2118. var XMLHttpRequestEventTarget = global['XMLHttpRequestEventTarget'];
  2119. if (XMLHttpRequestEventTarget && XMLHttpRequestEventTarget.prototype) {
  2120. api.patchEventTarget(global, api, [XMLHttpRequestEventTarget.prototype]);
  2121. }
  2122. });
  2123. Zone.__load_patch('MutationObserver', function (global, Zone, api) {
  2124. patchClass('MutationObserver');
  2125. patchClass('WebKitMutationObserver');
  2126. });
  2127. Zone.__load_patch('IntersectionObserver', function (global, Zone, api) {
  2128. patchClass('IntersectionObserver');
  2129. });
  2130. Zone.__load_patch('FileReader', function (global, Zone, api) {
  2131. patchClass('FileReader');
  2132. });
  2133. Zone.__load_patch('on_property', function (global, Zone, api) {
  2134. propertyDescriptorPatch(api, global);
  2135. });
  2136. Zone.__load_patch('customElements', function (global, Zone, api) {
  2137. patchCustomElements(global, api);
  2138. });
  2139. Zone.__load_patch('XHR', function (global, Zone) {
  2140. // Treat XMLHttpRequest as a macrotask.
  2141. patchXHR(global);
  2142. var XHR_TASK = zoneSymbol('xhrTask');
  2143. var XHR_SYNC = zoneSymbol('xhrSync');
  2144. var XHR_LISTENER = zoneSymbol('xhrListener');
  2145. var XHR_SCHEDULED = zoneSymbol('xhrScheduled');
  2146. var XHR_URL = zoneSymbol('xhrURL');
  2147. var XHR_ERROR_BEFORE_SCHEDULED = zoneSymbol('xhrErrorBeforeScheduled');
  2148. function patchXHR(window) {
  2149. var XMLHttpRequest = window['XMLHttpRequest'];
  2150. if (!XMLHttpRequest) {
  2151. // XMLHttpRequest is not available in service worker
  2152. return;
  2153. }
  2154. var XMLHttpRequestPrototype = XMLHttpRequest.prototype;
  2155. function findPendingTask(target) {
  2156. return target[XHR_TASK];
  2157. }
  2158. var oriAddListener = XMLHttpRequestPrototype[ZONE_SYMBOL_ADD_EVENT_LISTENER];
  2159. var oriRemoveListener = XMLHttpRequestPrototype[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
  2160. if (!oriAddListener) {
  2161. var XMLHttpRequestEventTarget_1 = window['XMLHttpRequestEventTarget'];
  2162. if (XMLHttpRequestEventTarget_1) {
  2163. var XMLHttpRequestEventTargetPrototype = XMLHttpRequestEventTarget_1.prototype;
  2164. oriAddListener = XMLHttpRequestEventTargetPrototype[ZONE_SYMBOL_ADD_EVENT_LISTENER];
  2165. oriRemoveListener = XMLHttpRequestEventTargetPrototype[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
  2166. }
  2167. }
  2168. var READY_STATE_CHANGE = 'readystatechange';
  2169. var SCHEDULED = 'scheduled';
  2170. function scheduleTask(task) {
  2171. var data = task.data;
  2172. var target = data.target;
  2173. target[XHR_SCHEDULED] = false;
  2174. target[XHR_ERROR_BEFORE_SCHEDULED] = false;
  2175. // remove existing event listener
  2176. var listener = target[XHR_LISTENER];
  2177. if (!oriAddListener) {
  2178. oriAddListener = target[ZONE_SYMBOL_ADD_EVENT_LISTENER];
  2179. oriRemoveListener = target[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
  2180. }
  2181. if (listener) {
  2182. oriRemoveListener.call(target, READY_STATE_CHANGE, listener);
  2183. }
  2184. var newListener = (target[XHR_LISTENER] = function () {
  2185. if (target.readyState === target.DONE) {
  2186. // sometimes on some browsers XMLHttpRequest will fire onreadystatechange with
  2187. // readyState=4 multiple times, so we need to check task state here
  2188. if (!data.aborted && target[XHR_SCHEDULED] && task.state === SCHEDULED) {
  2189. // check whether the xhr has registered onload listener
  2190. // if that is the case, the task should invoke after all
  2191. // onload listeners finish.
  2192. // Also if the request failed without response (status = 0), the load event handler
  2193. // will not be triggered, in that case, we should also invoke the placeholder callback
  2194. // to close the XMLHttpRequest::send macroTask.
  2195. // https://github.com/angular/angular/issues/38795
  2196. var loadTasks = target[Zone.__symbol__('loadfalse')];
  2197. if (target.status !== 0 && loadTasks && loadTasks.length > 0) {
  2198. var oriInvoke_1 = task.invoke;
  2199. task.invoke = function () {
  2200. // need to load the tasks again, because in other
  2201. // load listener, they may remove themselves
  2202. var loadTasks = target[Zone.__symbol__('loadfalse')];
  2203. for (var i = 0; i < loadTasks.length; i++) {
  2204. if (loadTasks[i] === task) {
  2205. loadTasks.splice(i, 1);
  2206. }
  2207. }
  2208. if (!data.aborted && task.state === SCHEDULED) {
  2209. oriInvoke_1.call(task);
  2210. }
  2211. };
  2212. loadTasks.push(task);
  2213. }
  2214. else {
  2215. task.invoke();
  2216. }
  2217. }
  2218. else if (!data.aborted && target[XHR_SCHEDULED] === false) {
  2219. // error occurs when xhr.send()
  2220. target[XHR_ERROR_BEFORE_SCHEDULED] = true;
  2221. }
  2222. }
  2223. });
  2224. oriAddListener.call(target, READY_STATE_CHANGE, newListener);
  2225. var storedTask = target[XHR_TASK];
  2226. if (!storedTask) {
  2227. target[XHR_TASK] = task;
  2228. }
  2229. sendNative.apply(target, data.args);
  2230. target[XHR_SCHEDULED] = true;
  2231. return task;
  2232. }
  2233. function placeholderCallback() { }
  2234. function clearTask(task) {
  2235. var data = task.data;
  2236. // Note - ideally, we would call data.target.removeEventListener here, but it's too late
  2237. // to prevent it from firing. So instead, we store info for the event listener.
  2238. data.aborted = true;
  2239. return abortNative.apply(data.target, data.args);
  2240. }
  2241. var openNative = patchMethod(XMLHttpRequestPrototype, 'open', function () { return function (self, args) {
  2242. self[XHR_SYNC] = args[2] == false;
  2243. self[XHR_URL] = args[1];
  2244. return openNative.apply(self, args);
  2245. }; });
  2246. var XMLHTTPREQUEST_SOURCE = 'XMLHttpRequest.send';
  2247. var fetchTaskAborting = zoneSymbol('fetchTaskAborting');
  2248. var fetchTaskScheduling = zoneSymbol('fetchTaskScheduling');
  2249. var sendNative = patchMethod(XMLHttpRequestPrototype, 'send', function () { return function (self, args) {
  2250. if (Zone.current[fetchTaskScheduling] === true) {
  2251. // a fetch is scheduling, so we are using xhr to polyfill fetch
  2252. // and because we already schedule macroTask for fetch, we should
  2253. // not schedule a macroTask for xhr again
  2254. return sendNative.apply(self, args);
  2255. }
  2256. if (self[XHR_SYNC]) {
  2257. // if the XHR is sync there is no task to schedule, just execute the code.
  2258. return sendNative.apply(self, args);
  2259. }
  2260. else {
  2261. var options = {
  2262. target: self,
  2263. url: self[XHR_URL],
  2264. isPeriodic: false,
  2265. args: args,
  2266. aborted: false,
  2267. };
  2268. var task = scheduleMacroTaskWithCurrentZone(XMLHTTPREQUEST_SOURCE, placeholderCallback, options, scheduleTask, clearTask);
  2269. if (self &&
  2270. self[XHR_ERROR_BEFORE_SCHEDULED] === true &&
  2271. !options.aborted &&
  2272. task.state === SCHEDULED) {
  2273. // xhr request throw error when send
  2274. // we should invoke task instead of leaving a scheduled
  2275. // pending macroTask
  2276. task.invoke();
  2277. }
  2278. }
  2279. }; });
  2280. var abortNative = patchMethod(XMLHttpRequestPrototype, 'abort', function () { return function (self, args) {
  2281. var task = findPendingTask(self);
  2282. if (task && typeof task.type == 'string') {
  2283. // If the XHR has already completed, do nothing.
  2284. // If the XHR has already been aborted, do nothing.
  2285. // Fix #569, call abort multiple times before done will cause
  2286. // macroTask task count be negative number
  2287. if (task.cancelFn == null || (task.data && task.data.aborted)) {
  2288. return;
  2289. }
  2290. task.zone.cancelTask(task);
  2291. }
  2292. else if (Zone.current[fetchTaskAborting] === true) {
  2293. // the abort is called from fetch polyfill, we need to call native abort of XHR.
  2294. return abortNative.apply(self, args);
  2295. }
  2296. // Otherwise, we are trying to abort an XHR which has not yet been sent, so there is no
  2297. // task
  2298. // to cancel. Do nothing.
  2299. }; });
  2300. }
  2301. });
  2302. Zone.__load_patch('geolocation', function (global) {
  2303. /// GEO_LOCATION
  2304. if (global['navigator'] && global['navigator'].geolocation) {
  2305. patchPrototype(global['navigator'].geolocation, ['getCurrentPosition', 'watchPosition']);
  2306. }
  2307. });
  2308. Zone.__load_patch('PromiseRejectionEvent', function (global, Zone) {
  2309. // handle unhandled promise rejection
  2310. function findPromiseRejectionHandler(evtName) {
  2311. return function (e) {
  2312. var eventTasks = findEventTasks(global, evtName);
  2313. eventTasks.forEach(function (eventTask) {
  2314. // windows has added unhandledrejection event listener
  2315. // trigger the event listener
  2316. var PromiseRejectionEvent = global['PromiseRejectionEvent'];
  2317. if (PromiseRejectionEvent) {
  2318. var evt = new PromiseRejectionEvent(evtName, {
  2319. promise: e.promise,
  2320. reason: e.rejection,
  2321. });
  2322. eventTask.invoke(evt);
  2323. }
  2324. });
  2325. };
  2326. }
  2327. if (global['PromiseRejectionEvent']) {
  2328. Zone[zoneSymbol('unhandledPromiseRejectionHandler')] =
  2329. findPromiseRejectionHandler('unhandledrejection');
  2330. Zone[zoneSymbol('rejectionHandledHandler')] =
  2331. findPromiseRejectionHandler('rejectionhandled');
  2332. }
  2333. });
  2334. Zone.__load_patch('queueMicrotask', function (global, Zone, api) {
  2335. patchQueueMicrotask(global, api);
  2336. });
  2337. }
  2338. function patchPromise(Zone) {
  2339. Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
  2340. var ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  2341. var ObjectDefineProperty = Object.defineProperty;
  2342. function readableObjectToString(obj) {
  2343. if (obj && obj.toString === Object.prototype.toString) {
  2344. var className = obj.constructor && obj.constructor.name;
  2345. return (className ? className : '') + ': ' + JSON.stringify(obj);
  2346. }
  2347. return obj ? obj.toString() : Object.prototype.toString.call(obj);
  2348. }
  2349. var __symbol__ = api.symbol;
  2350. var _uncaughtPromiseErrors = [];
  2351. var isDisableWrappingUncaughtPromiseRejection = global[__symbol__('DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION')] !== false;
  2352. var symbolPromise = __symbol__('Promise');
  2353. var symbolThen = __symbol__('then');
  2354. var creationTrace = '__creationTrace__';
  2355. api.onUnhandledError = function (e) {
  2356. if (api.showUncaughtError()) {
  2357. var rejection = e && e.rejection;
  2358. if (rejection) {
  2359. 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);
  2360. }
  2361. else {
  2362. console.error(e);
  2363. }
  2364. }
  2365. };
  2366. api.microtaskDrainDone = function () {
  2367. var _loop_3 = function () {
  2368. var uncaughtPromiseError = _uncaughtPromiseErrors.shift();
  2369. try {
  2370. uncaughtPromiseError.zone.runGuarded(function () {
  2371. if (uncaughtPromiseError.throwOriginal) {
  2372. throw uncaughtPromiseError.rejection;
  2373. }
  2374. throw uncaughtPromiseError;
  2375. });
  2376. }
  2377. catch (error) {
  2378. handleUnhandledRejection(error);
  2379. }
  2380. };
  2381. while (_uncaughtPromiseErrors.length) {
  2382. _loop_3();
  2383. }
  2384. };
  2385. var UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL = __symbol__('unhandledPromiseRejectionHandler');
  2386. function handleUnhandledRejection(e) {
  2387. api.onUnhandledError(e);
  2388. try {
  2389. var handler = Zone[UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL];
  2390. if (typeof handler === 'function') {
  2391. handler.call(this, e);
  2392. }
  2393. }
  2394. catch (err) { }
  2395. }
  2396. function isThenable(value) {
  2397. return value && typeof value.then === 'function';
  2398. }
  2399. function forwardResolution(value) {
  2400. return value;
  2401. }
  2402. function forwardRejection(rejection) {
  2403. return ZoneAwarePromise.reject(rejection);
  2404. }
  2405. var symbolState = __symbol__('state');
  2406. var symbolValue = __symbol__('value');
  2407. var symbolFinally = __symbol__('finally');
  2408. var symbolParentPromiseValue = __symbol__('parentPromiseValue');
  2409. var symbolParentPromiseState = __symbol__('parentPromiseState');
  2410. var source = 'Promise.then';
  2411. var UNRESOLVED = null;
  2412. var RESOLVED = true;
  2413. var REJECTED = false;
  2414. var REJECTED_NO_CATCH = 0;
  2415. function makeResolver(promise, state) {
  2416. return function (v) {
  2417. try {
  2418. resolvePromise(promise, state, v);
  2419. }
  2420. catch (err) {
  2421. resolvePromise(promise, false, err);
  2422. }
  2423. // Do not return value or you will break the Promise spec.
  2424. };
  2425. }
  2426. var once = function () {
  2427. var wasCalled = false;
  2428. return function wrapper(wrappedFunction) {
  2429. return function () {
  2430. if (wasCalled) {
  2431. return;
  2432. }
  2433. wasCalled = true;
  2434. wrappedFunction.apply(null, arguments);
  2435. };
  2436. };
  2437. };
  2438. var TYPE_ERROR = 'Promise resolved with itself';
  2439. var CURRENT_TASK_TRACE_SYMBOL = __symbol__('currentTaskTrace');
  2440. // Promise Resolution
  2441. function resolvePromise(promise, state, value) {
  2442. var onceWrapper = once();
  2443. if (promise === value) {
  2444. throw new TypeError(TYPE_ERROR);
  2445. }
  2446. if (promise[symbolState] === UNRESOLVED) {
  2447. // should only get value.then once based on promise spec.
  2448. var then = null;
  2449. try {
  2450. if (typeof value === 'object' || typeof value === 'function') {
  2451. then = value && value.then;
  2452. }
  2453. }
  2454. catch (err) {
  2455. onceWrapper(function () {
  2456. resolvePromise(promise, false, err);
  2457. })();
  2458. return promise;
  2459. }
  2460. // if (value instanceof ZoneAwarePromise) {
  2461. if (state !== REJECTED &&
  2462. value instanceof ZoneAwarePromise &&
  2463. value.hasOwnProperty(symbolState) &&
  2464. value.hasOwnProperty(symbolValue) &&
  2465. value[symbolState] !== UNRESOLVED) {
  2466. clearRejectedNoCatch(value);
  2467. resolvePromise(promise, value[symbolState], value[symbolValue]);
  2468. }
  2469. else if (state !== REJECTED && typeof then === 'function') {
  2470. try {
  2471. then.call(value, onceWrapper(makeResolver(promise, state)), onceWrapper(makeResolver(promise, false)));
  2472. }
  2473. catch (err) {
  2474. onceWrapper(function () {
  2475. resolvePromise(promise, false, err);
  2476. })();
  2477. }
  2478. }
  2479. else {
  2480. promise[symbolState] = state;
  2481. var queue = promise[symbolValue];
  2482. promise[symbolValue] = value;
  2483. if (promise[symbolFinally] === symbolFinally) {
  2484. // the promise is generated by Promise.prototype.finally
  2485. if (state === RESOLVED) {
  2486. // the state is resolved, should ignore the value
  2487. // and use parent promise value
  2488. promise[symbolState] = promise[symbolParentPromiseState];
  2489. promise[symbolValue] = promise[symbolParentPromiseValue];
  2490. }
  2491. }
  2492. // record task information in value when error occurs, so we can
  2493. // do some additional work such as render longStackTrace
  2494. if (state === REJECTED && value instanceof Error) {
  2495. // check if longStackTraceZone is here
  2496. var trace = Zone.currentTask &&
  2497. Zone.currentTask.data &&
  2498. Zone.currentTask.data[creationTrace];
  2499. if (trace) {
  2500. // only keep the long stack trace into error when in longStackTraceZone
  2501. ObjectDefineProperty(value, CURRENT_TASK_TRACE_SYMBOL, {
  2502. configurable: true,
  2503. enumerable: false,
  2504. writable: true,
  2505. value: trace,
  2506. });
  2507. }
  2508. }
  2509. for (var i = 0; i < queue.length;) {
  2510. scheduleResolveOrReject(promise, queue[i++], queue[i++], queue[i++], queue[i++]);
  2511. }
  2512. if (queue.length == 0 && state == REJECTED) {
  2513. promise[symbolState] = REJECTED_NO_CATCH;
  2514. var uncaughtPromiseError = value;
  2515. try {
  2516. // Here we throws a new Error to print more readable error log
  2517. // and if the value is not an error, zone.js builds an `Error`
  2518. // Object here to attach the stack information.
  2519. throw new Error('Uncaught (in promise): ' +
  2520. readableObjectToString(value) +
  2521. (value && value.stack ? '\n' + value.stack : ''));
  2522. }
  2523. catch (err) {
  2524. uncaughtPromiseError = err;
  2525. }
  2526. if (isDisableWrappingUncaughtPromiseRejection) {
  2527. // If disable wrapping uncaught promise reject
  2528. // use the value instead of wrapping it.
  2529. uncaughtPromiseError.throwOriginal = true;
  2530. }
  2531. uncaughtPromiseError.rejection = value;
  2532. uncaughtPromiseError.promise = promise;
  2533. uncaughtPromiseError.zone = Zone.current;
  2534. uncaughtPromiseError.task = Zone.currentTask;
  2535. _uncaughtPromiseErrors.push(uncaughtPromiseError);
  2536. api.scheduleMicroTask(); // to make sure that it is running
  2537. }
  2538. }
  2539. }
  2540. // Resolving an already resolved promise is a noop.
  2541. return promise;
  2542. }
  2543. var REJECTION_HANDLED_HANDLER = __symbol__('rejectionHandledHandler');
  2544. function clearRejectedNoCatch(promise) {
  2545. if (promise[symbolState] === REJECTED_NO_CATCH) {
  2546. // if the promise is rejected no catch status
  2547. // and queue.length > 0, means there is a error handler
  2548. // here to handle the rejected promise, we should trigger
  2549. // windows.rejectionhandled eventHandler or nodejs rejectionHandled
  2550. // eventHandler
  2551. try {
  2552. var handler = Zone[REJECTION_HANDLED_HANDLER];
  2553. if (handler && typeof handler === 'function') {
  2554. handler.call(this, { rejection: promise[symbolValue], promise: promise });
  2555. }
  2556. }
  2557. catch (err) { }
  2558. promise[symbolState] = REJECTED;
  2559. for (var i = 0; i < _uncaughtPromiseErrors.length; i++) {
  2560. if (promise === _uncaughtPromiseErrors[i].promise) {
  2561. _uncaughtPromiseErrors.splice(i, 1);
  2562. }
  2563. }
  2564. }
  2565. }
  2566. function scheduleResolveOrReject(promise, zone, chainPromise, onFulfilled, onRejected) {
  2567. clearRejectedNoCatch(promise);
  2568. var promiseState = promise[symbolState];
  2569. var delegate = promiseState
  2570. ? typeof onFulfilled === 'function'
  2571. ? onFulfilled
  2572. : forwardResolution
  2573. : typeof onRejected === 'function'
  2574. ? onRejected
  2575. : forwardRejection;
  2576. zone.scheduleMicroTask(source, function () {
  2577. try {
  2578. var parentPromiseValue = promise[symbolValue];
  2579. var isFinallyPromise = !!chainPromise && symbolFinally === chainPromise[symbolFinally];
  2580. if (isFinallyPromise) {
  2581. // if the promise is generated from finally call, keep parent promise's state and value
  2582. chainPromise[symbolParentPromiseValue] = parentPromiseValue;
  2583. chainPromise[symbolParentPromiseState] = promiseState;
  2584. }
  2585. // should not pass value to finally callback
  2586. var value = zone.run(delegate, undefined, isFinallyPromise && delegate !== forwardRejection && delegate !== forwardResolution
  2587. ? []
  2588. : [parentPromiseValue]);
  2589. resolvePromise(chainPromise, true, value);
  2590. }
  2591. catch (error) {
  2592. // if error occurs, should always return this error
  2593. resolvePromise(chainPromise, false, error);
  2594. }
  2595. }, chainPromise);
  2596. }
  2597. var ZONE_AWARE_PROMISE_TO_STRING = 'function ZoneAwarePromise() { [native code] }';
  2598. var noop = function () { };
  2599. var AggregateError = global.AggregateError;
  2600. var ZoneAwarePromise = /** @class */ (function () {
  2601. function ZoneAwarePromise(executor) {
  2602. var promise = this;
  2603. if (!(promise instanceof ZoneAwarePromise)) {
  2604. throw new Error('Must be an instanceof Promise.');
  2605. }
  2606. promise[symbolState] = UNRESOLVED;
  2607. promise[symbolValue] = []; // queue;
  2608. try {
  2609. var onceWrapper = once();
  2610. executor &&
  2611. executor(onceWrapper(makeResolver(promise, RESOLVED)), onceWrapper(makeResolver(promise, REJECTED)));
  2612. }
  2613. catch (error) {
  2614. resolvePromise(promise, false, error);
  2615. }
  2616. }
  2617. ZoneAwarePromise.toString = function () {
  2618. return ZONE_AWARE_PROMISE_TO_STRING;
  2619. };
  2620. ZoneAwarePromise.resolve = function (value) {
  2621. if (value instanceof ZoneAwarePromise) {
  2622. return value;
  2623. }
  2624. return resolvePromise(new this(null), RESOLVED, value);
  2625. };
  2626. ZoneAwarePromise.reject = function (error) {
  2627. return resolvePromise(new this(null), REJECTED, error);
  2628. };
  2629. ZoneAwarePromise.withResolvers = function () {
  2630. var result = {};
  2631. result.promise = new ZoneAwarePromise(function (res, rej) {
  2632. result.resolve = res;
  2633. result.reject = rej;
  2634. });
  2635. return result;
  2636. };
  2637. ZoneAwarePromise.any = function (values) {
  2638. if (!values || typeof values[Symbol.iterator] !== 'function') {
  2639. return Promise.reject(new AggregateError([], 'All promises were rejected'));
  2640. }
  2641. var promises = [];
  2642. var count = 0;
  2643. try {
  2644. for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
  2645. var v = values_1[_i];
  2646. count++;
  2647. promises.push(ZoneAwarePromise.resolve(v));
  2648. }
  2649. }
  2650. catch (err) {
  2651. return Promise.reject(new AggregateError([], 'All promises were rejected'));
  2652. }
  2653. if (count === 0) {
  2654. return Promise.reject(new AggregateError([], 'All promises were rejected'));
  2655. }
  2656. var finished = false;
  2657. var errors = [];
  2658. return new ZoneAwarePromise(function (resolve, reject) {
  2659. for (var i = 0; i < promises.length; i++) {
  2660. promises[i].then(function (v) {
  2661. if (finished) {
  2662. return;
  2663. }
  2664. finished = true;
  2665. resolve(v);
  2666. }, function (err) {
  2667. errors.push(err);
  2668. count--;
  2669. if (count === 0) {
  2670. finished = true;
  2671. reject(new AggregateError(errors, 'All promises were rejected'));
  2672. }
  2673. });
  2674. }
  2675. });
  2676. };
  2677. ZoneAwarePromise.race = function (values) {
  2678. var resolve;
  2679. var reject;
  2680. var promise = new this(function (res, rej) {
  2681. resolve = res;
  2682. reject = rej;
  2683. });
  2684. function onResolve(value) {
  2685. resolve(value);
  2686. }
  2687. function onReject(error) {
  2688. reject(error);
  2689. }
  2690. for (var _i = 0, values_2 = values; _i < values_2.length; _i++) {
  2691. var value = values_2[_i];
  2692. if (!isThenable(value)) {
  2693. value = this.resolve(value);
  2694. }
  2695. value.then(onResolve, onReject);
  2696. }
  2697. return promise;
  2698. };
  2699. ZoneAwarePromise.all = function (values) {
  2700. return ZoneAwarePromise.allWithCallback(values);
  2701. };
  2702. ZoneAwarePromise.allSettled = function (values) {
  2703. var P = this && this.prototype instanceof ZoneAwarePromise ? this : ZoneAwarePromise;
  2704. return P.allWithCallback(values, {
  2705. thenCallback: function (value) { return ({ status: 'fulfilled', value: value }); },
  2706. errorCallback: function (err) { return ({ status: 'rejected', reason: err }); },
  2707. });
  2708. };
  2709. ZoneAwarePromise.allWithCallback = function (values, callback) {
  2710. var resolve;
  2711. var reject;
  2712. var promise = new this(function (res, rej) {
  2713. resolve = res;
  2714. reject = rej;
  2715. });
  2716. // Start at 2 to prevent prematurely resolving if .then is called immediately.
  2717. var unresolvedCount = 2;
  2718. var valueIndex = 0;
  2719. var resolvedValues = [];
  2720. var _loop_4 = function (value) {
  2721. if (!isThenable(value)) {
  2722. value = this_1.resolve(value);
  2723. }
  2724. var curValueIndex = valueIndex;
  2725. try {
  2726. value.then(function (value) {
  2727. resolvedValues[curValueIndex] = callback ? callback.thenCallback(value) : value;
  2728. unresolvedCount--;
  2729. if (unresolvedCount === 0) {
  2730. resolve(resolvedValues);
  2731. }
  2732. }, function (err) {
  2733. if (!callback) {
  2734. reject(err);
  2735. }
  2736. else {
  2737. resolvedValues[curValueIndex] = callback.errorCallback(err);
  2738. unresolvedCount--;
  2739. if (unresolvedCount === 0) {
  2740. resolve(resolvedValues);
  2741. }
  2742. }
  2743. });
  2744. }
  2745. catch (thenErr) {
  2746. reject(thenErr);
  2747. }
  2748. unresolvedCount++;
  2749. valueIndex++;
  2750. };
  2751. var this_1 = this;
  2752. for (var _i = 0, values_3 = values; _i < values_3.length; _i++) {
  2753. var value = values_3[_i];
  2754. _loop_4(value);
  2755. }
  2756. // Make the unresolvedCount zero-based again.
  2757. unresolvedCount -= 2;
  2758. if (unresolvedCount === 0) {
  2759. resolve(resolvedValues);
  2760. }
  2761. return promise;
  2762. };
  2763. Object.defineProperty(ZoneAwarePromise.prototype, Symbol.toStringTag, {
  2764. get: function () {
  2765. return 'Promise';
  2766. },
  2767. enumerable: false,
  2768. configurable: true
  2769. });
  2770. Object.defineProperty(ZoneAwarePromise.prototype, Symbol.species, {
  2771. get: function () {
  2772. return ZoneAwarePromise;
  2773. },
  2774. enumerable: false,
  2775. configurable: true
  2776. });
  2777. ZoneAwarePromise.prototype.then = function (onFulfilled, onRejected) {
  2778. var _a;
  2779. // We must read `Symbol.species` safely because `this` may be anything. For instance, `this`
  2780. // may be an object without a prototype (created through `Object.create(null)`); thus
  2781. // `this.constructor` will be undefined. One of the use cases is SystemJS creating
  2782. // prototype-less objects (modules) via `Object.create(null)`. The SystemJS creates an empty
  2783. // object and copies promise properties into that object (within the `getOrCreateLoad`
  2784. // function). The zone.js then checks if the resolved value has the `then` method and
  2785. // invokes it with the `value` context. Otherwise, this will throw an error: `TypeError:
  2786. // Cannot read properties of undefined (reading 'Symbol(Symbol.species)')`.
  2787. var C = (_a = this.constructor) === null || _a === void 0 ? void 0 : _a[Symbol.species];
  2788. if (!C || typeof C !== 'function') {
  2789. C = this.constructor || ZoneAwarePromise;
  2790. }
  2791. var chainPromise = new C(noop);
  2792. var zone = Zone.current;
  2793. if (this[symbolState] == UNRESOLVED) {
  2794. this[symbolValue].push(zone, chainPromise, onFulfilled, onRejected);
  2795. }
  2796. else {
  2797. scheduleResolveOrReject(this, zone, chainPromise, onFulfilled, onRejected);
  2798. }
  2799. return chainPromise;
  2800. };
  2801. ZoneAwarePromise.prototype.catch = function (onRejected) {
  2802. return this.then(null, onRejected);
  2803. };
  2804. ZoneAwarePromise.prototype.finally = function (onFinally) {
  2805. var _a;
  2806. // See comment on the call to `then` about why thee `Symbol.species` is safely accessed.
  2807. var C = (_a = this.constructor) === null || _a === void 0 ? void 0 : _a[Symbol.species];
  2808. if (!C || typeof C !== 'function') {
  2809. C = ZoneAwarePromise;
  2810. }
  2811. var chainPromise = new C(noop);
  2812. chainPromise[symbolFinally] = symbolFinally;
  2813. var zone = Zone.current;
  2814. if (this[symbolState] == UNRESOLVED) {
  2815. this[symbolValue].push(zone, chainPromise, onFinally, onFinally);
  2816. }
  2817. else {
  2818. scheduleResolveOrReject(this, zone, chainPromise, onFinally, onFinally);
  2819. }
  2820. return chainPromise;
  2821. };
  2822. return ZoneAwarePromise;
  2823. }());
  2824. // Protect against aggressive optimizers dropping seemingly unused properties.
  2825. // E.g. Closure Compiler in advanced mode.
  2826. ZoneAwarePromise['resolve'] = ZoneAwarePromise.resolve;
  2827. ZoneAwarePromise['reject'] = ZoneAwarePromise.reject;
  2828. ZoneAwarePromise['race'] = ZoneAwarePromise.race;
  2829. ZoneAwarePromise['all'] = ZoneAwarePromise.all;
  2830. var NativePromise = (global[symbolPromise] = global['Promise']);
  2831. global['Promise'] = ZoneAwarePromise;
  2832. var symbolThenPatched = __symbol__('thenPatched');
  2833. function patchThen(Ctor) {
  2834. var proto = Ctor.prototype;
  2835. var prop = ObjectGetOwnPropertyDescriptor(proto, 'then');
  2836. if (prop && (prop.writable === false || !prop.configurable)) {
  2837. // check Ctor.prototype.then propertyDescriptor is writable or not
  2838. // in meteor env, writable is false, we should ignore such case
  2839. return;
  2840. }
  2841. var originalThen = proto.then;
  2842. // Keep a reference to the original method.
  2843. proto[symbolThen] = originalThen;
  2844. Ctor.prototype.then = function (onResolve, onReject) {
  2845. var _this = this;
  2846. var wrapped = new ZoneAwarePromise(function (resolve, reject) {
  2847. originalThen.call(_this, resolve, reject);
  2848. });
  2849. return wrapped.then(onResolve, onReject);
  2850. };
  2851. Ctor[symbolThenPatched] = true;
  2852. }
  2853. api.patchThen = patchThen;
  2854. function zoneify(fn) {
  2855. return function (self, args) {
  2856. var resultPromise = fn.apply(self, args);
  2857. if (resultPromise instanceof ZoneAwarePromise) {
  2858. return resultPromise;
  2859. }
  2860. var ctor = resultPromise.constructor;
  2861. if (!ctor[symbolThenPatched]) {
  2862. patchThen(ctor);
  2863. }
  2864. return resultPromise;
  2865. };
  2866. }
  2867. if (NativePromise) {
  2868. patchThen(NativePromise);
  2869. patchMethod(global, 'fetch', function (delegate) { return zoneify(delegate); });
  2870. }
  2871. // This is not part of public API, but it is useful for tests, so we expose it.
  2872. Promise[Zone.__symbol__('uncaughtPromiseErrors')] = _uncaughtPromiseErrors;
  2873. return ZoneAwarePromise;
  2874. });
  2875. }
  2876. function patchToString(Zone) {
  2877. // override Function.prototype.toString to make zone.js patched function
  2878. // look like native function
  2879. Zone.__load_patch('toString', function (global) {
  2880. // patch Func.prototype.toString to let them look like native
  2881. var originalFunctionToString = Function.prototype.toString;
  2882. var ORIGINAL_DELEGATE_SYMBOL = zoneSymbol('OriginalDelegate');
  2883. var PROMISE_SYMBOL = zoneSymbol('Promise');
  2884. var ERROR_SYMBOL = zoneSymbol('Error');
  2885. var newFunctionToString = function toString() {
  2886. if (typeof this === 'function') {
  2887. var originalDelegate = this[ORIGINAL_DELEGATE_SYMBOL];
  2888. if (originalDelegate) {
  2889. if (typeof originalDelegate === 'function') {
  2890. return originalFunctionToString.call(originalDelegate);
  2891. }
  2892. else {
  2893. return Object.prototype.toString.call(originalDelegate);
  2894. }
  2895. }
  2896. if (this === Promise) {
  2897. var nativePromise = global[PROMISE_SYMBOL];
  2898. if (nativePromise) {
  2899. return originalFunctionToString.call(nativePromise);
  2900. }
  2901. }
  2902. if (this === Error) {
  2903. var nativeError = global[ERROR_SYMBOL];
  2904. if (nativeError) {
  2905. return originalFunctionToString.call(nativeError);
  2906. }
  2907. }
  2908. }
  2909. return originalFunctionToString.call(this);
  2910. };
  2911. newFunctionToString[ORIGINAL_DELEGATE_SYMBOL] = originalFunctionToString;
  2912. Function.prototype.toString = newFunctionToString;
  2913. // patch Object.prototype.toString to let them look like native
  2914. var originalObjectToString = Object.prototype.toString;
  2915. var PROMISE_OBJECT_TO_STRING = '[object Promise]';
  2916. Object.prototype.toString = function () {
  2917. if (typeof Promise === 'function' && this instanceof Promise) {
  2918. return PROMISE_OBJECT_TO_STRING;
  2919. }
  2920. return originalObjectToString.call(this);
  2921. };
  2922. });
  2923. }
  2924. function patchCallbacks(api, target, targetName, method, callbacks) {
  2925. var symbol = Zone.__symbol__(method);
  2926. if (target[symbol]) {
  2927. return;
  2928. }
  2929. var nativeDelegate = (target[symbol] = target[method]);
  2930. target[method] = function (name, opts, options) {
  2931. if (opts && opts.prototype) {
  2932. callbacks.forEach(function (callback) {
  2933. var source = "".concat(targetName, ".").concat(method, "::") + callback;
  2934. var prototype = opts.prototype;
  2935. // Note: the `patchCallbacks` is used for patching the `document.registerElement` and
  2936. // `customElements.define`. We explicitly wrap the patching code into try-catch since
  2937. // callbacks may be already patched by other web components frameworks (e.g. LWC), and they
  2938. // make those properties non-writable. This means that patching callback will throw an error
  2939. // `cannot assign to read-only property`. See this code as an example:
  2940. // https://github.com/salesforce/lwc/blob/master/packages/@lwc/engine-core/src/framework/base-bridge-element.ts#L180-L186
  2941. // We don't want to stop the application rendering if we couldn't patch some
  2942. // callback, e.g. `attributeChangedCallback`.
  2943. try {
  2944. if (prototype.hasOwnProperty(callback)) {
  2945. var descriptor = api.ObjectGetOwnPropertyDescriptor(prototype, callback);
  2946. if (descriptor && descriptor.value) {
  2947. descriptor.value = api.wrapWithCurrentZone(descriptor.value, source);
  2948. api._redefineProperty(opts.prototype, callback, descriptor);
  2949. }
  2950. else if (prototype[callback]) {
  2951. prototype[callback] = api.wrapWithCurrentZone(prototype[callback], source);
  2952. }
  2953. }
  2954. else if (prototype[callback]) {
  2955. prototype[callback] = api.wrapWithCurrentZone(prototype[callback], source);
  2956. }
  2957. }
  2958. catch (_a) {
  2959. // Note: we leave the catch block empty since there's no way to handle the error related
  2960. // to non-writable property.
  2961. }
  2962. });
  2963. }
  2964. return nativeDelegate.call(target, name, opts, options);
  2965. };
  2966. api.attachOriginToPatched(target[method], nativeDelegate);
  2967. }
  2968. function patchUtil(Zone) {
  2969. Zone.__load_patch('util', function (global, Zone, api) {
  2970. // Collect native event names by looking at properties
  2971. // on the global namespace, e.g. 'onclick'.
  2972. var eventNames = getOnEventNames(global);
  2973. api.patchOnProperties = patchOnProperties;
  2974. api.patchMethod = patchMethod;
  2975. api.bindArguments = bindArguments;
  2976. api.patchMacroTask = patchMacroTask;
  2977. // In earlier version of zone.js (<0.9.0), we use env name `__zone_symbol__BLACK_LISTED_EVENTS`
  2978. // to define which events will not be patched by `Zone.js`. In newer version (>=0.9.0), we
  2979. // change the env name to `__zone_symbol__UNPATCHED_EVENTS` to keep the name consistent with
  2980. // angular repo. The `__zone_symbol__BLACK_LISTED_EVENTS` is deprecated, but it is still be
  2981. // supported for backwards compatibility.
  2982. var SYMBOL_BLACK_LISTED_EVENTS = Zone.__symbol__('BLACK_LISTED_EVENTS');
  2983. var SYMBOL_UNPATCHED_EVENTS = Zone.__symbol__('UNPATCHED_EVENTS');
  2984. if (global[SYMBOL_UNPATCHED_EVENTS]) {
  2985. global[SYMBOL_BLACK_LISTED_EVENTS] = global[SYMBOL_UNPATCHED_EVENTS];
  2986. }
  2987. if (global[SYMBOL_BLACK_LISTED_EVENTS]) {
  2988. Zone[SYMBOL_BLACK_LISTED_EVENTS] = Zone[SYMBOL_UNPATCHED_EVENTS] =
  2989. global[SYMBOL_BLACK_LISTED_EVENTS];
  2990. }
  2991. api.patchEventPrototype = patchEventPrototype;
  2992. api.patchEventTarget = patchEventTarget;
  2993. api.isIEOrEdge = isIEOrEdge;
  2994. api.ObjectDefineProperty = ObjectDefineProperty;
  2995. api.ObjectGetOwnPropertyDescriptor = ObjectGetOwnPropertyDescriptor;
  2996. api.ObjectCreate = ObjectCreate;
  2997. api.ArraySlice = ArraySlice;
  2998. api.patchClass = patchClass;
  2999. api.wrapWithCurrentZone = wrapWithCurrentZone;
  3000. api.filterProperties = filterProperties;
  3001. api.attachOriginToPatched = attachOriginToPatched;
  3002. api._redefineProperty = Object.defineProperty;
  3003. api.patchCallbacks = patchCallbacks;
  3004. api.getGlobalObjects = function () { return ({
  3005. globalSources: globalSources,
  3006. zoneSymbolEventNames: zoneSymbolEventNames,
  3007. eventNames: eventNames,
  3008. isBrowser: isBrowser,
  3009. isMix: isMix,
  3010. isNode: isNode,
  3011. TRUE_STR: TRUE_STR,
  3012. FALSE_STR: FALSE_STR,
  3013. ZONE_SYMBOL_PREFIX: ZONE_SYMBOL_PREFIX,
  3014. ADD_EVENT_LISTENER_STR: ADD_EVENT_LISTENER_STR,
  3015. REMOVE_EVENT_LISTENER_STR: REMOVE_EVENT_LISTENER_STR,
  3016. }); };
  3017. });
  3018. }
  3019. function patchCommon(Zone) {
  3020. patchPromise(Zone);
  3021. patchToString(Zone);
  3022. patchUtil(Zone);
  3023. }
  3024. function patchEvents(Zone) {
  3025. Zone.__load_patch('EventEmitter', function (global, Zone, api) {
  3026. // For EventEmitter
  3027. var EE_ADD_LISTENER = 'addListener';
  3028. var EE_PREPEND_LISTENER = 'prependListener';
  3029. var EE_REMOVE_LISTENER = 'removeListener';
  3030. var EE_REMOVE_ALL_LISTENER = 'removeAllListeners';
  3031. var EE_LISTENERS = 'listeners';
  3032. var EE_ON = 'on';
  3033. var EE_OFF = 'off';
  3034. var compareTaskCallbackVsDelegate = function (task, delegate) {
  3035. // same callback, same capture, same event name, just return
  3036. return task.callback === delegate || task.callback.listener === delegate;
  3037. };
  3038. var eventNameToString = function (eventName) {
  3039. if (typeof eventName === 'string') {
  3040. return eventName;
  3041. }
  3042. if (!eventName) {
  3043. return '';
  3044. }
  3045. return eventName.toString().replace('(', '_').replace(')', '_');
  3046. };
  3047. function patchEventEmitterMethods(obj) {
  3048. var result = patchEventTarget(global, api, [obj], {
  3049. useG: false,
  3050. add: EE_ADD_LISTENER,
  3051. rm: EE_REMOVE_LISTENER,
  3052. prepend: EE_PREPEND_LISTENER,
  3053. rmAll: EE_REMOVE_ALL_LISTENER,
  3054. listeners: EE_LISTENERS,
  3055. chkDup: false,
  3056. rt: true,
  3057. diff: compareTaskCallbackVsDelegate,
  3058. eventNameToString: eventNameToString,
  3059. });
  3060. if (result && result[0]) {
  3061. obj[EE_ON] = obj[EE_ADD_LISTENER];
  3062. obj[EE_OFF] = obj[EE_REMOVE_LISTENER];
  3063. }
  3064. }
  3065. // EventEmitter
  3066. var events;
  3067. try {
  3068. events = require('events');
  3069. }
  3070. catch (err) { }
  3071. if (events && events.EventEmitter) {
  3072. patchEventEmitterMethods(events.EventEmitter.prototype);
  3073. }
  3074. });
  3075. }
  3076. function patchFs(Zone) {
  3077. Zone.__load_patch('fs', function (global, Zone, api) {
  3078. var _a;
  3079. var fs;
  3080. try {
  3081. fs = require('fs');
  3082. }
  3083. catch (err) { }
  3084. if (!fs)
  3085. return;
  3086. // watch, watchFile, unwatchFile has been patched
  3087. // because EventEmitter has been patched
  3088. var TO_PATCH_MACROTASK_METHODS = [
  3089. 'access',
  3090. 'appendFile',
  3091. 'chmod',
  3092. 'chown',
  3093. 'close',
  3094. 'exists',
  3095. 'fchmod',
  3096. 'fchown',
  3097. 'fdatasync',
  3098. 'fstat',
  3099. 'fsync',
  3100. 'ftruncate',
  3101. 'futimes',
  3102. 'lchmod',
  3103. 'lchown',
  3104. 'lutimes',
  3105. 'link',
  3106. 'lstat',
  3107. 'mkdir',
  3108. 'mkdtemp',
  3109. 'open',
  3110. 'opendir',
  3111. 'read',
  3112. 'readdir',
  3113. 'readFile',
  3114. 'readlink',
  3115. 'realpath',
  3116. 'rename',
  3117. 'rmdir',
  3118. 'stat',
  3119. 'symlink',
  3120. 'truncate',
  3121. 'unlink',
  3122. 'utimes',
  3123. 'write',
  3124. 'writeFile',
  3125. 'writev',
  3126. ];
  3127. TO_PATCH_MACROTASK_METHODS.filter(function (name) { return !!fs[name] && typeof fs[name] === 'function'; }).forEach(function (name) {
  3128. patchMacroTask(fs, name, function (self, args) {
  3129. return {
  3130. name: 'fs.' + name,
  3131. args: args,
  3132. cbIdx: args.length > 0 ? args.length - 1 : -1,
  3133. target: self,
  3134. };
  3135. });
  3136. });
  3137. var realpathOriginalDelegate = (_a = fs.realpath) === null || _a === void 0 ? void 0 : _a[api.symbol('OriginalDelegate')];
  3138. // This is the only specific method that should be additionally patched because the previous
  3139. // `patchMacroTask` has overridden the `realpath` function and its `native` property.
  3140. if (realpathOriginalDelegate === null || realpathOriginalDelegate === void 0 ? void 0 : realpathOriginalDelegate.native) {
  3141. fs.realpath.native = realpathOriginalDelegate.native;
  3142. patchMacroTask(fs.realpath, 'native', function (self, args) { return ({
  3143. args: args,
  3144. target: self,
  3145. cbIdx: args.length > 0 ? args.length - 1 : -1,
  3146. name: 'fs.realpath.native',
  3147. }); });
  3148. }
  3149. });
  3150. }
  3151. function patchNodeUtil(Zone) {
  3152. Zone.__load_patch('node_util', function (global, Zone, api) {
  3153. api.patchOnProperties = patchOnProperties;
  3154. api.patchMethod = patchMethod;
  3155. api.bindArguments = bindArguments;
  3156. api.patchMacroTask = patchMacroTask;
  3157. setShouldCopySymbolProperties(true);
  3158. });
  3159. }
  3160. var set = 'set';
  3161. var clear = 'clear';
  3162. function patchNode(Zone) {
  3163. patchNodeUtil(Zone);
  3164. patchEvents(Zone);
  3165. patchFs(Zone);
  3166. Zone.__load_patch('node_timers', function (global, Zone) {
  3167. // Timers
  3168. var globalUseTimeoutFromTimer = false;
  3169. try {
  3170. var timers = require('timers');
  3171. var globalEqualTimersTimeout = global.setTimeout === timers.setTimeout;
  3172. if (!globalEqualTimersTimeout && !isMix) {
  3173. // 1. if isMix, then we are in mix environment such as Electron
  3174. // we should only patch timers.setTimeout because global.setTimeout
  3175. // have been patched
  3176. // 2. if global.setTimeout not equal timers.setTimeout, check
  3177. // whether global.setTimeout use timers.setTimeout or not
  3178. var originSetTimeout_1 = timers.setTimeout;
  3179. timers.setTimeout = function () {
  3180. globalUseTimeoutFromTimer = true;
  3181. return originSetTimeout_1.apply(this, arguments);
  3182. };
  3183. var detectTimeout = global.setTimeout(function () { }, 100);
  3184. clearTimeout(detectTimeout);
  3185. timers.setTimeout = originSetTimeout_1;
  3186. }
  3187. patchTimer(timers, set, clear, 'Timeout');
  3188. patchTimer(timers, set, clear, 'Interval');
  3189. patchTimer(timers, set, clear, 'Immediate');
  3190. }
  3191. catch (error) {
  3192. // timers module not exists, for example, when we using nativeScript
  3193. // timers is not available
  3194. }
  3195. if (isMix) {
  3196. // if we are in mix environment, such as Electron,
  3197. // the global.setTimeout has already been patched,
  3198. // so we just patch timers.setTimeout
  3199. return;
  3200. }
  3201. if (!globalUseTimeoutFromTimer) {
  3202. // 1. global setTimeout equals timers setTimeout
  3203. // 2. or global don't use timers setTimeout(maybe some other library patch setTimeout)
  3204. // 3. or load timers module error happens, we should patch global setTimeout
  3205. patchTimer(global, set, clear, 'Timeout');
  3206. patchTimer(global, set, clear, 'Interval');
  3207. patchTimer(global, set, clear, 'Immediate');
  3208. }
  3209. else {
  3210. // global use timers setTimeout, but not equals
  3211. // this happens when use nodejs v0.10.x, global setTimeout will
  3212. // use a lazy load version of timers setTimeout
  3213. // we should not double patch timer's setTimeout
  3214. // so we only store the __symbol__ for consistency
  3215. global[Zone.__symbol__('setTimeout')] = global.setTimeout;
  3216. global[Zone.__symbol__('setInterval')] = global.setInterval;
  3217. global[Zone.__symbol__('setImmediate')] = global.setImmediate;
  3218. }
  3219. });
  3220. // patch process related methods
  3221. Zone.__load_patch('nextTick', function () {
  3222. // patch nextTick as microTask
  3223. patchMicroTask(process, 'nextTick', function (self, args) {
  3224. return {
  3225. name: 'process.nextTick',
  3226. args: args,
  3227. cbIdx: args.length > 0 && typeof args[0] === 'function' ? 0 : -1,
  3228. target: process,
  3229. };
  3230. });
  3231. });
  3232. Zone.__load_patch('handleUnhandledPromiseRejection', function (global, Zone, api) {
  3233. Zone[api.symbol('unhandledPromiseRejectionHandler')] =
  3234. findProcessPromiseRejectionHandler('unhandledRejection');
  3235. Zone[api.symbol('rejectionHandledHandler')] =
  3236. findProcessPromiseRejectionHandler('rejectionHandled');
  3237. // handle unhandled promise rejection
  3238. function findProcessPromiseRejectionHandler(evtName) {
  3239. return function (e) {
  3240. var eventTasks = findEventTasks(process, evtName);
  3241. eventTasks.forEach(function (eventTask) {
  3242. // process has added unhandledrejection event listener
  3243. // trigger the event listener
  3244. if (evtName === 'unhandledRejection') {
  3245. eventTask.invoke(e.rejection, e.promise);
  3246. }
  3247. else if (evtName === 'rejectionHandled') {
  3248. eventTask.invoke(e.promise);
  3249. }
  3250. });
  3251. };
  3252. }
  3253. });
  3254. // Crypto
  3255. Zone.__load_patch('crypto', function () {
  3256. var crypto;
  3257. try {
  3258. crypto = require('crypto');
  3259. }
  3260. catch (err) { }
  3261. // use the generic patchMacroTask to patch crypto
  3262. if (crypto) {
  3263. var methodNames = ['randomBytes', 'pbkdf2'];
  3264. methodNames.forEach(function (name) {
  3265. patchMacroTask(crypto, name, function (self, args) {
  3266. return {
  3267. name: 'crypto.' + name,
  3268. args: args,
  3269. cbIdx: args.length > 0 && typeof args[args.length - 1] === 'function' ? args.length - 1 : -1,
  3270. target: crypto,
  3271. };
  3272. });
  3273. });
  3274. }
  3275. });
  3276. Zone.__load_patch('console', function (global, Zone) {
  3277. var consoleMethods = [
  3278. 'dir',
  3279. 'log',
  3280. 'info',
  3281. 'error',
  3282. 'warn',
  3283. 'assert',
  3284. 'debug',
  3285. 'timeEnd',
  3286. 'trace',
  3287. ];
  3288. consoleMethods.forEach(function (m) {
  3289. var originalMethod = (console[Zone.__symbol__(m)] = console[m]);
  3290. if (originalMethod) {
  3291. console[m] = function () {
  3292. var args = ArraySlice.call(arguments);
  3293. if (Zone.current === Zone.root) {
  3294. return originalMethod.apply(this, args);
  3295. }
  3296. else {
  3297. return Zone.root.run(originalMethod, this, args);
  3298. }
  3299. };
  3300. }
  3301. });
  3302. });
  3303. Zone.__load_patch('queueMicrotask', function (global, Zone, api) {
  3304. patchQueueMicrotask(global, api);
  3305. });
  3306. }
  3307. function loadZone() {
  3308. var _a;
  3309. // if global['Zone'] already exists (maybe zone.js was already loaded or
  3310. // some other lib also registered a global object named Zone), we may need
  3311. // to throw an error, but sometimes user may not want this error.
  3312. // For example,
  3313. // we have two web pages, page1 includes zone.js, page2 doesn't.
  3314. // and the 1st time user load page1 and page2, everything work fine,
  3315. // but when user load page2 again, error occurs because global['Zone'] already exists.
  3316. // so we add a flag to let user choose whether to throw this error or not.
  3317. // By default, if existing Zone is from zone.js, we will not throw the error.
  3318. var global = globalThis;
  3319. var checkDuplicate = global[__symbol__('forceDuplicateZoneCheck')] === true;
  3320. if (global['Zone'] && (checkDuplicate || typeof global['Zone'].__symbol__ !== 'function')) {
  3321. throw new Error('Zone already loaded.');
  3322. }
  3323. // Initialize global `Zone` constant.
  3324. (_a = global['Zone']) !== null && _a !== void 0 ? _a : (global['Zone'] = initZone());
  3325. return global['Zone'];
  3326. }
  3327. var Zone$1 = loadZone();
  3328. patchCommon(Zone$1);
  3329. patchBrowser(Zone$1);
  3330. patchNode(Zone$1);
  3331. }));