zone-evergreen.js 125 KB

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