zone.js 162 KB

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