zone-mix.js 130 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008
  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. static assertZonePatched() {
  43. if (global['Promise'] !== patches['ZoneAwarePromise']) {
  44. throw new Error('Zone.js has detected that ZoneAwarePromise `(window|global).Promise` ' +
  45. 'has been overwritten.\n' +
  46. 'Most likely cause is that a Promise polyfill has been loaded ' +
  47. 'after Zone.js (Polyfilling Promise api is not necessary when zone.js is loaded. ' +
  48. 'If you must load one, do so before loading zone.js.)');
  49. }
  50. }
  51. static get root() {
  52. let zone = Zone.current;
  53. while (zone.parent) {
  54. zone = zone.parent;
  55. }
  56. return zone;
  57. }
  58. static get current() {
  59. return _currentZoneFrame.zone;
  60. }
  61. static get currentTask() {
  62. return _currentTask;
  63. }
  64. // tslint:disable-next-line:require-internal-with-underscore
  65. static __load_patch(name, fn, ignoreDuplicate = false) {
  66. if (patches.hasOwnProperty(name)) {
  67. // `checkDuplicate` option is defined from global variable
  68. // so it works for all modules.
  69. // `ignoreDuplicate` can work for the specified module
  70. if (!ignoreDuplicate && checkDuplicate) {
  71. throw Error('Already loaded patch: ' + name);
  72. }
  73. }
  74. else if (!global['__Zone_disable_' + name]) {
  75. const perfName = 'Zone:' + name;
  76. mark(perfName);
  77. patches[name] = fn(global, Zone, _api);
  78. performanceMeasure(perfName, perfName);
  79. }
  80. }
  81. get parent() {
  82. return this._parent;
  83. }
  84. get name() {
  85. return this._name;
  86. }
  87. constructor(parent, zoneSpec) {
  88. this._parent = parent;
  89. this._name = zoneSpec ? zoneSpec.name || 'unnamed' : '<root>';
  90. this._properties = zoneSpec && zoneSpec.properties || {};
  91. this._zoneDelegate =
  92. new _ZoneDelegate(this, this._parent && this._parent._zoneDelegate, zoneSpec);
  93. }
  94. get(key) {
  95. const zone = this.getZoneWith(key);
  96. if (zone)
  97. return zone._properties[key];
  98. }
  99. getZoneWith(key) {
  100. let current = this;
  101. while (current) {
  102. if (current._properties.hasOwnProperty(key)) {
  103. return current;
  104. }
  105. current = current._parent;
  106. }
  107. return null;
  108. }
  109. fork(zoneSpec) {
  110. if (!zoneSpec)
  111. throw new Error('ZoneSpec required!');
  112. return this._zoneDelegate.fork(this, zoneSpec);
  113. }
  114. wrap(callback, source) {
  115. if (typeof callback !== 'function') {
  116. throw new Error('Expecting function got: ' + callback);
  117. }
  118. const _callback = this._zoneDelegate.intercept(this, callback, source);
  119. const zone = this;
  120. return function () {
  121. return zone.runGuarded(_callback, this, arguments, source);
  122. };
  123. }
  124. run(callback, applyThis, applyArgs, source) {
  125. _currentZoneFrame = { parent: _currentZoneFrame, zone: this };
  126. try {
  127. return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
  128. }
  129. finally {
  130. _currentZoneFrame = _currentZoneFrame.parent;
  131. }
  132. }
  133. runGuarded(callback, applyThis = null, applyArgs, source) {
  134. _currentZoneFrame = { parent: _currentZoneFrame, zone: this };
  135. try {
  136. try {
  137. return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
  138. }
  139. catch (error) {
  140. if (this._zoneDelegate.handleError(this, error)) {
  141. throw error;
  142. }
  143. }
  144. }
  145. finally {
  146. _currentZoneFrame = _currentZoneFrame.parent;
  147. }
  148. }
  149. runTask(task, applyThis, applyArgs) {
  150. if (task.zone != this) {
  151. throw new Error('A task can only be run in the zone of creation! (Creation: ' +
  152. (task.zone || NO_ZONE).name + '; Execution: ' + this.name + ')');
  153. }
  154. // https://github.com/angular/zone.js/issues/778, sometimes eventTask
  155. // will run in notScheduled(canceled) state, we should not try to
  156. // run such kind of task but just return
  157. if (task.state === notScheduled && (task.type === eventTask || task.type === macroTask)) {
  158. return;
  159. }
  160. const reEntryGuard = task.state != running;
  161. reEntryGuard && task._transitionTo(running, scheduled);
  162. task.runCount++;
  163. const previousTask = _currentTask;
  164. _currentTask = task;
  165. _currentZoneFrame = { parent: _currentZoneFrame, zone: this };
  166. try {
  167. if (task.type == macroTask && task.data && !task.data.isPeriodic) {
  168. task.cancelFn = undefined;
  169. }
  170. try {
  171. return this._zoneDelegate.invokeTask(this, task, applyThis, applyArgs);
  172. }
  173. catch (error) {
  174. if (this._zoneDelegate.handleError(this, error)) {
  175. throw error;
  176. }
  177. }
  178. }
  179. finally {
  180. // if the task's state is notScheduled or unknown, then it has already been cancelled
  181. // we should not reset the state to scheduled
  182. if (task.state !== notScheduled && task.state !== unknown) {
  183. if (task.type == eventTask || (task.data && task.data.isPeriodic)) {
  184. reEntryGuard && task._transitionTo(scheduled, running);
  185. }
  186. else {
  187. task.runCount = 0;
  188. this._updateTaskCount(task, -1);
  189. reEntryGuard &&
  190. task._transitionTo(notScheduled, running, notScheduled);
  191. }
  192. }
  193. _currentZoneFrame = _currentZoneFrame.parent;
  194. _currentTask = previousTask;
  195. }
  196. }
  197. scheduleTask(task) {
  198. if (task.zone && task.zone !== this) {
  199. // check if the task was rescheduled, the newZone
  200. // should not be the children of the original zone
  201. let newZone = this;
  202. while (newZone) {
  203. if (newZone === task.zone) {
  204. throw Error(`can not reschedule task to ${this.name} which is descendants of the original zone ${task.zone.name}`);
  205. }
  206. newZone = newZone.parent;
  207. }
  208. }
  209. task._transitionTo(scheduling, notScheduled);
  210. const zoneDelegates = [];
  211. task._zoneDelegates = zoneDelegates;
  212. task._zone = this;
  213. try {
  214. task = this._zoneDelegate.scheduleTask(this, task);
  215. }
  216. catch (err) {
  217. // should set task's state to unknown when scheduleTask throw error
  218. // because the err may from reschedule, so the fromState maybe notScheduled
  219. task._transitionTo(unknown, scheduling, notScheduled);
  220. // TODO: @JiaLiPassion, should we check the result from handleError?
  221. this._zoneDelegate.handleError(this, err);
  222. throw err;
  223. }
  224. if (task._zoneDelegates === zoneDelegates) {
  225. // we have to check because internally the delegate can reschedule the task.
  226. this._updateTaskCount(task, 1);
  227. }
  228. if (task.state == scheduling) {
  229. task._transitionTo(scheduled, scheduling);
  230. }
  231. return task;
  232. }
  233. scheduleMicroTask(source, callback, data, customSchedule) {
  234. return this.scheduleTask(new ZoneTask(microTask, source, callback, data, customSchedule, undefined));
  235. }
  236. scheduleMacroTask(source, callback, data, customSchedule, customCancel) {
  237. return this.scheduleTask(new ZoneTask(macroTask, source, callback, data, customSchedule, customCancel));
  238. }
  239. scheduleEventTask(source, callback, data, customSchedule, customCancel) {
  240. return this.scheduleTask(new ZoneTask(eventTask, source, callback, data, customSchedule, customCancel));
  241. }
  242. cancelTask(task) {
  243. if (task.zone != this)
  244. throw new Error('A task can only be cancelled in the zone of creation! (Creation: ' +
  245. (task.zone || NO_ZONE).name + '; Execution: ' + this.name + ')');
  246. if (task.state !== scheduled && task.state !== running) {
  247. return;
  248. }
  249. task._transitionTo(canceling, scheduled, running);
  250. try {
  251. this._zoneDelegate.cancelTask(this, task);
  252. }
  253. catch (err) {
  254. // if error occurs when cancelTask, transit the state to unknown
  255. task._transitionTo(unknown, canceling);
  256. this._zoneDelegate.handleError(this, err);
  257. throw err;
  258. }
  259. this._updateTaskCount(task, -1);
  260. task._transitionTo(notScheduled, canceling);
  261. task.runCount = 0;
  262. return task;
  263. }
  264. _updateTaskCount(task, count) {
  265. const zoneDelegates = task._zoneDelegates;
  266. if (count == -1) {
  267. task._zoneDelegates = null;
  268. }
  269. for (let i = 0; i < zoneDelegates.length; i++) {
  270. zoneDelegates[i]._updateTaskCount(task.type, count);
  271. }
  272. }
  273. }
  274. // tslint:disable-next-line:require-internal-with-underscore
  275. Zone.__symbol__ = __symbol__;
  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 copySymbolProperties(src, dest) {
  943. if (typeof Object.getOwnPropertySymbols !== 'function') {
  944. return;
  945. }
  946. const symbols = Object.getOwnPropertySymbols(src);
  947. symbols.forEach((symbol) => {
  948. const desc = Object.getOwnPropertyDescriptor(src, symbol);
  949. Object.defineProperty(dest, symbol, {
  950. get: function () {
  951. return src[symbol];
  952. },
  953. set: function (value) {
  954. if (desc && (!desc.writable || typeof desc.set !== 'function')) {
  955. // if src[symbol] is not writable or not have a setter, just return
  956. return;
  957. }
  958. src[symbol] = value;
  959. },
  960. enumerable: desc ? desc.enumerable : true,
  961. configurable: desc ? desc.configurable : true
  962. });
  963. });
  964. }
  965. let shouldCopySymbolProperties = false;
  966. function setShouldCopySymbolProperties(flag) {
  967. shouldCopySymbolProperties = flag;
  968. }
  969. function patchMethod(target, name, patchFn) {
  970. let proto = target;
  971. while (proto && !proto.hasOwnProperty(name)) {
  972. proto = ObjectGetPrototypeOf(proto);
  973. }
  974. if (!proto && target[name]) {
  975. // somehow we did not find it, but we can see it. This happens on IE for Window properties.
  976. proto = target;
  977. }
  978. const delegateName = zoneSymbol(name);
  979. let delegate = null;
  980. if (proto && (!(delegate = proto[delegateName]) || !proto.hasOwnProperty(delegateName))) {
  981. delegate = proto[delegateName] = proto[name];
  982. // check whether proto[name] is writable
  983. // some property is readonly in safari, such as HtmlCanvasElement.prototype.toBlob
  984. const desc = proto && ObjectGetOwnPropertyDescriptor(proto, name);
  985. if (isPropertyWritable(desc)) {
  986. const patchDelegate = patchFn(delegate, delegateName, name);
  987. proto[name] = function () {
  988. return patchDelegate(this, arguments);
  989. };
  990. attachOriginToPatched(proto[name], delegate);
  991. if (shouldCopySymbolProperties) {
  992. copySymbolProperties(delegate, proto[name]);
  993. }
  994. }
  995. }
  996. return delegate;
  997. }
  998. // TODO: @JiaLiPassion, support cancel task later if necessary
  999. function patchMacroTask(obj, funcName, metaCreator) {
  1000. let setNative = null;
  1001. function scheduleTask(task) {
  1002. const data = task.data;
  1003. data.args[data.cbIdx] = function () {
  1004. task.invoke.apply(this, arguments);
  1005. };
  1006. setNative.apply(data.target, data.args);
  1007. return task;
  1008. }
  1009. setNative = patchMethod(obj, funcName, (delegate) => function (self, args) {
  1010. const meta = metaCreator(self, args);
  1011. if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
  1012. return scheduleMacroTaskWithCurrentZone(meta.name, args[meta.cbIdx], meta, scheduleTask);
  1013. }
  1014. else {
  1015. // cause an error by calling it directly.
  1016. return delegate.apply(self, args);
  1017. }
  1018. });
  1019. }
  1020. function patchMicroTask(obj, funcName, metaCreator) {
  1021. let setNative = null;
  1022. function scheduleTask(task) {
  1023. const data = task.data;
  1024. data.args[data.cbIdx] = function () {
  1025. task.invoke.apply(this, arguments);
  1026. };
  1027. setNative.apply(data.target, data.args);
  1028. return task;
  1029. }
  1030. setNative = patchMethod(obj, funcName, (delegate) => function (self, args) {
  1031. const meta = metaCreator(self, args);
  1032. if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
  1033. return Zone.current.scheduleMicroTask(meta.name, args[meta.cbIdx], meta, scheduleTask);
  1034. }
  1035. else {
  1036. // cause an error by calling it directly.
  1037. return delegate.apply(self, args);
  1038. }
  1039. });
  1040. }
  1041. function attachOriginToPatched(patched, original) {
  1042. patched[zoneSymbol('OriginalDelegate')] = original;
  1043. }
  1044. let isDetectedIEOrEdge = false;
  1045. let ieOrEdge = false;
  1046. function isIE() {
  1047. try {
  1048. const ua = internalWindow.navigator.userAgent;
  1049. if (ua.indexOf('MSIE ') !== -1 || ua.indexOf('Trident/') !== -1) {
  1050. return true;
  1051. }
  1052. }
  1053. catch (error) {
  1054. }
  1055. return false;
  1056. }
  1057. function isIEOrEdge() {
  1058. if (isDetectedIEOrEdge) {
  1059. return ieOrEdge;
  1060. }
  1061. isDetectedIEOrEdge = true;
  1062. try {
  1063. const ua = internalWindow.navigator.userAgent;
  1064. if (ua.indexOf('MSIE ') !== -1 || ua.indexOf('Trident/') !== -1 || ua.indexOf('Edge/') !== -1) {
  1065. ieOrEdge = true;
  1066. }
  1067. }
  1068. catch (error) {
  1069. }
  1070. return ieOrEdge;
  1071. }
  1072. Zone.__load_patch('ZoneAwarePromise', (global, Zone, api) => {
  1073. const ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  1074. const ObjectDefineProperty = Object.defineProperty;
  1075. function readableObjectToString(obj) {
  1076. if (obj && obj.toString === Object.prototype.toString) {
  1077. const className = obj.constructor && obj.constructor.name;
  1078. return (className ? className : '') + ': ' + JSON.stringify(obj);
  1079. }
  1080. return obj ? obj.toString() : Object.prototype.toString.call(obj);
  1081. }
  1082. const __symbol__ = api.symbol;
  1083. const _uncaughtPromiseErrors = [];
  1084. const isDisableWrappingUncaughtPromiseRejection = global[__symbol__('DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION')] === true;
  1085. const symbolPromise = __symbol__('Promise');
  1086. const symbolThen = __symbol__('then');
  1087. const creationTrace = '__creationTrace__';
  1088. api.onUnhandledError = (e) => {
  1089. if (api.showUncaughtError()) {
  1090. const rejection = e && e.rejection;
  1091. if (rejection) {
  1092. 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);
  1093. }
  1094. else {
  1095. console.error(e);
  1096. }
  1097. }
  1098. };
  1099. api.microtaskDrainDone = () => {
  1100. while (_uncaughtPromiseErrors.length) {
  1101. const uncaughtPromiseError = _uncaughtPromiseErrors.shift();
  1102. try {
  1103. uncaughtPromiseError.zone.runGuarded(() => {
  1104. if (uncaughtPromiseError.throwOriginal) {
  1105. throw uncaughtPromiseError.rejection;
  1106. }
  1107. throw uncaughtPromiseError;
  1108. });
  1109. }
  1110. catch (error) {
  1111. handleUnhandledRejection(error);
  1112. }
  1113. }
  1114. };
  1115. const UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL = __symbol__('unhandledPromiseRejectionHandler');
  1116. function handleUnhandledRejection(e) {
  1117. api.onUnhandledError(e);
  1118. try {
  1119. const handler = Zone[UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL];
  1120. if (typeof handler === 'function') {
  1121. handler.call(this, e);
  1122. }
  1123. }
  1124. catch (err) {
  1125. }
  1126. }
  1127. function isThenable(value) {
  1128. return value && value.then;
  1129. }
  1130. function forwardResolution(value) {
  1131. return value;
  1132. }
  1133. function forwardRejection(rejection) {
  1134. return ZoneAwarePromise.reject(rejection);
  1135. }
  1136. const symbolState = __symbol__('state');
  1137. const symbolValue = __symbol__('value');
  1138. const symbolFinally = __symbol__('finally');
  1139. const symbolParentPromiseValue = __symbol__('parentPromiseValue');
  1140. const symbolParentPromiseState = __symbol__('parentPromiseState');
  1141. const source = 'Promise.then';
  1142. const UNRESOLVED = null;
  1143. const RESOLVED = true;
  1144. const REJECTED = false;
  1145. const REJECTED_NO_CATCH = 0;
  1146. function makeResolver(promise, state) {
  1147. return (v) => {
  1148. try {
  1149. resolvePromise(promise, state, v);
  1150. }
  1151. catch (err) {
  1152. resolvePromise(promise, false, err);
  1153. }
  1154. // Do not return value or you will break the Promise spec.
  1155. };
  1156. }
  1157. const once = function () {
  1158. let wasCalled = false;
  1159. return function wrapper(wrappedFunction) {
  1160. return function () {
  1161. if (wasCalled) {
  1162. return;
  1163. }
  1164. wasCalled = true;
  1165. wrappedFunction.apply(null, arguments);
  1166. };
  1167. };
  1168. };
  1169. const TYPE_ERROR = 'Promise resolved with itself';
  1170. const CURRENT_TASK_TRACE_SYMBOL = __symbol__('currentTaskTrace');
  1171. // Promise Resolution
  1172. function resolvePromise(promise, state, value) {
  1173. const onceWrapper = once();
  1174. if (promise === value) {
  1175. throw new TypeError(TYPE_ERROR);
  1176. }
  1177. if (promise[symbolState] === UNRESOLVED) {
  1178. // should only get value.then once based on promise spec.
  1179. let then = null;
  1180. try {
  1181. if (typeof value === 'object' || typeof value === 'function') {
  1182. then = value && value.then;
  1183. }
  1184. }
  1185. catch (err) {
  1186. onceWrapper(() => {
  1187. resolvePromise(promise, false, err);
  1188. })();
  1189. return promise;
  1190. }
  1191. // if (value instanceof ZoneAwarePromise) {
  1192. if (state !== REJECTED && value instanceof ZoneAwarePromise &&
  1193. value.hasOwnProperty(symbolState) && value.hasOwnProperty(symbolValue) &&
  1194. value[symbolState] !== UNRESOLVED) {
  1195. clearRejectedNoCatch(value);
  1196. resolvePromise(promise, value[symbolState], value[symbolValue]);
  1197. }
  1198. else if (state !== REJECTED && typeof then === 'function') {
  1199. try {
  1200. then.call(value, onceWrapper(makeResolver(promise, state)), onceWrapper(makeResolver(promise, false)));
  1201. }
  1202. catch (err) {
  1203. onceWrapper(() => {
  1204. resolvePromise(promise, false, err);
  1205. })();
  1206. }
  1207. }
  1208. else {
  1209. promise[symbolState] = state;
  1210. const queue = promise[symbolValue];
  1211. promise[symbolValue] = value;
  1212. if (promise[symbolFinally] === symbolFinally) {
  1213. // the promise is generated by Promise.prototype.finally
  1214. if (state === RESOLVED) {
  1215. // the state is resolved, should ignore the value
  1216. // and use parent promise value
  1217. promise[symbolState] = promise[symbolParentPromiseState];
  1218. promise[symbolValue] = promise[symbolParentPromiseValue];
  1219. }
  1220. }
  1221. // record task information in value when error occurs, so we can
  1222. // do some additional work such as render longStackTrace
  1223. if (state === REJECTED && value instanceof Error) {
  1224. // check if longStackTraceZone is here
  1225. const trace = Zone.currentTask && Zone.currentTask.data &&
  1226. Zone.currentTask.data[creationTrace];
  1227. if (trace) {
  1228. // only keep the long stack trace into error when in longStackTraceZone
  1229. ObjectDefineProperty(value, CURRENT_TASK_TRACE_SYMBOL, { configurable: true, enumerable: false, writable: true, value: trace });
  1230. }
  1231. }
  1232. for (let i = 0; i < queue.length;) {
  1233. scheduleResolveOrReject(promise, queue[i++], queue[i++], queue[i++], queue[i++]);
  1234. }
  1235. if (queue.length == 0 && state == REJECTED) {
  1236. promise[symbolState] = REJECTED_NO_CATCH;
  1237. let uncaughtPromiseError = value;
  1238. try {
  1239. // Here we throws a new Error to print more readable error log
  1240. // and if the value is not an error, zone.js builds an `Error`
  1241. // Object here to attach the stack information.
  1242. throw new Error('Uncaught (in promise): ' + readableObjectToString(value) +
  1243. (value && value.stack ? '\n' + value.stack : ''));
  1244. }
  1245. catch (err) {
  1246. uncaughtPromiseError = err;
  1247. }
  1248. if (isDisableWrappingUncaughtPromiseRejection) {
  1249. // If disable wrapping uncaught promise reject
  1250. // use the value instead of wrapping it.
  1251. uncaughtPromiseError.throwOriginal = true;
  1252. }
  1253. uncaughtPromiseError.rejection = value;
  1254. uncaughtPromiseError.promise = promise;
  1255. uncaughtPromiseError.zone = Zone.current;
  1256. uncaughtPromiseError.task = Zone.currentTask;
  1257. _uncaughtPromiseErrors.push(uncaughtPromiseError);
  1258. api.scheduleMicroTask(); // to make sure that it is running
  1259. }
  1260. }
  1261. }
  1262. // Resolving an already resolved promise is a noop.
  1263. return promise;
  1264. }
  1265. const REJECTION_HANDLED_HANDLER = __symbol__('rejectionHandledHandler');
  1266. function clearRejectedNoCatch(promise) {
  1267. if (promise[symbolState] === REJECTED_NO_CATCH) {
  1268. // if the promise is rejected no catch status
  1269. // and queue.length > 0, means there is a error handler
  1270. // here to handle the rejected promise, we should trigger
  1271. // windows.rejectionhandled eventHandler or nodejs rejectionHandled
  1272. // eventHandler
  1273. try {
  1274. const handler = Zone[REJECTION_HANDLED_HANDLER];
  1275. if (handler && typeof handler === 'function') {
  1276. handler.call(this, { rejection: promise[symbolValue], promise: promise });
  1277. }
  1278. }
  1279. catch (err) {
  1280. }
  1281. promise[symbolState] = REJECTED;
  1282. for (let i = 0; i < _uncaughtPromiseErrors.length; i++) {
  1283. if (promise === _uncaughtPromiseErrors[i].promise) {
  1284. _uncaughtPromiseErrors.splice(i, 1);
  1285. }
  1286. }
  1287. }
  1288. }
  1289. function scheduleResolveOrReject(promise, zone, chainPromise, onFulfilled, onRejected) {
  1290. clearRejectedNoCatch(promise);
  1291. const promiseState = promise[symbolState];
  1292. const delegate = promiseState ?
  1293. (typeof onFulfilled === 'function') ? onFulfilled : forwardResolution :
  1294. (typeof onRejected === 'function') ? onRejected :
  1295. forwardRejection;
  1296. zone.scheduleMicroTask(source, () => {
  1297. try {
  1298. const parentPromiseValue = promise[symbolValue];
  1299. const isFinallyPromise = !!chainPromise && symbolFinally === chainPromise[symbolFinally];
  1300. if (isFinallyPromise) {
  1301. // if the promise is generated from finally call, keep parent promise's state and value
  1302. chainPromise[symbolParentPromiseValue] = parentPromiseValue;
  1303. chainPromise[symbolParentPromiseState] = promiseState;
  1304. }
  1305. // should not pass value to finally callback
  1306. const value = zone.run(delegate, undefined, isFinallyPromise && delegate !== forwardRejection && delegate !== forwardResolution ?
  1307. [] :
  1308. [parentPromiseValue]);
  1309. resolvePromise(chainPromise, true, value);
  1310. }
  1311. catch (error) {
  1312. // if error occurs, should always return this error
  1313. resolvePromise(chainPromise, false, error);
  1314. }
  1315. }, chainPromise);
  1316. }
  1317. const ZONE_AWARE_PROMISE_TO_STRING = 'function ZoneAwarePromise() { [native code] }';
  1318. const noop = function () { };
  1319. const AggregateError = global.AggregateError;
  1320. class ZoneAwarePromise {
  1321. static toString() {
  1322. return ZONE_AWARE_PROMISE_TO_STRING;
  1323. }
  1324. static resolve(value) {
  1325. return resolvePromise(new this(null), RESOLVED, value);
  1326. }
  1327. static reject(error) {
  1328. return resolvePromise(new this(null), REJECTED, error);
  1329. }
  1330. static any(values) {
  1331. if (!values || typeof values[Symbol.iterator] !== 'function') {
  1332. return Promise.reject(new AggregateError([], 'All promises were rejected'));
  1333. }
  1334. const promises = [];
  1335. let count = 0;
  1336. try {
  1337. for (let v of values) {
  1338. count++;
  1339. promises.push(ZoneAwarePromise.resolve(v));
  1340. }
  1341. }
  1342. catch (err) {
  1343. return Promise.reject(new AggregateError([], 'All promises were rejected'));
  1344. }
  1345. if (count === 0) {
  1346. return Promise.reject(new AggregateError([], 'All promises were rejected'));
  1347. }
  1348. let finished = false;
  1349. const errors = [];
  1350. return new ZoneAwarePromise((resolve, reject) => {
  1351. for (let i = 0; i < promises.length; i++) {
  1352. promises[i].then(v => {
  1353. if (finished) {
  1354. return;
  1355. }
  1356. finished = true;
  1357. resolve(v);
  1358. }, err => {
  1359. errors.push(err);
  1360. count--;
  1361. if (count === 0) {
  1362. finished = true;
  1363. reject(new AggregateError(errors, 'All promises were rejected'));
  1364. }
  1365. });
  1366. }
  1367. });
  1368. }
  1369. ;
  1370. static race(values) {
  1371. let resolve;
  1372. let reject;
  1373. let promise = new this((res, rej) => {
  1374. resolve = res;
  1375. reject = rej;
  1376. });
  1377. function onResolve(value) {
  1378. resolve(value);
  1379. }
  1380. function onReject(error) {
  1381. reject(error);
  1382. }
  1383. for (let value of values) {
  1384. if (!isThenable(value)) {
  1385. value = this.resolve(value);
  1386. }
  1387. value.then(onResolve, onReject);
  1388. }
  1389. return promise;
  1390. }
  1391. static all(values) {
  1392. return ZoneAwarePromise.allWithCallback(values);
  1393. }
  1394. static allSettled(values) {
  1395. const P = this && this.prototype instanceof ZoneAwarePromise ? this : ZoneAwarePromise;
  1396. return P.allWithCallback(values, {
  1397. thenCallback: (value) => ({ status: 'fulfilled', value }),
  1398. errorCallback: (err) => ({ status: 'rejected', reason: err })
  1399. });
  1400. }
  1401. static allWithCallback(values, callback) {
  1402. let resolve;
  1403. let reject;
  1404. let promise = new this((res, rej) => {
  1405. resolve = res;
  1406. reject = rej;
  1407. });
  1408. // Start at 2 to prevent prematurely resolving if .then is called immediately.
  1409. let unresolvedCount = 2;
  1410. let valueIndex = 0;
  1411. const resolvedValues = [];
  1412. for (let value of values) {
  1413. if (!isThenable(value)) {
  1414. value = this.resolve(value);
  1415. }
  1416. const curValueIndex = valueIndex;
  1417. try {
  1418. value.then((value) => {
  1419. resolvedValues[curValueIndex] = callback ? callback.thenCallback(value) : value;
  1420. unresolvedCount--;
  1421. if (unresolvedCount === 0) {
  1422. resolve(resolvedValues);
  1423. }
  1424. }, (err) => {
  1425. if (!callback) {
  1426. reject(err);
  1427. }
  1428. else {
  1429. resolvedValues[curValueIndex] = callback.errorCallback(err);
  1430. unresolvedCount--;
  1431. if (unresolvedCount === 0) {
  1432. resolve(resolvedValues);
  1433. }
  1434. }
  1435. });
  1436. }
  1437. catch (thenErr) {
  1438. reject(thenErr);
  1439. }
  1440. unresolvedCount++;
  1441. valueIndex++;
  1442. }
  1443. // Make the unresolvedCount zero-based again.
  1444. unresolvedCount -= 2;
  1445. if (unresolvedCount === 0) {
  1446. resolve(resolvedValues);
  1447. }
  1448. return promise;
  1449. }
  1450. constructor(executor) {
  1451. const promise = this;
  1452. if (!(promise instanceof ZoneAwarePromise)) {
  1453. throw new Error('Must be an instanceof Promise.');
  1454. }
  1455. promise[symbolState] = UNRESOLVED;
  1456. promise[symbolValue] = []; // queue;
  1457. try {
  1458. const onceWrapper = once();
  1459. executor &&
  1460. executor(onceWrapper(makeResolver(promise, RESOLVED)), onceWrapper(makeResolver(promise, REJECTED)));
  1461. }
  1462. catch (error) {
  1463. resolvePromise(promise, false, error);
  1464. }
  1465. }
  1466. get [Symbol.toStringTag]() {
  1467. return 'Promise';
  1468. }
  1469. get [Symbol.species]() {
  1470. return ZoneAwarePromise;
  1471. }
  1472. then(onFulfilled, onRejected) {
  1473. // We must read `Symbol.species` safely because `this` may be anything. For instance, `this`
  1474. // may be an object without a prototype (created through `Object.create(null)`); thus
  1475. // `this.constructor` will be undefined. One of the use cases is SystemJS creating
  1476. // prototype-less objects (modules) via `Object.create(null)`. The SystemJS creates an empty
  1477. // object and copies promise properties into that object (within the `getOrCreateLoad`
  1478. // function). The zone.js then checks if the resolved value has the `then` method and invokes
  1479. // it with the `value` context. Otherwise, this will throw an error: `TypeError: Cannot read
  1480. // properties of undefined (reading 'Symbol(Symbol.species)')`.
  1481. let C = this.constructor?.[Symbol.species];
  1482. if (!C || typeof C !== 'function') {
  1483. C = this.constructor || ZoneAwarePromise;
  1484. }
  1485. const chainPromise = new C(noop);
  1486. const zone = Zone.current;
  1487. if (this[symbolState] == UNRESOLVED) {
  1488. this[symbolValue].push(zone, chainPromise, onFulfilled, onRejected);
  1489. }
  1490. else {
  1491. scheduleResolveOrReject(this, zone, chainPromise, onFulfilled, onRejected);
  1492. }
  1493. return chainPromise;
  1494. }
  1495. catch(onRejected) {
  1496. return this.then(null, onRejected);
  1497. }
  1498. finally(onFinally) {
  1499. // See comment on the call to `then` about why thee `Symbol.species` is safely accessed.
  1500. let C = this.constructor?.[Symbol.species];
  1501. if (!C || typeof C !== 'function') {
  1502. C = ZoneAwarePromise;
  1503. }
  1504. const chainPromise = new C(noop);
  1505. chainPromise[symbolFinally] = symbolFinally;
  1506. const zone = Zone.current;
  1507. if (this[symbolState] == UNRESOLVED) {
  1508. this[symbolValue].push(zone, chainPromise, onFinally, onFinally);
  1509. }
  1510. else {
  1511. scheduleResolveOrReject(this, zone, chainPromise, onFinally, onFinally);
  1512. }
  1513. return chainPromise;
  1514. }
  1515. }
  1516. // Protect against aggressive optimizers dropping seemingly unused properties.
  1517. // E.g. Closure Compiler in advanced mode.
  1518. ZoneAwarePromise['resolve'] = ZoneAwarePromise.resolve;
  1519. ZoneAwarePromise['reject'] = ZoneAwarePromise.reject;
  1520. ZoneAwarePromise['race'] = ZoneAwarePromise.race;
  1521. ZoneAwarePromise['all'] = ZoneAwarePromise.all;
  1522. const NativePromise = global[symbolPromise] = global['Promise'];
  1523. global['Promise'] = ZoneAwarePromise;
  1524. const symbolThenPatched = __symbol__('thenPatched');
  1525. function patchThen(Ctor) {
  1526. const proto = Ctor.prototype;
  1527. const prop = ObjectGetOwnPropertyDescriptor(proto, 'then');
  1528. if (prop && (prop.writable === false || !prop.configurable)) {
  1529. // check Ctor.prototype.then propertyDescriptor is writable or not
  1530. // in meteor env, writable is false, we should ignore such case
  1531. return;
  1532. }
  1533. const originalThen = proto.then;
  1534. // Keep a reference to the original method.
  1535. proto[symbolThen] = originalThen;
  1536. Ctor.prototype.then = function (onResolve, onReject) {
  1537. const wrapped = new ZoneAwarePromise((resolve, reject) => {
  1538. originalThen.call(this, resolve, reject);
  1539. });
  1540. return wrapped.then(onResolve, onReject);
  1541. };
  1542. Ctor[symbolThenPatched] = true;
  1543. }
  1544. api.patchThen = patchThen;
  1545. function zoneify(fn) {
  1546. return function (self, args) {
  1547. let resultPromise = fn.apply(self, args);
  1548. if (resultPromise instanceof ZoneAwarePromise) {
  1549. return resultPromise;
  1550. }
  1551. let ctor = resultPromise.constructor;
  1552. if (!ctor[symbolThenPatched]) {
  1553. patchThen(ctor);
  1554. }
  1555. return resultPromise;
  1556. };
  1557. }
  1558. if (NativePromise) {
  1559. patchThen(NativePromise);
  1560. patchMethod(global, 'fetch', delegate => zoneify(delegate));
  1561. }
  1562. // This is not part of public API, but it is useful for tests, so we expose it.
  1563. Promise[Zone.__symbol__('uncaughtPromiseErrors')] = _uncaughtPromiseErrors;
  1564. return ZoneAwarePromise;
  1565. });
  1566. // override Function.prototype.toString to make zone.js patched function
  1567. // look like native function
  1568. Zone.__load_patch('toString', (global) => {
  1569. // patch Func.prototype.toString to let them look like native
  1570. const originalFunctionToString = Function.prototype.toString;
  1571. const ORIGINAL_DELEGATE_SYMBOL = zoneSymbol('OriginalDelegate');
  1572. const PROMISE_SYMBOL = zoneSymbol('Promise');
  1573. const ERROR_SYMBOL = zoneSymbol('Error');
  1574. const newFunctionToString = function toString() {
  1575. if (typeof this === 'function') {
  1576. const originalDelegate = this[ORIGINAL_DELEGATE_SYMBOL];
  1577. if (originalDelegate) {
  1578. if (typeof originalDelegate === 'function') {
  1579. return originalFunctionToString.call(originalDelegate);
  1580. }
  1581. else {
  1582. return Object.prototype.toString.call(originalDelegate);
  1583. }
  1584. }
  1585. if (this === Promise) {
  1586. const nativePromise = global[PROMISE_SYMBOL];
  1587. if (nativePromise) {
  1588. return originalFunctionToString.call(nativePromise);
  1589. }
  1590. }
  1591. if (this === Error) {
  1592. const nativeError = global[ERROR_SYMBOL];
  1593. if (nativeError) {
  1594. return originalFunctionToString.call(nativeError);
  1595. }
  1596. }
  1597. }
  1598. return originalFunctionToString.call(this);
  1599. };
  1600. newFunctionToString[ORIGINAL_DELEGATE_SYMBOL] = originalFunctionToString;
  1601. Function.prototype.toString = newFunctionToString;
  1602. // patch Object.prototype.toString to let them look like native
  1603. const originalObjectToString = Object.prototype.toString;
  1604. const PROMISE_OBJECT_TO_STRING = '[object Promise]';
  1605. Object.prototype.toString = function () {
  1606. if (typeof Promise === 'function' && this instanceof Promise) {
  1607. return PROMISE_OBJECT_TO_STRING;
  1608. }
  1609. return originalObjectToString.call(this);
  1610. };
  1611. });
  1612. /**
  1613. * @fileoverview
  1614. * @suppress {missingRequire}
  1615. */
  1616. let passiveSupported = false;
  1617. if (typeof window !== 'undefined') {
  1618. try {
  1619. const options = Object.defineProperty({}, 'passive', {
  1620. get: function () {
  1621. passiveSupported = true;
  1622. }
  1623. });
  1624. // Note: We pass the `options` object as the event handler too. This is not compatible with the
  1625. // signature of `addEventListener` or `removeEventListener` but enables us to remove the handler
  1626. // without an actual handler.
  1627. window.addEventListener('test', options, options);
  1628. window.removeEventListener('test', options, options);
  1629. }
  1630. catch (err) {
  1631. passiveSupported = false;
  1632. }
  1633. }
  1634. // an identifier to tell ZoneTask do not create a new invoke closure
  1635. const OPTIMIZED_ZONE_EVENT_TASK_DATA = {
  1636. useG: true
  1637. };
  1638. const zoneSymbolEventNames = {};
  1639. const globalSources = {};
  1640. const EVENT_NAME_SYMBOL_REGX = new RegExp('^' + ZONE_SYMBOL_PREFIX + '(\\w+)(true|false)$');
  1641. const IMMEDIATE_PROPAGATION_SYMBOL = zoneSymbol('propagationStopped');
  1642. function prepareEventNames(eventName, eventNameToString) {
  1643. const falseEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + FALSE_STR;
  1644. const trueEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + TRUE_STR;
  1645. const symbol = ZONE_SYMBOL_PREFIX + falseEventName;
  1646. const symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
  1647. zoneSymbolEventNames[eventName] = {};
  1648. zoneSymbolEventNames[eventName][FALSE_STR] = symbol;
  1649. zoneSymbolEventNames[eventName][TRUE_STR] = symbolCapture;
  1650. }
  1651. function patchEventTarget(_global, api, apis, patchOptions) {
  1652. const ADD_EVENT_LISTENER = (patchOptions && patchOptions.add) || ADD_EVENT_LISTENER_STR;
  1653. const REMOVE_EVENT_LISTENER = (patchOptions && patchOptions.rm) || REMOVE_EVENT_LISTENER_STR;
  1654. const LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.listeners) || 'eventListeners';
  1655. const REMOVE_ALL_LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.rmAll) || 'removeAllListeners';
  1656. const zoneSymbolAddEventListener = zoneSymbol(ADD_EVENT_LISTENER);
  1657. const ADD_EVENT_LISTENER_SOURCE = '.' + ADD_EVENT_LISTENER + ':';
  1658. const PREPEND_EVENT_LISTENER = 'prependListener';
  1659. const PREPEND_EVENT_LISTENER_SOURCE = '.' + PREPEND_EVENT_LISTENER + ':';
  1660. const invokeTask = function (task, target, event) {
  1661. // for better performance, check isRemoved which is set
  1662. // by removeEventListener
  1663. if (task.isRemoved) {
  1664. return;
  1665. }
  1666. const delegate = task.callback;
  1667. if (typeof delegate === 'object' && delegate.handleEvent) {
  1668. // create the bind version of handleEvent when invoke
  1669. task.callback = (event) => delegate.handleEvent(event);
  1670. task.originalDelegate = delegate;
  1671. }
  1672. // invoke static task.invoke
  1673. // need to try/catch error here, otherwise, the error in one event listener
  1674. // will break the executions of the other event listeners. Also error will
  1675. // not remove the event listener when `once` options is true.
  1676. let error;
  1677. try {
  1678. task.invoke(task, target, [event]);
  1679. }
  1680. catch (err) {
  1681. error = err;
  1682. }
  1683. const options = task.options;
  1684. if (options && typeof options === 'object' && options.once) {
  1685. // if options.once is true, after invoke once remove listener here
  1686. // only browser need to do this, nodejs eventEmitter will cal removeListener
  1687. // inside EventEmitter.once
  1688. const delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  1689. target[REMOVE_EVENT_LISTENER].call(target, event.type, delegate, options);
  1690. }
  1691. return error;
  1692. };
  1693. function globalCallback(context, event, isCapture) {
  1694. // https://github.com/angular/zone.js/issues/911, in IE, sometimes
  1695. // event will be undefined, so we need to use window.event
  1696. event = event || _global.event;
  1697. if (!event) {
  1698. return;
  1699. }
  1700. // event.target is needed for Samsung TV and SourceBuffer
  1701. // || global is needed https://github.com/angular/zone.js/issues/190
  1702. const target = context || event.target || _global;
  1703. const tasks = target[zoneSymbolEventNames[event.type][isCapture ? TRUE_STR : FALSE_STR]];
  1704. if (tasks) {
  1705. const errors = [];
  1706. // invoke all tasks which attached to current target with given event.type and capture = false
  1707. // for performance concern, if task.length === 1, just invoke
  1708. if (tasks.length === 1) {
  1709. const err = invokeTask(tasks[0], target, event);
  1710. err && errors.push(err);
  1711. }
  1712. else {
  1713. // https://github.com/angular/zone.js/issues/836
  1714. // copy the tasks array before invoke, to avoid
  1715. // the callback will remove itself or other listener
  1716. const copyTasks = tasks.slice();
  1717. for (let i = 0; i < copyTasks.length; i++) {
  1718. if (event && event[IMMEDIATE_PROPAGATION_SYMBOL] === true) {
  1719. break;
  1720. }
  1721. const err = invokeTask(copyTasks[i], target, event);
  1722. err && errors.push(err);
  1723. }
  1724. }
  1725. // Since there is only one error, we don't need to schedule microTask
  1726. // to throw the error.
  1727. if (errors.length === 1) {
  1728. throw errors[0];
  1729. }
  1730. else {
  1731. for (let i = 0; i < errors.length; i++) {
  1732. const err = errors[i];
  1733. api.nativeScheduleMicroTask(() => {
  1734. throw err;
  1735. });
  1736. }
  1737. }
  1738. }
  1739. }
  1740. // global shared zoneAwareCallback to handle all event callback with capture = false
  1741. const globalZoneAwareCallback = function (event) {
  1742. return globalCallback(this, event, false);
  1743. };
  1744. // global shared zoneAwareCallback to handle all event callback with capture = true
  1745. const globalZoneAwareCaptureCallback = function (event) {
  1746. return globalCallback(this, event, true);
  1747. };
  1748. function patchEventTargetMethods(obj, patchOptions) {
  1749. if (!obj) {
  1750. return false;
  1751. }
  1752. let useGlobalCallback = true;
  1753. if (patchOptions && patchOptions.useG !== undefined) {
  1754. useGlobalCallback = patchOptions.useG;
  1755. }
  1756. const validateHandler = patchOptions && patchOptions.vh;
  1757. let checkDuplicate = true;
  1758. if (patchOptions && patchOptions.chkDup !== undefined) {
  1759. checkDuplicate = patchOptions.chkDup;
  1760. }
  1761. let returnTarget = false;
  1762. if (patchOptions && patchOptions.rt !== undefined) {
  1763. returnTarget = patchOptions.rt;
  1764. }
  1765. let proto = obj;
  1766. while (proto && !proto.hasOwnProperty(ADD_EVENT_LISTENER)) {
  1767. proto = ObjectGetPrototypeOf(proto);
  1768. }
  1769. if (!proto && obj[ADD_EVENT_LISTENER]) {
  1770. // somehow we did not find it, but we can see it. This happens on IE for Window properties.
  1771. proto = obj;
  1772. }
  1773. if (!proto) {
  1774. return false;
  1775. }
  1776. if (proto[zoneSymbolAddEventListener]) {
  1777. return false;
  1778. }
  1779. const eventNameToString = patchOptions && patchOptions.eventNameToString;
  1780. // a shared global taskData to pass data for scheduleEventTask
  1781. // so we do not need to create a new object just for pass some data
  1782. const taskData = {};
  1783. const nativeAddEventListener = proto[zoneSymbolAddEventListener] = proto[ADD_EVENT_LISTENER];
  1784. const nativeRemoveEventListener = proto[zoneSymbol(REMOVE_EVENT_LISTENER)] =
  1785. proto[REMOVE_EVENT_LISTENER];
  1786. const nativeListeners = proto[zoneSymbol(LISTENERS_EVENT_LISTENER)] =
  1787. proto[LISTENERS_EVENT_LISTENER];
  1788. const nativeRemoveAllListeners = proto[zoneSymbol(REMOVE_ALL_LISTENERS_EVENT_LISTENER)] =
  1789. proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER];
  1790. let nativePrependEventListener;
  1791. if (patchOptions && patchOptions.prepend) {
  1792. nativePrependEventListener = proto[zoneSymbol(patchOptions.prepend)] =
  1793. proto[patchOptions.prepend];
  1794. }
  1795. /**
  1796. * This util function will build an option object with passive option
  1797. * to handle all possible input from the user.
  1798. */
  1799. function buildEventListenerOptions(options, passive) {
  1800. if (!passiveSupported && typeof options === 'object' && options) {
  1801. // doesn't support passive but user want to pass an object as options.
  1802. // this will not work on some old browser, so we just pass a boolean
  1803. // as useCapture parameter
  1804. return !!options.capture;
  1805. }
  1806. if (!passiveSupported || !passive) {
  1807. return options;
  1808. }
  1809. if (typeof options === 'boolean') {
  1810. return { capture: options, passive: true };
  1811. }
  1812. if (!options) {
  1813. return { passive: true };
  1814. }
  1815. if (typeof options === 'object' && options.passive !== false) {
  1816. return { ...options, passive: true };
  1817. }
  1818. return options;
  1819. }
  1820. const customScheduleGlobal = function (task) {
  1821. // if there is already a task for the eventName + capture,
  1822. // just return, because we use the shared globalZoneAwareCallback here.
  1823. if (taskData.isExisting) {
  1824. return;
  1825. }
  1826. return nativeAddEventListener.call(taskData.target, taskData.eventName, taskData.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, taskData.options);
  1827. };
  1828. const customCancelGlobal = function (task) {
  1829. // if task is not marked as isRemoved, this call is directly
  1830. // from Zone.prototype.cancelTask, we should remove the task
  1831. // from tasksList of target first
  1832. if (!task.isRemoved) {
  1833. const symbolEventNames = zoneSymbolEventNames[task.eventName];
  1834. let symbolEventName;
  1835. if (symbolEventNames) {
  1836. symbolEventName = symbolEventNames[task.capture ? TRUE_STR : FALSE_STR];
  1837. }
  1838. const existingTasks = symbolEventName && task.target[symbolEventName];
  1839. if (existingTasks) {
  1840. for (let i = 0; i < existingTasks.length; i++) {
  1841. const existingTask = existingTasks[i];
  1842. if (existingTask === task) {
  1843. existingTasks.splice(i, 1);
  1844. // set isRemoved to data for faster invokeTask check
  1845. task.isRemoved = true;
  1846. if (existingTasks.length === 0) {
  1847. // all tasks for the eventName + capture have gone,
  1848. // remove globalZoneAwareCallback and remove the task cache from target
  1849. task.allRemoved = true;
  1850. task.target[symbolEventName] = null;
  1851. }
  1852. break;
  1853. }
  1854. }
  1855. }
  1856. }
  1857. // if all tasks for the eventName + capture have gone,
  1858. // we will really remove the global event callback,
  1859. // if not, return
  1860. if (!task.allRemoved) {
  1861. return;
  1862. }
  1863. return nativeRemoveEventListener.call(task.target, task.eventName, task.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, task.options);
  1864. };
  1865. const customScheduleNonGlobal = function (task) {
  1866. return nativeAddEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
  1867. };
  1868. const customSchedulePrepend = function (task) {
  1869. return nativePrependEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
  1870. };
  1871. const customCancelNonGlobal = function (task) {
  1872. return nativeRemoveEventListener.call(task.target, task.eventName, task.invoke, task.options);
  1873. };
  1874. const customSchedule = useGlobalCallback ? customScheduleGlobal : customScheduleNonGlobal;
  1875. const customCancel = useGlobalCallback ? customCancelGlobal : customCancelNonGlobal;
  1876. const compareTaskCallbackVsDelegate = function (task, delegate) {
  1877. const typeOfDelegate = typeof delegate;
  1878. return (typeOfDelegate === 'function' && task.callback === delegate) ||
  1879. (typeOfDelegate === 'object' && task.originalDelegate === delegate);
  1880. };
  1881. const compare = (patchOptions && patchOptions.diff) ? patchOptions.diff : compareTaskCallbackVsDelegate;
  1882. const unpatchedEvents = Zone[zoneSymbol('UNPATCHED_EVENTS')];
  1883. const passiveEvents = _global[zoneSymbol('PASSIVE_EVENTS')];
  1884. const makeAddListener = function (nativeListener, addSource, customScheduleFn, customCancelFn, returnTarget = false, prepend = false) {
  1885. return function () {
  1886. const target = this || _global;
  1887. let eventName = arguments[0];
  1888. if (patchOptions && patchOptions.transferEventName) {
  1889. eventName = patchOptions.transferEventName(eventName);
  1890. }
  1891. let delegate = arguments[1];
  1892. if (!delegate) {
  1893. return nativeListener.apply(this, arguments);
  1894. }
  1895. if (isNode && eventName === 'uncaughtException') {
  1896. // don't patch uncaughtException of nodejs to prevent endless loop
  1897. return nativeListener.apply(this, arguments);
  1898. }
  1899. // don't create the bind delegate function for handleEvent
  1900. // case here to improve addEventListener performance
  1901. // we will create the bind delegate when invoke
  1902. let isHandleEvent = false;
  1903. if (typeof delegate !== 'function') {
  1904. if (!delegate.handleEvent) {
  1905. return nativeListener.apply(this, arguments);
  1906. }
  1907. isHandleEvent = true;
  1908. }
  1909. if (validateHandler && !validateHandler(nativeListener, delegate, target, arguments)) {
  1910. return;
  1911. }
  1912. const passive = passiveSupported && !!passiveEvents && passiveEvents.indexOf(eventName) !== -1;
  1913. const options = buildEventListenerOptions(arguments[2], passive);
  1914. if (unpatchedEvents) {
  1915. // check unpatched list
  1916. for (let i = 0; i < unpatchedEvents.length; i++) {
  1917. if (eventName === unpatchedEvents[i]) {
  1918. if (passive) {
  1919. return nativeListener.call(target, eventName, delegate, options);
  1920. }
  1921. else {
  1922. return nativeListener.apply(this, arguments);
  1923. }
  1924. }
  1925. }
  1926. }
  1927. const capture = !options ? false : typeof options === 'boolean' ? true : options.capture;
  1928. const once = options && typeof options === 'object' ? options.once : false;
  1929. const zone = Zone.current;
  1930. let symbolEventNames = zoneSymbolEventNames[eventName];
  1931. if (!symbolEventNames) {
  1932. prepareEventNames(eventName, eventNameToString);
  1933. symbolEventNames = zoneSymbolEventNames[eventName];
  1934. }
  1935. const symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
  1936. let existingTasks = target[symbolEventName];
  1937. let isExisting = false;
  1938. if (existingTasks) {
  1939. // already have task registered
  1940. isExisting = true;
  1941. if (checkDuplicate) {
  1942. for (let i = 0; i < existingTasks.length; i++) {
  1943. if (compare(existingTasks[i], delegate)) {
  1944. // same callback, same capture, same event name, just return
  1945. return;
  1946. }
  1947. }
  1948. }
  1949. }
  1950. else {
  1951. existingTasks = target[symbolEventName] = [];
  1952. }
  1953. let source;
  1954. const constructorName = target.constructor['name'];
  1955. const targetSource = globalSources[constructorName];
  1956. if (targetSource) {
  1957. source = targetSource[eventName];
  1958. }
  1959. if (!source) {
  1960. source = constructorName + addSource +
  1961. (eventNameToString ? eventNameToString(eventName) : eventName);
  1962. }
  1963. // do not create a new object as task.data to pass those things
  1964. // just use the global shared one
  1965. taskData.options = options;
  1966. if (once) {
  1967. // if addEventListener with once options, we don't pass it to
  1968. // native addEventListener, instead we keep the once setting
  1969. // and handle ourselves.
  1970. taskData.options.once = false;
  1971. }
  1972. taskData.target = target;
  1973. taskData.capture = capture;
  1974. taskData.eventName = eventName;
  1975. taskData.isExisting = isExisting;
  1976. const data = useGlobalCallback ? OPTIMIZED_ZONE_EVENT_TASK_DATA : undefined;
  1977. // keep taskData into data to allow onScheduleEventTask to access the task information
  1978. if (data) {
  1979. data.taskData = taskData;
  1980. }
  1981. const task = zone.scheduleEventTask(source, delegate, data, customScheduleFn, customCancelFn);
  1982. // should clear taskData.target to avoid memory leak
  1983. // issue, https://github.com/angular/angular/issues/20442
  1984. taskData.target = null;
  1985. // need to clear up taskData because it is a global object
  1986. if (data) {
  1987. data.taskData = null;
  1988. }
  1989. // have to save those information to task in case
  1990. // application may call task.zone.cancelTask() directly
  1991. if (once) {
  1992. options.once = true;
  1993. }
  1994. if (!(!passiveSupported && typeof task.options === 'boolean')) {
  1995. // if not support passive, and we pass an option object
  1996. // to addEventListener, we should save the options to task
  1997. task.options = options;
  1998. }
  1999. task.target = target;
  2000. task.capture = capture;
  2001. task.eventName = eventName;
  2002. if (isHandleEvent) {
  2003. // save original delegate for compare to check duplicate
  2004. task.originalDelegate = delegate;
  2005. }
  2006. if (!prepend) {
  2007. existingTasks.push(task);
  2008. }
  2009. else {
  2010. existingTasks.unshift(task);
  2011. }
  2012. if (returnTarget) {
  2013. return target;
  2014. }
  2015. };
  2016. };
  2017. proto[ADD_EVENT_LISTENER] = makeAddListener(nativeAddEventListener, ADD_EVENT_LISTENER_SOURCE, customSchedule, customCancel, returnTarget);
  2018. if (nativePrependEventListener) {
  2019. proto[PREPEND_EVENT_LISTENER] = makeAddListener(nativePrependEventListener, PREPEND_EVENT_LISTENER_SOURCE, customSchedulePrepend, customCancel, returnTarget, true);
  2020. }
  2021. proto[REMOVE_EVENT_LISTENER] = function () {
  2022. const target = this || _global;
  2023. let eventName = arguments[0];
  2024. if (patchOptions && patchOptions.transferEventName) {
  2025. eventName = patchOptions.transferEventName(eventName);
  2026. }
  2027. const options = arguments[2];
  2028. const capture = !options ? false : typeof options === 'boolean' ? true : options.capture;
  2029. const delegate = arguments[1];
  2030. if (!delegate) {
  2031. return nativeRemoveEventListener.apply(this, arguments);
  2032. }
  2033. if (validateHandler &&
  2034. !validateHandler(nativeRemoveEventListener, delegate, target, arguments)) {
  2035. return;
  2036. }
  2037. const symbolEventNames = zoneSymbolEventNames[eventName];
  2038. let symbolEventName;
  2039. if (symbolEventNames) {
  2040. symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
  2041. }
  2042. const existingTasks = symbolEventName && target[symbolEventName];
  2043. if (existingTasks) {
  2044. for (let i = 0; i < existingTasks.length; i++) {
  2045. const existingTask = existingTasks[i];
  2046. if (compare(existingTask, delegate)) {
  2047. existingTasks.splice(i, 1);
  2048. // set isRemoved to data for faster invokeTask check
  2049. existingTask.isRemoved = true;
  2050. if (existingTasks.length === 0) {
  2051. // all tasks for the eventName + capture have gone,
  2052. // remove globalZoneAwareCallback and remove the task cache from target
  2053. existingTask.allRemoved = true;
  2054. target[symbolEventName] = null;
  2055. // in the target, we have an event listener which is added by on_property
  2056. // such as target.onclick = function() {}, so we need to clear this internal
  2057. // property too if all delegates all removed
  2058. if (typeof eventName === 'string') {
  2059. const onPropertySymbol = ZONE_SYMBOL_PREFIX + 'ON_PROPERTY' + eventName;
  2060. target[onPropertySymbol] = null;
  2061. }
  2062. }
  2063. existingTask.zone.cancelTask(existingTask);
  2064. if (returnTarget) {
  2065. return target;
  2066. }
  2067. return;
  2068. }
  2069. }
  2070. }
  2071. // issue 930, didn't find the event name or callback
  2072. // from zone kept existingTasks, the callback maybe
  2073. // added outside of zone, we need to call native removeEventListener
  2074. // to try to remove it.
  2075. return nativeRemoveEventListener.apply(this, arguments);
  2076. };
  2077. proto[LISTENERS_EVENT_LISTENER] = function () {
  2078. const target = this || _global;
  2079. let eventName = arguments[0];
  2080. if (patchOptions && patchOptions.transferEventName) {
  2081. eventName = patchOptions.transferEventName(eventName);
  2082. }
  2083. const listeners = [];
  2084. const tasks = findEventTasks(target, eventNameToString ? eventNameToString(eventName) : eventName);
  2085. for (let i = 0; i < tasks.length; i++) {
  2086. const task = tasks[i];
  2087. let delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  2088. listeners.push(delegate);
  2089. }
  2090. return listeners;
  2091. };
  2092. proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER] = function () {
  2093. const target = this || _global;
  2094. let eventName = arguments[0];
  2095. if (!eventName) {
  2096. const keys = Object.keys(target);
  2097. for (let i = 0; i < keys.length; i++) {
  2098. const prop = keys[i];
  2099. const match = EVENT_NAME_SYMBOL_REGX.exec(prop);
  2100. let evtName = match && match[1];
  2101. // in nodejs EventEmitter, removeListener event is
  2102. // used for monitoring the removeListener call,
  2103. // so just keep removeListener eventListener until
  2104. // all other eventListeners are removed
  2105. if (evtName && evtName !== 'removeListener') {
  2106. this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, evtName);
  2107. }
  2108. }
  2109. // remove removeListener listener finally
  2110. this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, 'removeListener');
  2111. }
  2112. else {
  2113. if (patchOptions && patchOptions.transferEventName) {
  2114. eventName = patchOptions.transferEventName(eventName);
  2115. }
  2116. const symbolEventNames = zoneSymbolEventNames[eventName];
  2117. if (symbolEventNames) {
  2118. const symbolEventName = symbolEventNames[FALSE_STR];
  2119. const symbolCaptureEventName = symbolEventNames[TRUE_STR];
  2120. const tasks = target[symbolEventName];
  2121. const captureTasks = target[symbolCaptureEventName];
  2122. if (tasks) {
  2123. const removeTasks = tasks.slice();
  2124. for (let i = 0; i < removeTasks.length; i++) {
  2125. const task = removeTasks[i];
  2126. let delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  2127. this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
  2128. }
  2129. }
  2130. if (captureTasks) {
  2131. const removeTasks = captureTasks.slice();
  2132. for (let i = 0; i < removeTasks.length; i++) {
  2133. const task = removeTasks[i];
  2134. let delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  2135. this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
  2136. }
  2137. }
  2138. }
  2139. }
  2140. if (returnTarget) {
  2141. return this;
  2142. }
  2143. };
  2144. // for native toString patch
  2145. attachOriginToPatched(proto[ADD_EVENT_LISTENER], nativeAddEventListener);
  2146. attachOriginToPatched(proto[REMOVE_EVENT_LISTENER], nativeRemoveEventListener);
  2147. if (nativeRemoveAllListeners) {
  2148. attachOriginToPatched(proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER], nativeRemoveAllListeners);
  2149. }
  2150. if (nativeListeners) {
  2151. attachOriginToPatched(proto[LISTENERS_EVENT_LISTENER], nativeListeners);
  2152. }
  2153. return true;
  2154. }
  2155. let results = [];
  2156. for (let i = 0; i < apis.length; i++) {
  2157. results[i] = patchEventTargetMethods(apis[i], patchOptions);
  2158. }
  2159. return results;
  2160. }
  2161. function findEventTasks(target, eventName) {
  2162. if (!eventName) {
  2163. const foundTasks = [];
  2164. for (let prop in target) {
  2165. const match = EVENT_NAME_SYMBOL_REGX.exec(prop);
  2166. let evtName = match && match[1];
  2167. if (evtName && (!eventName || evtName === eventName)) {
  2168. const tasks = target[prop];
  2169. if (tasks) {
  2170. for (let i = 0; i < tasks.length; i++) {
  2171. foundTasks.push(tasks[i]);
  2172. }
  2173. }
  2174. }
  2175. }
  2176. return foundTasks;
  2177. }
  2178. let symbolEventName = zoneSymbolEventNames[eventName];
  2179. if (!symbolEventName) {
  2180. prepareEventNames(eventName);
  2181. symbolEventName = zoneSymbolEventNames[eventName];
  2182. }
  2183. const captureFalseTasks = target[symbolEventName[FALSE_STR]];
  2184. const captureTrueTasks = target[symbolEventName[TRUE_STR]];
  2185. if (!captureFalseTasks) {
  2186. return captureTrueTasks ? captureTrueTasks.slice() : [];
  2187. }
  2188. else {
  2189. return captureTrueTasks ? captureFalseTasks.concat(captureTrueTasks) :
  2190. captureFalseTasks.slice();
  2191. }
  2192. }
  2193. function patchEventPrototype(global, api) {
  2194. const Event = global['Event'];
  2195. if (Event && Event.prototype) {
  2196. api.patchMethod(Event.prototype, 'stopImmediatePropagation', (delegate) => function (self, args) {
  2197. self[IMMEDIATE_PROPAGATION_SYMBOL] = true;
  2198. // we need to call the native stopImmediatePropagation
  2199. // in case in some hybrid application, some part of
  2200. // application will be controlled by zone, some are not
  2201. delegate && delegate.apply(self, args);
  2202. });
  2203. }
  2204. }
  2205. function patchCallbacks(api, target, targetName, method, callbacks) {
  2206. const symbol = Zone.__symbol__(method);
  2207. if (target[symbol]) {
  2208. return;
  2209. }
  2210. const nativeDelegate = target[symbol] = target[method];
  2211. target[method] = function (name, opts, options) {
  2212. if (opts && opts.prototype) {
  2213. callbacks.forEach(function (callback) {
  2214. const source = `${targetName}.${method}::` + callback;
  2215. const prototype = opts.prototype;
  2216. // Note: the `patchCallbacks` is used for patching the `document.registerElement` and
  2217. // `customElements.define`. We explicitly wrap the patching code into try-catch since
  2218. // callbacks may be already patched by other web components frameworks (e.g. LWC), and they
  2219. // make those properties non-writable. This means that patching callback will throw an error
  2220. // `cannot assign to read-only property`. See this code as an example:
  2221. // https://github.com/salesforce/lwc/blob/master/packages/@lwc/engine-core/src/framework/base-bridge-element.ts#L180-L186
  2222. // We don't want to stop the application rendering if we couldn't patch some
  2223. // callback, e.g. `attributeChangedCallback`.
  2224. try {
  2225. if (prototype.hasOwnProperty(callback)) {
  2226. const descriptor = api.ObjectGetOwnPropertyDescriptor(prototype, callback);
  2227. if (descriptor && descriptor.value) {
  2228. descriptor.value = api.wrapWithCurrentZone(descriptor.value, source);
  2229. api._redefineProperty(opts.prototype, callback, descriptor);
  2230. }
  2231. else if (prototype[callback]) {
  2232. prototype[callback] = api.wrapWithCurrentZone(prototype[callback], source);
  2233. }
  2234. }
  2235. else if (prototype[callback]) {
  2236. prototype[callback] = api.wrapWithCurrentZone(prototype[callback], source);
  2237. }
  2238. }
  2239. catch {
  2240. // Note: we leave the catch block empty since there's no way to handle the error related
  2241. // to non-writable property.
  2242. }
  2243. });
  2244. }
  2245. return nativeDelegate.call(target, name, opts, options);
  2246. };
  2247. api.attachOriginToPatched(target[method], nativeDelegate);
  2248. }
  2249. /**
  2250. * @fileoverview
  2251. * @suppress {globalThis}
  2252. */
  2253. function filterProperties(target, onProperties, ignoreProperties) {
  2254. if (!ignoreProperties || ignoreProperties.length === 0) {
  2255. return onProperties;
  2256. }
  2257. const tip = ignoreProperties.filter(ip => ip.target === target);
  2258. if (!tip || tip.length === 0) {
  2259. return onProperties;
  2260. }
  2261. const targetIgnoreProperties = tip[0].ignoreProperties;
  2262. return onProperties.filter(op => targetIgnoreProperties.indexOf(op) === -1);
  2263. }
  2264. function patchFilteredProperties(target, onProperties, ignoreProperties, prototype) {
  2265. // check whether target is available, sometimes target will be undefined
  2266. // because different browser or some 3rd party plugin.
  2267. if (!target) {
  2268. return;
  2269. }
  2270. const filteredProperties = filterProperties(target, onProperties, ignoreProperties);
  2271. patchOnProperties(target, filteredProperties, prototype);
  2272. }
  2273. /**
  2274. * Get all event name properties which the event name startsWith `on`
  2275. * from the target object itself, inherited properties are not considered.
  2276. */
  2277. function getOnEventNames(target) {
  2278. return Object.getOwnPropertyNames(target)
  2279. .filter(name => name.startsWith('on') && name.length > 2)
  2280. .map(name => name.substring(2));
  2281. }
  2282. function propertyDescriptorPatch(api, _global) {
  2283. if (isNode && !isMix) {
  2284. return;
  2285. }
  2286. if (Zone[api.symbol('patchEvents')]) {
  2287. // events are already been patched by legacy patch.
  2288. return;
  2289. }
  2290. const ignoreProperties = _global['__Zone_ignore_on_properties'];
  2291. // for browsers that we can patch the descriptor: Chrome & Firefox
  2292. let patchTargets = [];
  2293. if (isBrowser) {
  2294. const internalWindow = window;
  2295. patchTargets = patchTargets.concat([
  2296. 'Document', 'SVGElement', 'Element', 'HTMLElement', 'HTMLBodyElement', 'HTMLMediaElement',
  2297. 'HTMLFrameSetElement', 'HTMLFrameElement', 'HTMLIFrameElement', 'HTMLMarqueeElement', 'Worker'
  2298. ]);
  2299. const ignoreErrorProperties = isIE() ? [{ target: internalWindow, ignoreProperties: ['error'] }] : [];
  2300. // in IE/Edge, onProp not exist in window object, but in WindowPrototype
  2301. // so we need to pass WindowPrototype to check onProp exist or not
  2302. patchFilteredProperties(internalWindow, getOnEventNames(internalWindow), ignoreProperties ? ignoreProperties.concat(ignoreErrorProperties) : ignoreProperties, ObjectGetPrototypeOf(internalWindow));
  2303. }
  2304. patchTargets = patchTargets.concat([
  2305. 'XMLHttpRequest', 'XMLHttpRequestEventTarget', 'IDBIndex', 'IDBRequest', 'IDBOpenDBRequest',
  2306. 'IDBDatabase', 'IDBTransaction', 'IDBCursor', 'WebSocket'
  2307. ]);
  2308. for (let i = 0; i < patchTargets.length; i++) {
  2309. const target = _global[patchTargets[i]];
  2310. target && target.prototype &&
  2311. patchFilteredProperties(target.prototype, getOnEventNames(target.prototype), ignoreProperties);
  2312. }
  2313. }
  2314. Zone.__load_patch('util', (global, Zone, api) => {
  2315. // Collect native event names by looking at properties
  2316. // on the global namespace, e.g. 'onclick'.
  2317. const eventNames = getOnEventNames(global);
  2318. api.patchOnProperties = patchOnProperties;
  2319. api.patchMethod = patchMethod;
  2320. api.bindArguments = bindArguments;
  2321. api.patchMacroTask = patchMacroTask;
  2322. // In earlier version of zone.js (<0.9.0), we use env name `__zone_symbol__BLACK_LISTED_EVENTS` to
  2323. // define which events will not be patched by `Zone.js`.
  2324. // In newer version (>=0.9.0), we change the env name to `__zone_symbol__UNPATCHED_EVENTS` to keep
  2325. // the name consistent with angular repo.
  2326. // The `__zone_symbol__BLACK_LISTED_EVENTS` is deprecated, but it is still be supported for
  2327. // backwards compatibility.
  2328. const SYMBOL_BLACK_LISTED_EVENTS = Zone.__symbol__('BLACK_LISTED_EVENTS');
  2329. const SYMBOL_UNPATCHED_EVENTS = Zone.__symbol__('UNPATCHED_EVENTS');
  2330. if (global[SYMBOL_UNPATCHED_EVENTS]) {
  2331. global[SYMBOL_BLACK_LISTED_EVENTS] = global[SYMBOL_UNPATCHED_EVENTS];
  2332. }
  2333. if (global[SYMBOL_BLACK_LISTED_EVENTS]) {
  2334. Zone[SYMBOL_BLACK_LISTED_EVENTS] = Zone[SYMBOL_UNPATCHED_EVENTS] =
  2335. global[SYMBOL_BLACK_LISTED_EVENTS];
  2336. }
  2337. api.patchEventPrototype = patchEventPrototype;
  2338. api.patchEventTarget = patchEventTarget;
  2339. api.isIEOrEdge = isIEOrEdge;
  2340. api.ObjectDefineProperty = ObjectDefineProperty;
  2341. api.ObjectGetOwnPropertyDescriptor = ObjectGetOwnPropertyDescriptor;
  2342. api.ObjectCreate = ObjectCreate;
  2343. api.ArraySlice = ArraySlice;
  2344. api.patchClass = patchClass;
  2345. api.wrapWithCurrentZone = wrapWithCurrentZone;
  2346. api.filterProperties = filterProperties;
  2347. api.attachOriginToPatched = attachOriginToPatched;
  2348. api._redefineProperty = Object.defineProperty;
  2349. api.patchCallbacks = patchCallbacks;
  2350. api.getGlobalObjects = () => ({
  2351. globalSources,
  2352. zoneSymbolEventNames,
  2353. eventNames,
  2354. isBrowser,
  2355. isMix,
  2356. isNode,
  2357. TRUE_STR,
  2358. FALSE_STR,
  2359. ZONE_SYMBOL_PREFIX,
  2360. ADD_EVENT_LISTENER_STR,
  2361. REMOVE_EVENT_LISTENER_STR
  2362. });
  2363. });
  2364. /**
  2365. * @fileoverview
  2366. * @suppress {missingRequire}
  2367. */
  2368. const taskSymbol = zoneSymbol('zoneTask');
  2369. function patchTimer(window, setName, cancelName, nameSuffix) {
  2370. let setNative = null;
  2371. let clearNative = null;
  2372. setName += nameSuffix;
  2373. cancelName += nameSuffix;
  2374. const tasksByHandleId = {};
  2375. function scheduleTask(task) {
  2376. const data = task.data;
  2377. data.args[0] = function () {
  2378. return task.invoke.apply(this, arguments);
  2379. };
  2380. data.handleId = setNative.apply(window, data.args);
  2381. return task;
  2382. }
  2383. function clearTask(task) {
  2384. return clearNative.call(window, task.data.handleId);
  2385. }
  2386. setNative =
  2387. patchMethod(window, setName, (delegate) => function (self, args) {
  2388. if (typeof args[0] === 'function') {
  2389. const options = {
  2390. isPeriodic: nameSuffix === 'Interval',
  2391. delay: (nameSuffix === 'Timeout' || nameSuffix === 'Interval') ? args[1] || 0 :
  2392. undefined,
  2393. args: args
  2394. };
  2395. const callback = args[0];
  2396. args[0] = function timer() {
  2397. try {
  2398. return callback.apply(this, arguments);
  2399. }
  2400. finally {
  2401. // issue-934, task will be cancelled
  2402. // even it is a periodic task such as
  2403. // setInterval
  2404. // https://github.com/angular/angular/issues/40387
  2405. // Cleanup tasksByHandleId should be handled before scheduleTask
  2406. // Since some zoneSpec may intercept and doesn't trigger
  2407. // scheduleFn(scheduleTask) provided here.
  2408. if (!(options.isPeriodic)) {
  2409. if (typeof options.handleId === 'number') {
  2410. // in non-nodejs env, we remove timerId
  2411. // from local cache
  2412. delete tasksByHandleId[options.handleId];
  2413. }
  2414. else if (options.handleId) {
  2415. // Node returns complex objects as handleIds
  2416. // we remove task reference from timer object
  2417. options.handleId[taskSymbol] = null;
  2418. }
  2419. }
  2420. }
  2421. };
  2422. const task = scheduleMacroTaskWithCurrentZone(setName, args[0], options, scheduleTask, clearTask);
  2423. if (!task) {
  2424. return task;
  2425. }
  2426. // Node.js must additionally support the ref and unref functions.
  2427. const handle = task.data.handleId;
  2428. if (typeof handle === 'number') {
  2429. // for non nodejs env, we save handleId: task
  2430. // mapping in local cache for clearTimeout
  2431. tasksByHandleId[handle] = task;
  2432. }
  2433. else if (handle) {
  2434. // for nodejs env, we save task
  2435. // reference in timerId Object for clearTimeout
  2436. handle[taskSymbol] = task;
  2437. }
  2438. // check whether handle is null, because some polyfill or browser
  2439. // may return undefined from setTimeout/setInterval/setImmediate/requestAnimationFrame
  2440. if (handle && handle.ref && handle.unref && typeof handle.ref === 'function' &&
  2441. typeof handle.unref === 'function') {
  2442. task.ref = handle.ref.bind(handle);
  2443. task.unref = handle.unref.bind(handle);
  2444. }
  2445. if (typeof handle === 'number' || handle) {
  2446. return handle;
  2447. }
  2448. return task;
  2449. }
  2450. else {
  2451. // cause an error by calling it directly.
  2452. return delegate.apply(window, args);
  2453. }
  2454. });
  2455. clearNative =
  2456. patchMethod(window, cancelName, (delegate) => function (self, args) {
  2457. const id = args[0];
  2458. let task;
  2459. if (typeof id === 'number') {
  2460. // non nodejs env.
  2461. task = tasksByHandleId[id];
  2462. }
  2463. else {
  2464. // nodejs env.
  2465. task = id && id[taskSymbol];
  2466. // other environments.
  2467. if (!task) {
  2468. task = id;
  2469. }
  2470. }
  2471. if (task && typeof task.type === 'string') {
  2472. if (task.state !== 'notScheduled' &&
  2473. (task.cancelFn && task.data.isPeriodic || task.runCount === 0)) {
  2474. if (typeof id === 'number') {
  2475. delete tasksByHandleId[id];
  2476. }
  2477. else if (id) {
  2478. id[taskSymbol] = null;
  2479. }
  2480. // Do not cancel already canceled functions
  2481. task.zone.cancelTask(task);
  2482. }
  2483. }
  2484. else {
  2485. // cause an error by calling it directly.
  2486. delegate.apply(window, args);
  2487. }
  2488. });
  2489. }
  2490. function patchCustomElements(_global, api) {
  2491. const { isBrowser, isMix } = api.getGlobalObjects();
  2492. if ((!isBrowser && !isMix) || !_global['customElements'] || !('customElements' in _global)) {
  2493. return;
  2494. }
  2495. const callbacks = ['connectedCallback', 'disconnectedCallback', 'adoptedCallback', 'attributeChangedCallback'];
  2496. api.patchCallbacks(api, _global.customElements, 'customElements', 'define', callbacks);
  2497. }
  2498. function eventTargetPatch(_global, api) {
  2499. if (Zone[api.symbol('patchEventTarget')]) {
  2500. // EventTarget is already patched.
  2501. return;
  2502. }
  2503. const { eventNames, zoneSymbolEventNames, TRUE_STR, FALSE_STR, ZONE_SYMBOL_PREFIX } = api.getGlobalObjects();
  2504. // predefine all __zone_symbol__ + eventName + true/false string
  2505. for (let i = 0; i < eventNames.length; i++) {
  2506. const eventName = eventNames[i];
  2507. const falseEventName = eventName + FALSE_STR;
  2508. const trueEventName = eventName + TRUE_STR;
  2509. const symbol = ZONE_SYMBOL_PREFIX + falseEventName;
  2510. const symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
  2511. zoneSymbolEventNames[eventName] = {};
  2512. zoneSymbolEventNames[eventName][FALSE_STR] = symbol;
  2513. zoneSymbolEventNames[eventName][TRUE_STR] = symbolCapture;
  2514. }
  2515. const EVENT_TARGET = _global['EventTarget'];
  2516. if (!EVENT_TARGET || !EVENT_TARGET.prototype) {
  2517. return;
  2518. }
  2519. api.patchEventTarget(_global, api, [EVENT_TARGET && EVENT_TARGET.prototype]);
  2520. return true;
  2521. }
  2522. function patchEvent(global, api) {
  2523. api.patchEventPrototype(global, api);
  2524. }
  2525. /**
  2526. * @fileoverview
  2527. * @suppress {missingRequire}
  2528. */
  2529. Zone.__load_patch('legacy', (global) => {
  2530. const legacyPatch = global[Zone.__symbol__('legacyPatch')];
  2531. if (legacyPatch) {
  2532. legacyPatch();
  2533. }
  2534. });
  2535. Zone.__load_patch('queueMicrotask', (global, Zone, api) => {
  2536. api.patchMethod(global, 'queueMicrotask', delegate => {
  2537. return function (self, args) {
  2538. Zone.current.scheduleMicroTask('queueMicrotask', args[0]);
  2539. };
  2540. });
  2541. });
  2542. Zone.__load_patch('timers', (global) => {
  2543. const set = 'set';
  2544. const clear = 'clear';
  2545. patchTimer(global, set, clear, 'Timeout');
  2546. patchTimer(global, set, clear, 'Interval');
  2547. patchTimer(global, set, clear, 'Immediate');
  2548. });
  2549. Zone.__load_patch('requestAnimationFrame', (global) => {
  2550. patchTimer(global, 'request', 'cancel', 'AnimationFrame');
  2551. patchTimer(global, 'mozRequest', 'mozCancel', 'AnimationFrame');
  2552. patchTimer(global, 'webkitRequest', 'webkitCancel', 'AnimationFrame');
  2553. });
  2554. Zone.__load_patch('blocking', (global, Zone) => {
  2555. const blockingMethods = ['alert', 'prompt', 'confirm'];
  2556. for (let i = 0; i < blockingMethods.length; i++) {
  2557. const name = blockingMethods[i];
  2558. patchMethod(global, name, (delegate, symbol, name) => {
  2559. return function (s, args) {
  2560. return Zone.current.run(delegate, global, args, name);
  2561. };
  2562. });
  2563. }
  2564. });
  2565. Zone.__load_patch('EventTarget', (global, Zone, api) => {
  2566. patchEvent(global, api);
  2567. eventTargetPatch(global, api);
  2568. // patch XMLHttpRequestEventTarget's addEventListener/removeEventListener
  2569. const XMLHttpRequestEventTarget = global['XMLHttpRequestEventTarget'];
  2570. if (XMLHttpRequestEventTarget && XMLHttpRequestEventTarget.prototype) {
  2571. api.patchEventTarget(global, api, [XMLHttpRequestEventTarget.prototype]);
  2572. }
  2573. });
  2574. Zone.__load_patch('MutationObserver', (global, Zone, api) => {
  2575. patchClass('MutationObserver');
  2576. patchClass('WebKitMutationObserver');
  2577. });
  2578. Zone.__load_patch('IntersectionObserver', (global, Zone, api) => {
  2579. patchClass('IntersectionObserver');
  2580. });
  2581. Zone.__load_patch('FileReader', (global, Zone, api) => {
  2582. patchClass('FileReader');
  2583. });
  2584. Zone.__load_patch('on_property', (global, Zone, api) => {
  2585. propertyDescriptorPatch(api, global);
  2586. });
  2587. Zone.__load_patch('customElements', (global, Zone, api) => {
  2588. patchCustomElements(global, api);
  2589. });
  2590. Zone.__load_patch('XHR', (global, Zone) => {
  2591. // Treat XMLHttpRequest as a macrotask.
  2592. patchXHR(global);
  2593. const XHR_TASK = zoneSymbol('xhrTask');
  2594. const XHR_SYNC = zoneSymbol('xhrSync');
  2595. const XHR_LISTENER = zoneSymbol('xhrListener');
  2596. const XHR_SCHEDULED = zoneSymbol('xhrScheduled');
  2597. const XHR_URL = zoneSymbol('xhrURL');
  2598. const XHR_ERROR_BEFORE_SCHEDULED = zoneSymbol('xhrErrorBeforeScheduled');
  2599. function patchXHR(window) {
  2600. const XMLHttpRequest = window['XMLHttpRequest'];
  2601. if (!XMLHttpRequest) {
  2602. // XMLHttpRequest is not available in service worker
  2603. return;
  2604. }
  2605. const XMLHttpRequestPrototype = XMLHttpRequest.prototype;
  2606. function findPendingTask(target) {
  2607. return target[XHR_TASK];
  2608. }
  2609. let oriAddListener = XMLHttpRequestPrototype[ZONE_SYMBOL_ADD_EVENT_LISTENER];
  2610. let oriRemoveListener = XMLHttpRequestPrototype[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
  2611. if (!oriAddListener) {
  2612. const XMLHttpRequestEventTarget = window['XMLHttpRequestEventTarget'];
  2613. if (XMLHttpRequestEventTarget) {
  2614. const XMLHttpRequestEventTargetPrototype = XMLHttpRequestEventTarget.prototype;
  2615. oriAddListener = XMLHttpRequestEventTargetPrototype[ZONE_SYMBOL_ADD_EVENT_LISTENER];
  2616. oriRemoveListener = XMLHttpRequestEventTargetPrototype[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
  2617. }
  2618. }
  2619. const READY_STATE_CHANGE = 'readystatechange';
  2620. const SCHEDULED = 'scheduled';
  2621. function scheduleTask(task) {
  2622. const data = task.data;
  2623. const target = data.target;
  2624. target[XHR_SCHEDULED] = false;
  2625. target[XHR_ERROR_BEFORE_SCHEDULED] = false;
  2626. // remove existing event listener
  2627. const listener = target[XHR_LISTENER];
  2628. if (!oriAddListener) {
  2629. oriAddListener = target[ZONE_SYMBOL_ADD_EVENT_LISTENER];
  2630. oriRemoveListener = target[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
  2631. }
  2632. if (listener) {
  2633. oriRemoveListener.call(target, READY_STATE_CHANGE, listener);
  2634. }
  2635. const newListener = target[XHR_LISTENER] = () => {
  2636. if (target.readyState === target.DONE) {
  2637. // sometimes on some browsers XMLHttpRequest will fire onreadystatechange with
  2638. // readyState=4 multiple times, so we need to check task state here
  2639. if (!data.aborted && target[XHR_SCHEDULED] && task.state === SCHEDULED) {
  2640. // check whether the xhr has registered onload listener
  2641. // if that is the case, the task should invoke after all
  2642. // onload listeners finish.
  2643. // Also if the request failed without response (status = 0), the load event handler
  2644. // will not be triggered, in that case, we should also invoke the placeholder callback
  2645. // to close the XMLHttpRequest::send macroTask.
  2646. // https://github.com/angular/angular/issues/38795
  2647. const loadTasks = target[Zone.__symbol__('loadfalse')];
  2648. if (target.status !== 0 && loadTasks && loadTasks.length > 0) {
  2649. const oriInvoke = task.invoke;
  2650. task.invoke = function () {
  2651. // need to load the tasks again, because in other
  2652. // load listener, they may remove themselves
  2653. const loadTasks = target[Zone.__symbol__('loadfalse')];
  2654. for (let i = 0; i < loadTasks.length; i++) {
  2655. if (loadTasks[i] === task) {
  2656. loadTasks.splice(i, 1);
  2657. }
  2658. }
  2659. if (!data.aborted && task.state === SCHEDULED) {
  2660. oriInvoke.call(task);
  2661. }
  2662. };
  2663. loadTasks.push(task);
  2664. }
  2665. else {
  2666. task.invoke();
  2667. }
  2668. }
  2669. else if (!data.aborted && target[XHR_SCHEDULED] === false) {
  2670. // error occurs when xhr.send()
  2671. target[XHR_ERROR_BEFORE_SCHEDULED] = true;
  2672. }
  2673. }
  2674. };
  2675. oriAddListener.call(target, READY_STATE_CHANGE, newListener);
  2676. const storedTask = target[XHR_TASK];
  2677. if (!storedTask) {
  2678. target[XHR_TASK] = task;
  2679. }
  2680. sendNative.apply(target, data.args);
  2681. target[XHR_SCHEDULED] = true;
  2682. return task;
  2683. }
  2684. function placeholderCallback() { }
  2685. function clearTask(task) {
  2686. const data = task.data;
  2687. // Note - ideally, we would call data.target.removeEventListener here, but it's too late
  2688. // to prevent it from firing. So instead, we store info for the event listener.
  2689. data.aborted = true;
  2690. return abortNative.apply(data.target, data.args);
  2691. }
  2692. const openNative = patchMethod(XMLHttpRequestPrototype, 'open', () => function (self, args) {
  2693. self[XHR_SYNC] = args[2] == false;
  2694. self[XHR_URL] = args[1];
  2695. return openNative.apply(self, args);
  2696. });
  2697. const XMLHTTPREQUEST_SOURCE = 'XMLHttpRequest.send';
  2698. const fetchTaskAborting = zoneSymbol('fetchTaskAborting');
  2699. const fetchTaskScheduling = zoneSymbol('fetchTaskScheduling');
  2700. const sendNative = patchMethod(XMLHttpRequestPrototype, 'send', () => function (self, args) {
  2701. if (Zone.current[fetchTaskScheduling] === true) {
  2702. // a fetch is scheduling, so we are using xhr to polyfill fetch
  2703. // and because we already schedule macroTask for fetch, we should
  2704. // not schedule a macroTask for xhr again
  2705. return sendNative.apply(self, args);
  2706. }
  2707. if (self[XHR_SYNC]) {
  2708. // if the XHR is sync there is no task to schedule, just execute the code.
  2709. return sendNative.apply(self, args);
  2710. }
  2711. else {
  2712. const options = { target: self, url: self[XHR_URL], isPeriodic: false, args: args, aborted: false };
  2713. const task = scheduleMacroTaskWithCurrentZone(XMLHTTPREQUEST_SOURCE, placeholderCallback, options, scheduleTask, clearTask);
  2714. if (self && self[XHR_ERROR_BEFORE_SCHEDULED] === true && !options.aborted &&
  2715. task.state === SCHEDULED) {
  2716. // xhr request throw error when send
  2717. // we should invoke task instead of leaving a scheduled
  2718. // pending macroTask
  2719. task.invoke();
  2720. }
  2721. }
  2722. });
  2723. const abortNative = patchMethod(XMLHttpRequestPrototype, 'abort', () => function (self, args) {
  2724. const task = findPendingTask(self);
  2725. if (task && typeof task.type == 'string') {
  2726. // If the XHR has already completed, do nothing.
  2727. // If the XHR has already been aborted, do nothing.
  2728. // Fix #569, call abort multiple times before done will cause
  2729. // macroTask task count be negative number
  2730. if (task.cancelFn == null || (task.data && task.data.aborted)) {
  2731. return;
  2732. }
  2733. task.zone.cancelTask(task);
  2734. }
  2735. else if (Zone.current[fetchTaskAborting] === true) {
  2736. // the abort is called from fetch polyfill, we need to call native abort of XHR.
  2737. return abortNative.apply(self, args);
  2738. }
  2739. // Otherwise, we are trying to abort an XHR which has not yet been sent, so there is no
  2740. // task
  2741. // to cancel. Do nothing.
  2742. });
  2743. }
  2744. });
  2745. Zone.__load_patch('geolocation', (global) => {
  2746. /// GEO_LOCATION
  2747. if (global['navigator'] && global['navigator'].geolocation) {
  2748. patchPrototype(global['navigator'].geolocation, ['getCurrentPosition', 'watchPosition']);
  2749. }
  2750. });
  2751. Zone.__load_patch('PromiseRejectionEvent', (global, Zone) => {
  2752. // handle unhandled promise rejection
  2753. function findPromiseRejectionHandler(evtName) {
  2754. return function (e) {
  2755. const eventTasks = findEventTasks(global, evtName);
  2756. eventTasks.forEach(eventTask => {
  2757. // windows has added unhandledrejection event listener
  2758. // trigger the event listener
  2759. const PromiseRejectionEvent = global['PromiseRejectionEvent'];
  2760. if (PromiseRejectionEvent) {
  2761. const evt = new PromiseRejectionEvent(evtName, { promise: e.promise, reason: e.rejection });
  2762. eventTask.invoke(evt);
  2763. }
  2764. });
  2765. };
  2766. }
  2767. if (global['PromiseRejectionEvent']) {
  2768. Zone[zoneSymbol('unhandledPromiseRejectionHandler')] =
  2769. findPromiseRejectionHandler('unhandledrejection');
  2770. Zone[zoneSymbol('rejectionHandledHandler')] =
  2771. findPromiseRejectionHandler('rejectionhandled');
  2772. }
  2773. });
  2774. Zone.__load_patch('node_util', (global, Zone, api) => {
  2775. api.patchOnProperties = patchOnProperties;
  2776. api.patchMethod = patchMethod;
  2777. api.bindArguments = bindArguments;
  2778. api.patchMacroTask = patchMacroTask;
  2779. setShouldCopySymbolProperties(true);
  2780. });
  2781. Zone.__load_patch('EventEmitter', (global, Zone, api) => {
  2782. // For EventEmitter
  2783. const EE_ADD_LISTENER = 'addListener';
  2784. const EE_PREPEND_LISTENER = 'prependListener';
  2785. const EE_REMOVE_LISTENER = 'removeListener';
  2786. const EE_REMOVE_ALL_LISTENER = 'removeAllListeners';
  2787. const EE_LISTENERS = 'listeners';
  2788. const EE_ON = 'on';
  2789. const EE_OFF = 'off';
  2790. const compareTaskCallbackVsDelegate = function (task, delegate) {
  2791. // same callback, same capture, same event name, just return
  2792. return task.callback === delegate || task.callback.listener === delegate;
  2793. };
  2794. const eventNameToString = function (eventName) {
  2795. if (typeof eventName === 'string') {
  2796. return eventName;
  2797. }
  2798. if (!eventName) {
  2799. return '';
  2800. }
  2801. return eventName.toString().replace('(', '_').replace(')', '_');
  2802. };
  2803. function patchEventEmitterMethods(obj) {
  2804. const result = patchEventTarget(global, api, [obj], {
  2805. useG: false,
  2806. add: EE_ADD_LISTENER,
  2807. rm: EE_REMOVE_LISTENER,
  2808. prepend: EE_PREPEND_LISTENER,
  2809. rmAll: EE_REMOVE_ALL_LISTENER,
  2810. listeners: EE_LISTENERS,
  2811. chkDup: false,
  2812. rt: true,
  2813. diff: compareTaskCallbackVsDelegate,
  2814. eventNameToString: eventNameToString
  2815. });
  2816. if (result && result[0]) {
  2817. obj[EE_ON] = obj[EE_ADD_LISTENER];
  2818. obj[EE_OFF] = obj[EE_REMOVE_LISTENER];
  2819. }
  2820. }
  2821. // EventEmitter
  2822. let events;
  2823. try {
  2824. events = require('events');
  2825. }
  2826. catch (err) {
  2827. }
  2828. if (events && events.EventEmitter) {
  2829. patchEventEmitterMethods(events.EventEmitter.prototype);
  2830. }
  2831. });
  2832. Zone.__load_patch('fs', () => {
  2833. let fs;
  2834. try {
  2835. fs = require('fs');
  2836. }
  2837. catch (err) {
  2838. }
  2839. // watch, watchFile, unwatchFile has been patched
  2840. // because EventEmitter has been patched
  2841. const TO_PATCH_MACROTASK_METHODS = [
  2842. 'access', 'appendFile', 'chmod', 'chown', 'close', 'exists', 'fchmod',
  2843. 'fchown', 'fdatasync', 'fstat', 'fsync', 'ftruncate', 'futimes', 'lchmod',
  2844. 'lchown', 'link', 'lstat', 'mkdir', 'mkdtemp', 'open', 'read',
  2845. 'readdir', 'readFile', 'readlink', 'realpath', 'rename', 'rmdir', 'stat',
  2846. 'symlink', 'truncate', 'unlink', 'utimes', 'write', 'writeFile',
  2847. ];
  2848. if (fs) {
  2849. TO_PATCH_MACROTASK_METHODS.filter(name => !!fs[name] && typeof fs[name] === 'function')
  2850. .forEach(name => {
  2851. patchMacroTask(fs, name, (self, args) => {
  2852. return {
  2853. name: 'fs.' + name,
  2854. args: args,
  2855. cbIdx: args.length > 0 ? args.length - 1 : -1,
  2856. target: self
  2857. };
  2858. });
  2859. });
  2860. }
  2861. });
  2862. const set = 'set';
  2863. const clear = 'clear';
  2864. Zone.__load_patch('node_timers', (global, Zone) => {
  2865. // Timers
  2866. let globalUseTimeoutFromTimer = false;
  2867. try {
  2868. const timers = require('timers');
  2869. let globalEqualTimersTimeout = global.setTimeout === timers.setTimeout;
  2870. if (!globalEqualTimersTimeout && !isMix) {
  2871. // 1. if isMix, then we are in mix environment such as Electron
  2872. // we should only patch timers.setTimeout because global.setTimeout
  2873. // have been patched
  2874. // 2. if global.setTimeout not equal timers.setTimeout, check
  2875. // whether global.setTimeout use timers.setTimeout or not
  2876. const originSetTimeout = timers.setTimeout;
  2877. timers.setTimeout = function () {
  2878. globalUseTimeoutFromTimer = true;
  2879. return originSetTimeout.apply(this, arguments);
  2880. };
  2881. const detectTimeout = global.setTimeout(() => { }, 100);
  2882. clearTimeout(detectTimeout);
  2883. timers.setTimeout = originSetTimeout;
  2884. }
  2885. patchTimer(timers, set, clear, 'Timeout');
  2886. patchTimer(timers, set, clear, 'Interval');
  2887. patchTimer(timers, set, clear, 'Immediate');
  2888. }
  2889. catch (error) {
  2890. // timers module not exists, for example, when we using nativeScript
  2891. // timers is not available
  2892. }
  2893. if (isMix) {
  2894. // if we are in mix environment, such as Electron,
  2895. // the global.setTimeout has already been patched,
  2896. // so we just patch timers.setTimeout
  2897. return;
  2898. }
  2899. if (!globalUseTimeoutFromTimer) {
  2900. // 1. global setTimeout equals timers setTimeout
  2901. // 2. or global don't use timers setTimeout(maybe some other library patch setTimeout)
  2902. // 3. or load timers module error happens, we should patch global setTimeout
  2903. patchTimer(global, set, clear, 'Timeout');
  2904. patchTimer(global, set, clear, 'Interval');
  2905. patchTimer(global, set, clear, 'Immediate');
  2906. }
  2907. else {
  2908. // global use timers setTimeout, but not equals
  2909. // this happens when use nodejs v0.10.x, global setTimeout will
  2910. // use a lazy load version of timers setTimeout
  2911. // we should not double patch timer's setTimeout
  2912. // so we only store the __symbol__ for consistency
  2913. global[Zone.__symbol__('setTimeout')] = global.setTimeout;
  2914. global[Zone.__symbol__('setInterval')] = global.setInterval;
  2915. global[Zone.__symbol__('setImmediate')] = global.setImmediate;
  2916. }
  2917. });
  2918. // patch process related methods
  2919. Zone.__load_patch('nextTick', () => {
  2920. // patch nextTick as microTask
  2921. patchMicroTask(process, 'nextTick', (self, args) => {
  2922. return {
  2923. name: 'process.nextTick',
  2924. args: args,
  2925. cbIdx: (args.length > 0 && typeof args[0] === 'function') ? 0 : -1,
  2926. target: process
  2927. };
  2928. });
  2929. });
  2930. Zone.__load_patch('handleUnhandledPromiseRejection', (global, Zone, api) => {
  2931. Zone[api.symbol('unhandledPromiseRejectionHandler')] =
  2932. findProcessPromiseRejectionHandler('unhandledRejection');
  2933. Zone[api.symbol('rejectionHandledHandler')] =
  2934. findProcessPromiseRejectionHandler('rejectionHandled');
  2935. // handle unhandled promise rejection
  2936. function findProcessPromiseRejectionHandler(evtName) {
  2937. return function (e) {
  2938. const eventTasks = findEventTasks(process, evtName);
  2939. eventTasks.forEach(eventTask => {
  2940. // process has added unhandledrejection event listener
  2941. // trigger the event listener
  2942. if (evtName === 'unhandledRejection') {
  2943. eventTask.invoke(e.rejection, e.promise);
  2944. }
  2945. else if (evtName === 'rejectionHandled') {
  2946. eventTask.invoke(e.promise);
  2947. }
  2948. });
  2949. };
  2950. }
  2951. });
  2952. // Crypto
  2953. Zone.__load_patch('crypto', () => {
  2954. let crypto;
  2955. try {
  2956. crypto = require('crypto');
  2957. }
  2958. catch (err) {
  2959. }
  2960. // use the generic patchMacroTask to patch crypto
  2961. if (crypto) {
  2962. const methodNames = ['randomBytes', 'pbkdf2'];
  2963. methodNames.forEach(name => {
  2964. patchMacroTask(crypto, name, (self, args) => {
  2965. return {
  2966. name: 'crypto.' + name,
  2967. args: args,
  2968. cbIdx: (args.length > 0 && typeof args[args.length - 1] === 'function') ?
  2969. args.length - 1 :
  2970. -1,
  2971. target: crypto
  2972. };
  2973. });
  2974. });
  2975. }
  2976. });
  2977. Zone.__load_patch('console', (global, Zone) => {
  2978. const consoleMethods = ['dir', 'log', 'info', 'error', 'warn', 'assert', 'debug', 'timeEnd', 'trace'];
  2979. consoleMethods.forEach((m) => {
  2980. const originalMethod = console[Zone.__symbol__(m)] = console[m];
  2981. if (originalMethod) {
  2982. console[m] = function () {
  2983. const args = ArraySlice.call(arguments);
  2984. if (Zone.current === Zone.root) {
  2985. return originalMethod.apply(this, args);
  2986. }
  2987. else {
  2988. return Zone.root.run(originalMethod, this, args);
  2989. }
  2990. };
  2991. }
  2992. });
  2993. });