zone.js 132 KB

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