zone-node.js 118 KB

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