zone.js 120 KB

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