zone-mix.js 145 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302
  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. /** Object.create */
  649. const ObjectCreate = Object.create;
  650. /** Array.prototype.slice */
  651. const ArraySlice = Array.prototype.slice;
  652. /** addEventListener string const */
  653. const ADD_EVENT_LISTENER_STR = 'addEventListener';
  654. /** removeEventListener string const */
  655. const REMOVE_EVENT_LISTENER_STR = 'removeEventListener';
  656. /** zoneSymbol addEventListener */
  657. const ZONE_SYMBOL_ADD_EVENT_LISTENER = __symbol__(ADD_EVENT_LISTENER_STR);
  658. /** zoneSymbol removeEventListener */
  659. const ZONE_SYMBOL_REMOVE_EVENT_LISTENER = __symbol__(REMOVE_EVENT_LISTENER_STR);
  660. /** true string const */
  661. const TRUE_STR = 'true';
  662. /** false string const */
  663. const FALSE_STR = 'false';
  664. /** Zone symbol prefix string const. */
  665. const ZONE_SYMBOL_PREFIX = __symbol__('');
  666. function wrapWithCurrentZone(callback, source) {
  667. return Zone.current.wrap(callback, source);
  668. }
  669. function scheduleMacroTaskWithCurrentZone(source, callback, data, customSchedule, customCancel) {
  670. return Zone.current.scheduleMacroTask(source, callback, data, customSchedule, customCancel);
  671. }
  672. const zoneSymbol = __symbol__;
  673. const isWindowExists = typeof window !== 'undefined';
  674. const internalWindow = isWindowExists ? window : undefined;
  675. const _global = (isWindowExists && internalWindow) || globalThis;
  676. const REMOVE_ATTRIBUTE = 'removeAttribute';
  677. function bindArguments(args, source) {
  678. for (let i = args.length - 1; i >= 0; i--) {
  679. if (typeof args[i] === 'function') {
  680. args[i] = wrapWithCurrentZone(args[i], source + '_' + i);
  681. }
  682. }
  683. return args;
  684. }
  685. function patchPrototype(prototype, fnNames) {
  686. const source = prototype.constructor['name'];
  687. for (let i = 0; i < fnNames.length; i++) {
  688. const name = fnNames[i];
  689. const delegate = prototype[name];
  690. if (delegate) {
  691. const prototypeDesc = ObjectGetOwnPropertyDescriptor(prototype, name);
  692. if (!isPropertyWritable(prototypeDesc)) {
  693. continue;
  694. }
  695. prototype[name] = ((delegate) => {
  696. const patched = function () {
  697. return delegate.apply(this, bindArguments(arguments, source + '.' + name));
  698. };
  699. attachOriginToPatched(patched, delegate);
  700. return patched;
  701. })(delegate);
  702. }
  703. }
  704. }
  705. function isPropertyWritable(propertyDesc) {
  706. if (!propertyDesc) {
  707. return true;
  708. }
  709. if (propertyDesc.writable === false) {
  710. return false;
  711. }
  712. return !(typeof propertyDesc.get === 'function' && typeof propertyDesc.set === 'undefined');
  713. }
  714. const isWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
  715. // Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
  716. // this code.
  717. const isNode = !('nw' in _global) &&
  718. typeof _global.process !== 'undefined' &&
  719. _global.process.toString() === '[object process]';
  720. const isBrowser = !isNode && !isWebWorker && !!(isWindowExists && internalWindow['HTMLElement']);
  721. // we are in electron of nw, so we are both browser and nodejs
  722. // Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
  723. // this code.
  724. const isMix = typeof _global.process !== 'undefined' &&
  725. _global.process.toString() === '[object process]' &&
  726. !isWebWorker &&
  727. !!(isWindowExists && internalWindow['HTMLElement']);
  728. const zoneSymbolEventNames$1 = {};
  729. const enableBeforeunloadSymbol = zoneSymbol('enable_beforeunload');
  730. const wrapFn = function (event) {
  731. // https://github.com/angular/zone.js/issues/911, in IE, sometimes
  732. // event will be undefined, so we need to use window.event
  733. event = event || _global.event;
  734. if (!event) {
  735. return;
  736. }
  737. let eventNameSymbol = zoneSymbolEventNames$1[event.type];
  738. if (!eventNameSymbol) {
  739. eventNameSymbol = zoneSymbolEventNames$1[event.type] = zoneSymbol('ON_PROPERTY' + event.type);
  740. }
  741. const target = this || event.target || _global;
  742. const listener = target[eventNameSymbol];
  743. let result;
  744. if (isBrowser && target === internalWindow && event.type === 'error') {
  745. // window.onerror have different signature
  746. // https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror#window.onerror
  747. // and onerror callback will prevent default when callback return true
  748. const errorEvent = event;
  749. result =
  750. listener &&
  751. listener.call(this, errorEvent.message, errorEvent.filename, errorEvent.lineno, errorEvent.colno, errorEvent.error);
  752. if (result === true) {
  753. event.preventDefault();
  754. }
  755. }
  756. else {
  757. result = listener && listener.apply(this, arguments);
  758. if (
  759. // https://github.com/angular/angular/issues/47579
  760. // https://www.w3.org/TR/2011/WD-html5-20110525/history.html#beforeunloadevent
  761. // This is the only specific case we should check for. The spec defines that the
  762. // `returnValue` attribute represents the message to show the user. When the event
  763. // is created, this attribute must be set to the empty string.
  764. event.type === 'beforeunload' &&
  765. // To prevent any breaking changes resulting from this change, given that
  766. // it was already causing a significant number of failures in G3, we have hidden
  767. // that behavior behind a global configuration flag. Consumers can enable this
  768. // flag explicitly if they want the `beforeunload` event to be handled as defined
  769. // in the specification.
  770. _global[enableBeforeunloadSymbol] &&
  771. // The IDL event definition is `attribute DOMString returnValue`, so we check whether
  772. // `typeof result` is a string.
  773. typeof result === 'string') {
  774. event.returnValue = result;
  775. }
  776. else if (result != undefined && !result) {
  777. event.preventDefault();
  778. }
  779. }
  780. return result;
  781. };
  782. function patchProperty(obj, prop, prototype) {
  783. let desc = ObjectGetOwnPropertyDescriptor(obj, prop);
  784. if (!desc && prototype) {
  785. // when patch window object, use prototype to check prop exist or not
  786. const prototypeDesc = ObjectGetOwnPropertyDescriptor(prototype, prop);
  787. if (prototypeDesc) {
  788. desc = { enumerable: true, configurable: true };
  789. }
  790. }
  791. // if the descriptor not exists or is not configurable
  792. // just return
  793. if (!desc || !desc.configurable) {
  794. return;
  795. }
  796. const onPropPatchedSymbol = zoneSymbol('on' + prop + 'patched');
  797. if (obj.hasOwnProperty(onPropPatchedSymbol) && obj[onPropPatchedSymbol]) {
  798. return;
  799. }
  800. // A property descriptor cannot have getter/setter and be writable
  801. // deleting the writable and value properties avoids this error:
  802. //
  803. // TypeError: property descriptors must not specify a value or be writable when a
  804. // getter or setter has been specified
  805. delete desc.writable;
  806. delete desc.value;
  807. const originalDescGet = desc.get;
  808. const originalDescSet = desc.set;
  809. // slice(2) cuz 'onclick' -> 'click', etc
  810. const eventName = prop.slice(2);
  811. let eventNameSymbol = zoneSymbolEventNames$1[eventName];
  812. if (!eventNameSymbol) {
  813. eventNameSymbol = zoneSymbolEventNames$1[eventName] = zoneSymbol('ON_PROPERTY' + eventName);
  814. }
  815. desc.set = function (newValue) {
  816. // in some of windows's onproperty callback, this is undefined
  817. // so we need to check it
  818. let target = this;
  819. if (!target && obj === _global) {
  820. target = _global;
  821. }
  822. if (!target) {
  823. return;
  824. }
  825. const previousValue = target[eventNameSymbol];
  826. if (typeof previousValue === 'function') {
  827. target.removeEventListener(eventName, wrapFn);
  828. }
  829. // issue #978, when onload handler was added before loading zone.js
  830. // we should remove it with originalDescSet
  831. originalDescSet && originalDescSet.call(target, null);
  832. target[eventNameSymbol] = newValue;
  833. if (typeof newValue === 'function') {
  834. target.addEventListener(eventName, wrapFn, false);
  835. }
  836. };
  837. // The getter would return undefined for unassigned properties but the default value of an
  838. // unassigned property is null
  839. desc.get = function () {
  840. // in some of windows's onproperty callback, this is undefined
  841. // so we need to check it
  842. let target = this;
  843. if (!target && obj === _global) {
  844. target = _global;
  845. }
  846. if (!target) {
  847. return null;
  848. }
  849. const listener = target[eventNameSymbol];
  850. if (listener) {
  851. return listener;
  852. }
  853. else if (originalDescGet) {
  854. // result will be null when use inline event attribute,
  855. // such as <button onclick="func();">OK</button>
  856. // because the onclick function is internal raw uncompiled handler
  857. // the onclick will be evaluated when first time event was triggered or
  858. // the property is accessed, https://github.com/angular/zone.js/issues/525
  859. // so we should use original native get to retrieve the handler
  860. let value = originalDescGet.call(this);
  861. if (value) {
  862. desc.set.call(this, value);
  863. if (typeof target[REMOVE_ATTRIBUTE] === 'function') {
  864. target.removeAttribute(prop);
  865. }
  866. return value;
  867. }
  868. }
  869. return null;
  870. };
  871. ObjectDefineProperty(obj, prop, desc);
  872. obj[onPropPatchedSymbol] = true;
  873. }
  874. function patchOnProperties(obj, properties, prototype) {
  875. if (properties) {
  876. for (let i = 0; i < properties.length; i++) {
  877. patchProperty(obj, 'on' + properties[i], prototype);
  878. }
  879. }
  880. else {
  881. const onProperties = [];
  882. for (const prop in obj) {
  883. if (prop.slice(0, 2) == 'on') {
  884. onProperties.push(prop);
  885. }
  886. }
  887. for (let j = 0; j < onProperties.length; j++) {
  888. patchProperty(obj, onProperties[j], prototype);
  889. }
  890. }
  891. }
  892. const originalInstanceKey = zoneSymbol('originalInstance');
  893. // wrap some native API on `window`
  894. function patchClass(className) {
  895. const OriginalClass = _global[className];
  896. if (!OriginalClass)
  897. return;
  898. // keep original class in global
  899. _global[zoneSymbol(className)] = OriginalClass;
  900. _global[className] = function () {
  901. const a = bindArguments(arguments, className);
  902. switch (a.length) {
  903. case 0:
  904. this[originalInstanceKey] = new OriginalClass();
  905. break;
  906. case 1:
  907. this[originalInstanceKey] = new OriginalClass(a[0]);
  908. break;
  909. case 2:
  910. this[originalInstanceKey] = new OriginalClass(a[0], a[1]);
  911. break;
  912. case 3:
  913. this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2]);
  914. break;
  915. case 4:
  916. this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2], a[3]);
  917. break;
  918. default:
  919. throw new Error('Arg list too long.');
  920. }
  921. };
  922. // attach original delegate to patched function
  923. attachOriginToPatched(_global[className], OriginalClass);
  924. const instance = new OriginalClass(function () { });
  925. let prop;
  926. for (prop in instance) {
  927. // https://bugs.webkit.org/show_bug.cgi?id=44721
  928. if (className === 'XMLHttpRequest' && prop === 'responseBlob')
  929. continue;
  930. (function (prop) {
  931. if (typeof instance[prop] === 'function') {
  932. _global[className].prototype[prop] = function () {
  933. return this[originalInstanceKey][prop].apply(this[originalInstanceKey], arguments);
  934. };
  935. }
  936. else {
  937. ObjectDefineProperty(_global[className].prototype, prop, {
  938. set: function (fn) {
  939. if (typeof fn === 'function') {
  940. this[originalInstanceKey][prop] = wrapWithCurrentZone(fn, className + '.' + prop);
  941. // keep callback in wrapped function so we can
  942. // use it in Function.prototype.toString to return
  943. // the native one.
  944. attachOriginToPatched(this[originalInstanceKey][prop], fn);
  945. }
  946. else {
  947. this[originalInstanceKey][prop] = fn;
  948. }
  949. },
  950. get: function () {
  951. return this[originalInstanceKey][prop];
  952. },
  953. });
  954. }
  955. })(prop);
  956. }
  957. for (prop in OriginalClass) {
  958. if (prop !== 'prototype' && OriginalClass.hasOwnProperty(prop)) {
  959. _global[className][prop] = OriginalClass[prop];
  960. }
  961. }
  962. }
  963. function copySymbolProperties(src, dest) {
  964. if (typeof Object.getOwnPropertySymbols !== 'function') {
  965. return;
  966. }
  967. const symbols = Object.getOwnPropertySymbols(src);
  968. symbols.forEach((symbol) => {
  969. const desc = Object.getOwnPropertyDescriptor(src, symbol);
  970. Object.defineProperty(dest, symbol, {
  971. get: function () {
  972. return src[symbol];
  973. },
  974. set: function (value) {
  975. if (desc && (!desc.writable || typeof desc.set !== 'function')) {
  976. // if src[symbol] is not writable or not have a setter, just return
  977. return;
  978. }
  979. src[symbol] = value;
  980. },
  981. enumerable: desc ? desc.enumerable : true,
  982. configurable: desc ? desc.configurable : true,
  983. });
  984. });
  985. }
  986. let shouldCopySymbolProperties = false;
  987. function setShouldCopySymbolProperties(flag) {
  988. shouldCopySymbolProperties = flag;
  989. }
  990. function patchMethod(target, name, patchFn) {
  991. let proto = target;
  992. while (proto && !proto.hasOwnProperty(name)) {
  993. proto = ObjectGetPrototypeOf(proto);
  994. }
  995. if (!proto && target[name]) {
  996. // somehow we did not find it, but we can see it. This happens on IE for Window properties.
  997. proto = target;
  998. }
  999. const delegateName = zoneSymbol(name);
  1000. let delegate = null;
  1001. if (proto && (!(delegate = proto[delegateName]) || !proto.hasOwnProperty(delegateName))) {
  1002. delegate = proto[delegateName] = proto[name];
  1003. // check whether proto[name] is writable
  1004. // some property is readonly in safari, such as HtmlCanvasElement.prototype.toBlob
  1005. const desc = proto && ObjectGetOwnPropertyDescriptor(proto, name);
  1006. if (isPropertyWritable(desc)) {
  1007. const patchDelegate = patchFn(delegate, delegateName, name);
  1008. proto[name] = function () {
  1009. return patchDelegate(this, arguments);
  1010. };
  1011. attachOriginToPatched(proto[name], delegate);
  1012. if (shouldCopySymbolProperties) {
  1013. copySymbolProperties(delegate, proto[name]);
  1014. }
  1015. }
  1016. }
  1017. return delegate;
  1018. }
  1019. // TODO: @JiaLiPassion, support cancel task later if necessary
  1020. function patchMacroTask(obj, funcName, metaCreator) {
  1021. let setNative = null;
  1022. function scheduleTask(task) {
  1023. const data = task.data;
  1024. data.args[data.cbIdx] = function () {
  1025. task.invoke.apply(this, arguments);
  1026. };
  1027. setNative.apply(data.target, data.args);
  1028. return task;
  1029. }
  1030. setNative = patchMethod(obj, funcName, (delegate) => function (self, args) {
  1031. const meta = metaCreator(self, args);
  1032. if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
  1033. return scheduleMacroTaskWithCurrentZone(meta.name, args[meta.cbIdx], meta, scheduleTask);
  1034. }
  1035. else {
  1036. // cause an error by calling it directly.
  1037. return delegate.apply(self, args);
  1038. }
  1039. });
  1040. }
  1041. function patchMicroTask(obj, funcName, metaCreator) {
  1042. let setNative = null;
  1043. function scheduleTask(task) {
  1044. const data = task.data;
  1045. data.args[data.cbIdx] = function () {
  1046. task.invoke.apply(this, arguments);
  1047. };
  1048. setNative.apply(data.target, data.args);
  1049. return task;
  1050. }
  1051. setNative = patchMethod(obj, funcName, (delegate) => function (self, args) {
  1052. const meta = metaCreator(self, args);
  1053. if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
  1054. return Zone.current.scheduleMicroTask(meta.name, args[meta.cbIdx], meta, scheduleTask);
  1055. }
  1056. else {
  1057. // cause an error by calling it directly.
  1058. return delegate.apply(self, args);
  1059. }
  1060. });
  1061. }
  1062. function attachOriginToPatched(patched, original) {
  1063. patched[zoneSymbol('OriginalDelegate')] = original;
  1064. }
  1065. let isDetectedIEOrEdge = false;
  1066. let ieOrEdge = false;
  1067. function isIE() {
  1068. try {
  1069. const ua = internalWindow.navigator.userAgent;
  1070. if (ua.indexOf('MSIE ') !== -1 || ua.indexOf('Trident/') !== -1) {
  1071. return true;
  1072. }
  1073. }
  1074. catch (error) { }
  1075. return false;
  1076. }
  1077. function isIEOrEdge() {
  1078. if (isDetectedIEOrEdge) {
  1079. return ieOrEdge;
  1080. }
  1081. isDetectedIEOrEdge = true;
  1082. try {
  1083. const ua = internalWindow.navigator.userAgent;
  1084. if (ua.indexOf('MSIE ') !== -1 || ua.indexOf('Trident/') !== -1 || ua.indexOf('Edge/') !== -1) {
  1085. ieOrEdge = true;
  1086. }
  1087. }
  1088. catch (error) { }
  1089. return ieOrEdge;
  1090. }
  1091. function isFunction(value) {
  1092. return typeof value === 'function';
  1093. }
  1094. function isNumber(value) {
  1095. return typeof value === 'number';
  1096. }
  1097. /**
  1098. * @fileoverview
  1099. * @suppress {missingRequire}
  1100. */
  1101. // Note that passive event listeners are now supported by most modern browsers,
  1102. // including Chrome, Firefox, Safari, and Edge. There's a pending change that
  1103. // would remove support for legacy browsers by zone.js. Removing `passiveSupported`
  1104. // from the codebase will reduce the final code size for existing apps that still use zone.js.
  1105. let passiveSupported = false;
  1106. if (typeof window !== 'undefined') {
  1107. try {
  1108. const options = Object.defineProperty({}, 'passive', {
  1109. get: function () {
  1110. passiveSupported = true;
  1111. },
  1112. });
  1113. // Note: We pass the `options` object as the event handler too. This is not compatible with the
  1114. // signature of `addEventListener` or `removeEventListener` but enables us to remove the handler
  1115. // without an actual handler.
  1116. window.addEventListener('test', options, options);
  1117. window.removeEventListener('test', options, options);
  1118. }
  1119. catch (err) {
  1120. passiveSupported = false;
  1121. }
  1122. }
  1123. // an identifier to tell ZoneTask do not create a new invoke closure
  1124. const OPTIMIZED_ZONE_EVENT_TASK_DATA = {
  1125. useG: true,
  1126. };
  1127. const zoneSymbolEventNames = {};
  1128. const globalSources = {};
  1129. const EVENT_NAME_SYMBOL_REGX = new RegExp('^' + ZONE_SYMBOL_PREFIX + '(\\w+)(true|false)$');
  1130. const IMMEDIATE_PROPAGATION_SYMBOL = zoneSymbol('propagationStopped');
  1131. function prepareEventNames(eventName, eventNameToString) {
  1132. const falseEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + FALSE_STR;
  1133. const trueEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + TRUE_STR;
  1134. const symbol = ZONE_SYMBOL_PREFIX + falseEventName;
  1135. const symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
  1136. zoneSymbolEventNames[eventName] = {};
  1137. zoneSymbolEventNames[eventName][FALSE_STR] = symbol;
  1138. zoneSymbolEventNames[eventName][TRUE_STR] = symbolCapture;
  1139. }
  1140. function patchEventTarget(_global, api, apis, patchOptions) {
  1141. const ADD_EVENT_LISTENER = (patchOptions && patchOptions.add) || ADD_EVENT_LISTENER_STR;
  1142. const REMOVE_EVENT_LISTENER = (patchOptions && patchOptions.rm) || REMOVE_EVENT_LISTENER_STR;
  1143. const LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.listeners) || 'eventListeners';
  1144. const REMOVE_ALL_LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.rmAll) || 'removeAllListeners';
  1145. const zoneSymbolAddEventListener = zoneSymbol(ADD_EVENT_LISTENER);
  1146. const ADD_EVENT_LISTENER_SOURCE = '.' + ADD_EVENT_LISTENER + ':';
  1147. const PREPEND_EVENT_LISTENER = 'prependListener';
  1148. const PREPEND_EVENT_LISTENER_SOURCE = '.' + PREPEND_EVENT_LISTENER + ':';
  1149. const invokeTask = function (task, target, event) {
  1150. // for better performance, check isRemoved which is set
  1151. // by removeEventListener
  1152. if (task.isRemoved) {
  1153. return;
  1154. }
  1155. const delegate = task.callback;
  1156. if (typeof delegate === 'object' && delegate.handleEvent) {
  1157. // create the bind version of handleEvent when invoke
  1158. task.callback = (event) => delegate.handleEvent(event);
  1159. task.originalDelegate = delegate;
  1160. }
  1161. // invoke static task.invoke
  1162. // need to try/catch error here, otherwise, the error in one event listener
  1163. // will break the executions of the other event listeners. Also error will
  1164. // not remove the event listener when `once` options is true.
  1165. let error;
  1166. try {
  1167. task.invoke(task, target, [event]);
  1168. }
  1169. catch (err) {
  1170. error = err;
  1171. }
  1172. const options = task.options;
  1173. if (options && typeof options === 'object' && options.once) {
  1174. // if options.once is true, after invoke once remove listener here
  1175. // only browser need to do this, nodejs eventEmitter will cal removeListener
  1176. // inside EventEmitter.once
  1177. const delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  1178. target[REMOVE_EVENT_LISTENER].call(target, event.type, delegate, options);
  1179. }
  1180. return error;
  1181. };
  1182. function globalCallback(context, event, isCapture) {
  1183. // https://github.com/angular/zone.js/issues/911, in IE, sometimes
  1184. // event will be undefined, so we need to use window.event
  1185. event = event || _global.event;
  1186. if (!event) {
  1187. return;
  1188. }
  1189. // event.target is needed for Samsung TV and SourceBuffer
  1190. // || global is needed https://github.com/angular/zone.js/issues/190
  1191. const target = context || event.target || _global;
  1192. const tasks = target[zoneSymbolEventNames[event.type][isCapture ? TRUE_STR : FALSE_STR]];
  1193. if (tasks) {
  1194. const errors = [];
  1195. // invoke all tasks which attached to current target with given event.type and capture = false
  1196. // for performance concern, if task.length === 1, just invoke
  1197. if (tasks.length === 1) {
  1198. const err = invokeTask(tasks[0], target, event);
  1199. err && errors.push(err);
  1200. }
  1201. else {
  1202. // https://github.com/angular/zone.js/issues/836
  1203. // copy the tasks array before invoke, to avoid
  1204. // the callback will remove itself or other listener
  1205. const copyTasks = tasks.slice();
  1206. for (let i = 0; i < copyTasks.length; i++) {
  1207. if (event && event[IMMEDIATE_PROPAGATION_SYMBOL] === true) {
  1208. break;
  1209. }
  1210. const err = invokeTask(copyTasks[i], target, event);
  1211. err && errors.push(err);
  1212. }
  1213. }
  1214. // Since there is only one error, we don't need to schedule microTask
  1215. // to throw the error.
  1216. if (errors.length === 1) {
  1217. throw errors[0];
  1218. }
  1219. else {
  1220. for (let i = 0; i < errors.length; i++) {
  1221. const err = errors[i];
  1222. api.nativeScheduleMicroTask(() => {
  1223. throw err;
  1224. });
  1225. }
  1226. }
  1227. }
  1228. }
  1229. // global shared zoneAwareCallback to handle all event callback with capture = false
  1230. const globalZoneAwareCallback = function (event) {
  1231. return globalCallback(this, event, false);
  1232. };
  1233. // global shared zoneAwareCallback to handle all event callback with capture = true
  1234. const globalZoneAwareCaptureCallback = function (event) {
  1235. return globalCallback(this, event, true);
  1236. };
  1237. function patchEventTargetMethods(obj, patchOptions) {
  1238. if (!obj) {
  1239. return false;
  1240. }
  1241. let useGlobalCallback = true;
  1242. if (patchOptions && patchOptions.useG !== undefined) {
  1243. useGlobalCallback = patchOptions.useG;
  1244. }
  1245. const validateHandler = patchOptions && patchOptions.vh;
  1246. let checkDuplicate = true;
  1247. if (patchOptions && patchOptions.chkDup !== undefined) {
  1248. checkDuplicate = patchOptions.chkDup;
  1249. }
  1250. let returnTarget = false;
  1251. if (patchOptions && patchOptions.rt !== undefined) {
  1252. returnTarget = patchOptions.rt;
  1253. }
  1254. let proto = obj;
  1255. while (proto && !proto.hasOwnProperty(ADD_EVENT_LISTENER)) {
  1256. proto = ObjectGetPrototypeOf(proto);
  1257. }
  1258. if (!proto && obj[ADD_EVENT_LISTENER]) {
  1259. // somehow we did not find it, but we can see it. This happens on IE for Window properties.
  1260. proto = obj;
  1261. }
  1262. if (!proto) {
  1263. return false;
  1264. }
  1265. if (proto[zoneSymbolAddEventListener]) {
  1266. return false;
  1267. }
  1268. const eventNameToString = patchOptions && patchOptions.eventNameToString;
  1269. // We use a shared global `taskData` to pass data for `scheduleEventTask`,
  1270. // eliminating the need to create a new object solely for passing data.
  1271. // WARNING: This object has a static lifetime, meaning it is not created
  1272. // each time `addEventListener` is called. It is instantiated only once
  1273. // and captured by reference inside the `addEventListener` and
  1274. // `removeEventListener` functions. Do not add any new properties to this
  1275. // object, as doing so would necessitate maintaining the information
  1276. // between `addEventListener` calls.
  1277. const taskData = {};
  1278. const nativeAddEventListener = (proto[zoneSymbolAddEventListener] = proto[ADD_EVENT_LISTENER]);
  1279. const nativeRemoveEventListener = (proto[zoneSymbol(REMOVE_EVENT_LISTENER)] =
  1280. proto[REMOVE_EVENT_LISTENER]);
  1281. const nativeListeners = (proto[zoneSymbol(LISTENERS_EVENT_LISTENER)] =
  1282. proto[LISTENERS_EVENT_LISTENER]);
  1283. const nativeRemoveAllListeners = (proto[zoneSymbol(REMOVE_ALL_LISTENERS_EVENT_LISTENER)] =
  1284. proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER]);
  1285. let nativePrependEventListener;
  1286. if (patchOptions && patchOptions.prepend) {
  1287. nativePrependEventListener = proto[zoneSymbol(patchOptions.prepend)] =
  1288. proto[patchOptions.prepend];
  1289. }
  1290. /**
  1291. * This util function will build an option object with passive option
  1292. * to handle all possible input from the user.
  1293. */
  1294. function buildEventListenerOptions(options, passive) {
  1295. if (!passiveSupported && typeof options === 'object' && options) {
  1296. // doesn't support passive but user want to pass an object as options.
  1297. // this will not work on some old browser, so we just pass a boolean
  1298. // as useCapture parameter
  1299. return !!options.capture;
  1300. }
  1301. if (!passiveSupported || !passive) {
  1302. return options;
  1303. }
  1304. if (typeof options === 'boolean') {
  1305. return { capture: options, passive: true };
  1306. }
  1307. if (!options) {
  1308. return { passive: true };
  1309. }
  1310. if (typeof options === 'object' && options.passive !== false) {
  1311. return { ...options, passive: true };
  1312. }
  1313. return options;
  1314. }
  1315. const customScheduleGlobal = function (task) {
  1316. // if there is already a task for the eventName + capture,
  1317. // just return, because we use the shared globalZoneAwareCallback here.
  1318. if (taskData.isExisting) {
  1319. return;
  1320. }
  1321. return nativeAddEventListener.call(taskData.target, taskData.eventName, taskData.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, taskData.options);
  1322. };
  1323. /**
  1324. * In the context of events and listeners, this function will be
  1325. * called at the end by `cancelTask`, which, in turn, calls `task.cancelFn`.
  1326. * Cancelling a task is primarily used to remove event listeners from
  1327. * the task target.
  1328. */
  1329. const customCancelGlobal = function (task) {
  1330. // if task is not marked as isRemoved, this call is directly
  1331. // from Zone.prototype.cancelTask, we should remove the task
  1332. // from tasksList of target first
  1333. if (!task.isRemoved) {
  1334. const symbolEventNames = zoneSymbolEventNames[task.eventName];
  1335. let symbolEventName;
  1336. if (symbolEventNames) {
  1337. symbolEventName = symbolEventNames[task.capture ? TRUE_STR : FALSE_STR];
  1338. }
  1339. const existingTasks = symbolEventName && task.target[symbolEventName];
  1340. if (existingTasks) {
  1341. for (let i = 0; i < existingTasks.length; i++) {
  1342. const existingTask = existingTasks[i];
  1343. if (existingTask === task) {
  1344. existingTasks.splice(i, 1);
  1345. // set isRemoved to data for faster invokeTask check
  1346. task.isRemoved = true;
  1347. if (task.removeAbortListener) {
  1348. task.removeAbortListener();
  1349. task.removeAbortListener = null;
  1350. }
  1351. if (existingTasks.length === 0) {
  1352. // all tasks for the eventName + capture have gone,
  1353. // remove globalZoneAwareCallback and remove the task cache from target
  1354. task.allRemoved = true;
  1355. task.target[symbolEventName] = null;
  1356. }
  1357. break;
  1358. }
  1359. }
  1360. }
  1361. }
  1362. // if all tasks for the eventName + capture have gone,
  1363. // we will really remove the global event callback,
  1364. // if not, return
  1365. if (!task.allRemoved) {
  1366. return;
  1367. }
  1368. return nativeRemoveEventListener.call(task.target, task.eventName, task.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, task.options);
  1369. };
  1370. const customScheduleNonGlobal = function (task) {
  1371. return nativeAddEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
  1372. };
  1373. const customSchedulePrepend = function (task) {
  1374. return nativePrependEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
  1375. };
  1376. const customCancelNonGlobal = function (task) {
  1377. return nativeRemoveEventListener.call(task.target, task.eventName, task.invoke, task.options);
  1378. };
  1379. const customSchedule = useGlobalCallback ? customScheduleGlobal : customScheduleNonGlobal;
  1380. const customCancel = useGlobalCallback ? customCancelGlobal : customCancelNonGlobal;
  1381. const compareTaskCallbackVsDelegate = function (task, delegate) {
  1382. const typeOfDelegate = typeof delegate;
  1383. return ((typeOfDelegate === 'function' && task.callback === delegate) ||
  1384. (typeOfDelegate === 'object' && task.originalDelegate === delegate));
  1385. };
  1386. const compare = patchOptions && patchOptions.diff ? patchOptions.diff : compareTaskCallbackVsDelegate;
  1387. const unpatchedEvents = Zone[zoneSymbol('UNPATCHED_EVENTS')];
  1388. const passiveEvents = _global[zoneSymbol('PASSIVE_EVENTS')];
  1389. function copyEventListenerOptions(options) {
  1390. if (typeof options === 'object' && options !== null) {
  1391. // We need to destructure the target `options` object since it may
  1392. // be frozen or sealed (possibly provided implicitly by a third-party
  1393. // library), or its properties may be readonly.
  1394. const newOptions = { ...options };
  1395. // The `signal` option was recently introduced, which caused regressions in
  1396. // third-party scenarios where `AbortController` was directly provided to
  1397. // `addEventListener` as options. For instance, in cases like
  1398. // `document.addEventListener('keydown', callback, abortControllerInstance)`,
  1399. // which is valid because `AbortController` includes a `signal` getter, spreading
  1400. // `{...options}` wouldn't copy the `signal`. Additionally, using `Object.create`
  1401. // isn't feasible since `AbortController` is a built-in object type, and attempting
  1402. // to create a new object directly with it as the prototype might result in
  1403. // unexpected behavior.
  1404. if (options.signal) {
  1405. newOptions.signal = options.signal;
  1406. }
  1407. return newOptions;
  1408. }
  1409. return options;
  1410. }
  1411. const makeAddListener = function (nativeListener, addSource, customScheduleFn, customCancelFn, returnTarget = false, prepend = false) {
  1412. return function () {
  1413. const target = this || _global;
  1414. let eventName = arguments[0];
  1415. if (patchOptions && patchOptions.transferEventName) {
  1416. eventName = patchOptions.transferEventName(eventName);
  1417. }
  1418. let delegate = arguments[1];
  1419. if (!delegate) {
  1420. return nativeListener.apply(this, arguments);
  1421. }
  1422. if (isNode && eventName === 'uncaughtException') {
  1423. // don't patch uncaughtException of nodejs to prevent endless loop
  1424. return nativeListener.apply(this, arguments);
  1425. }
  1426. // don't create the bind delegate function for handleEvent
  1427. // case here to improve addEventListener performance
  1428. // we will create the bind delegate when invoke
  1429. let isHandleEvent = false;
  1430. if (typeof delegate !== 'function') {
  1431. if (!delegate.handleEvent) {
  1432. return nativeListener.apply(this, arguments);
  1433. }
  1434. isHandleEvent = true;
  1435. }
  1436. if (validateHandler && !validateHandler(nativeListener, delegate, target, arguments)) {
  1437. return;
  1438. }
  1439. const passive = passiveSupported && !!passiveEvents && passiveEvents.indexOf(eventName) !== -1;
  1440. const options = copyEventListenerOptions(buildEventListenerOptions(arguments[2], passive));
  1441. const signal = options?.signal;
  1442. if (signal?.aborted) {
  1443. // the signal is an aborted one, just return without attaching the event listener.
  1444. return;
  1445. }
  1446. if (unpatchedEvents) {
  1447. // check unpatched list
  1448. for (let i = 0; i < unpatchedEvents.length; i++) {
  1449. if (eventName === unpatchedEvents[i]) {
  1450. if (passive) {
  1451. return nativeListener.call(target, eventName, delegate, options);
  1452. }
  1453. else {
  1454. return nativeListener.apply(this, arguments);
  1455. }
  1456. }
  1457. }
  1458. }
  1459. const capture = !options ? false : typeof options === 'boolean' ? true : options.capture;
  1460. const once = options && typeof options === 'object' ? options.once : false;
  1461. const zone = Zone.current;
  1462. let symbolEventNames = zoneSymbolEventNames[eventName];
  1463. if (!symbolEventNames) {
  1464. prepareEventNames(eventName, eventNameToString);
  1465. symbolEventNames = zoneSymbolEventNames[eventName];
  1466. }
  1467. const symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
  1468. let existingTasks = target[symbolEventName];
  1469. let isExisting = false;
  1470. if (existingTasks) {
  1471. // already have task registered
  1472. isExisting = true;
  1473. if (checkDuplicate) {
  1474. for (let i = 0; i < existingTasks.length; i++) {
  1475. if (compare(existingTasks[i], delegate)) {
  1476. // same callback, same capture, same event name, just return
  1477. return;
  1478. }
  1479. }
  1480. }
  1481. }
  1482. else {
  1483. existingTasks = target[symbolEventName] = [];
  1484. }
  1485. let source;
  1486. const constructorName = target.constructor['name'];
  1487. const targetSource = globalSources[constructorName];
  1488. if (targetSource) {
  1489. source = targetSource[eventName];
  1490. }
  1491. if (!source) {
  1492. source =
  1493. constructorName +
  1494. addSource +
  1495. (eventNameToString ? eventNameToString(eventName) : eventName);
  1496. }
  1497. // In the code below, `options` should no longer be reassigned; instead, it
  1498. // should only be mutated. This is because we pass that object to the native
  1499. // `addEventListener`.
  1500. // It's generally recommended to use the same object reference for options.
  1501. // This ensures consistency and avoids potential issues.
  1502. taskData.options = options;
  1503. if (once) {
  1504. // When using `addEventListener` with the `once` option, we don't pass
  1505. // the `once` option directly to the native `addEventListener` method.
  1506. // Instead, we keep the `once` setting and handle it ourselves.
  1507. taskData.options.once = false;
  1508. }
  1509. taskData.target = target;
  1510. taskData.capture = capture;
  1511. taskData.eventName = eventName;
  1512. taskData.isExisting = isExisting;
  1513. const data = useGlobalCallback ? OPTIMIZED_ZONE_EVENT_TASK_DATA : undefined;
  1514. // keep taskData into data to allow onScheduleEventTask to access the task information
  1515. if (data) {
  1516. data.taskData = taskData;
  1517. }
  1518. if (signal) {
  1519. // When using `addEventListener` with the `signal` option, we don't pass
  1520. // the `signal` option directly to the native `addEventListener` method.
  1521. // Instead, we keep the `signal` setting and handle it ourselves.
  1522. taskData.options.signal = undefined;
  1523. }
  1524. // The `scheduleEventTask` function will ultimately call `customScheduleGlobal`,
  1525. // which in turn calls the native `addEventListener`. This is why `taskData.options`
  1526. // is updated before scheduling the task, as `customScheduleGlobal` uses
  1527. // `taskData.options` to pass it to the native `addEventListener`.
  1528. const task = zone.scheduleEventTask(source, delegate, data, customScheduleFn, customCancelFn);
  1529. if (signal) {
  1530. // after task is scheduled, we need to store the signal back to task.options
  1531. taskData.options.signal = signal;
  1532. // Wrapping `task` in a weak reference would not prevent memory leaks. Weak references are
  1533. // primarily used for preventing strong references cycles. `onAbort` is always reachable
  1534. // as it's an event listener, so its closure retains a strong reference to the `task`.
  1535. const onAbort = () => task.zone.cancelTask(task);
  1536. nativeListener.call(signal, 'abort', onAbort, { once: true });
  1537. // We need to remove the `abort` listener when the event listener is going to be removed,
  1538. // as it creates a closure that captures `task`. This closure retains a reference to the
  1539. // `task` object even after it goes out of scope, preventing `task` from being garbage
  1540. // collected.
  1541. task.removeAbortListener = () => signal.removeEventListener('abort', onAbort);
  1542. }
  1543. // should clear taskData.target to avoid memory leak
  1544. // issue, https://github.com/angular/angular/issues/20442
  1545. taskData.target = null;
  1546. // need to clear up taskData because it is a global object
  1547. if (data) {
  1548. data.taskData = null;
  1549. }
  1550. // have to save those information to task in case
  1551. // application may call task.zone.cancelTask() directly
  1552. if (once) {
  1553. taskData.options.once = true;
  1554. }
  1555. if (!(!passiveSupported && typeof task.options === 'boolean')) {
  1556. // if not support passive, and we pass an option object
  1557. // to addEventListener, we should save the options to task
  1558. task.options = options;
  1559. }
  1560. task.target = target;
  1561. task.capture = capture;
  1562. task.eventName = eventName;
  1563. if (isHandleEvent) {
  1564. // save original delegate for compare to check duplicate
  1565. task.originalDelegate = delegate;
  1566. }
  1567. if (!prepend) {
  1568. existingTasks.push(task);
  1569. }
  1570. else {
  1571. existingTasks.unshift(task);
  1572. }
  1573. if (returnTarget) {
  1574. return target;
  1575. }
  1576. };
  1577. };
  1578. proto[ADD_EVENT_LISTENER] = makeAddListener(nativeAddEventListener, ADD_EVENT_LISTENER_SOURCE, customSchedule, customCancel, returnTarget);
  1579. if (nativePrependEventListener) {
  1580. proto[PREPEND_EVENT_LISTENER] = makeAddListener(nativePrependEventListener, PREPEND_EVENT_LISTENER_SOURCE, customSchedulePrepend, customCancel, returnTarget, true);
  1581. }
  1582. proto[REMOVE_EVENT_LISTENER] = function () {
  1583. const target = this || _global;
  1584. let eventName = arguments[0];
  1585. if (patchOptions && patchOptions.transferEventName) {
  1586. eventName = patchOptions.transferEventName(eventName);
  1587. }
  1588. const options = arguments[2];
  1589. const capture = !options ? false : typeof options === 'boolean' ? true : options.capture;
  1590. const delegate = arguments[1];
  1591. if (!delegate) {
  1592. return nativeRemoveEventListener.apply(this, arguments);
  1593. }
  1594. if (validateHandler &&
  1595. !validateHandler(nativeRemoveEventListener, delegate, target, arguments)) {
  1596. return;
  1597. }
  1598. const symbolEventNames = zoneSymbolEventNames[eventName];
  1599. let symbolEventName;
  1600. if (symbolEventNames) {
  1601. symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
  1602. }
  1603. const existingTasks = symbolEventName && target[symbolEventName];
  1604. // `existingTasks` may not exist if the `addEventListener` was called before
  1605. // it was patched by zone.js. Please refer to the attached issue for
  1606. // clarification, particularly after the `if` condition, before calling
  1607. // the native `removeEventListener`.
  1608. if (existingTasks) {
  1609. for (let i = 0; i < existingTasks.length; i++) {
  1610. const existingTask = existingTasks[i];
  1611. if (compare(existingTask, delegate)) {
  1612. existingTasks.splice(i, 1);
  1613. // set isRemoved to data for faster invokeTask check
  1614. existingTask.isRemoved = true;
  1615. if (existingTasks.length === 0) {
  1616. // all tasks for the eventName + capture have gone,
  1617. // remove globalZoneAwareCallback and remove the task cache from target
  1618. existingTask.allRemoved = true;
  1619. target[symbolEventName] = null;
  1620. // in the target, we have an event listener which is added by on_property
  1621. // such as target.onclick = function() {}, so we need to clear this internal
  1622. // property too if all delegates with capture=false were removed
  1623. // https:// github.com/angular/angular/issues/31643
  1624. // https://github.com/angular/angular/issues/54581
  1625. if (!capture && typeof eventName === 'string') {
  1626. const onPropertySymbol = ZONE_SYMBOL_PREFIX + 'ON_PROPERTY' + eventName;
  1627. target[onPropertySymbol] = null;
  1628. }
  1629. }
  1630. // In all other conditions, when `addEventListener` is called after being
  1631. // patched by zone.js, we would always find an event task on the `EventTarget`.
  1632. // This will trigger `cancelFn` on the `existingTask`, leading to `customCancelGlobal`,
  1633. // which ultimately removes an event listener and cleans up the abort listener
  1634. // (if an `AbortSignal` was provided when scheduling a task).
  1635. existingTask.zone.cancelTask(existingTask);
  1636. if (returnTarget) {
  1637. return target;
  1638. }
  1639. return;
  1640. }
  1641. }
  1642. }
  1643. // https://github.com/angular/zone.js/issues/930
  1644. // We may encounter a situation where the `addEventListener` was
  1645. // called on the event target before zone.js is loaded, resulting
  1646. // in no task being stored on the event target due to its invocation
  1647. // of the native implementation. In this scenario, we simply need to
  1648. // invoke the native `removeEventListener`.
  1649. return nativeRemoveEventListener.apply(this, arguments);
  1650. };
  1651. proto[LISTENERS_EVENT_LISTENER] = function () {
  1652. const target = this || _global;
  1653. let eventName = arguments[0];
  1654. if (patchOptions && patchOptions.transferEventName) {
  1655. eventName = patchOptions.transferEventName(eventName);
  1656. }
  1657. const listeners = [];
  1658. const tasks = findEventTasks(target, eventNameToString ? eventNameToString(eventName) : eventName);
  1659. for (let i = 0; i < tasks.length; i++) {
  1660. const task = tasks[i];
  1661. let delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  1662. listeners.push(delegate);
  1663. }
  1664. return listeners;
  1665. };
  1666. proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER] = function () {
  1667. const target = this || _global;
  1668. let eventName = arguments[0];
  1669. if (!eventName) {
  1670. const keys = Object.keys(target);
  1671. for (let i = 0; i < keys.length; i++) {
  1672. const prop = keys[i];
  1673. const match = EVENT_NAME_SYMBOL_REGX.exec(prop);
  1674. let evtName = match && match[1];
  1675. // in nodejs EventEmitter, removeListener event is
  1676. // used for monitoring the removeListener call,
  1677. // so just keep removeListener eventListener until
  1678. // all other eventListeners are removed
  1679. if (evtName && evtName !== 'removeListener') {
  1680. this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, evtName);
  1681. }
  1682. }
  1683. // remove removeListener listener finally
  1684. this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, 'removeListener');
  1685. }
  1686. else {
  1687. if (patchOptions && patchOptions.transferEventName) {
  1688. eventName = patchOptions.transferEventName(eventName);
  1689. }
  1690. const symbolEventNames = zoneSymbolEventNames[eventName];
  1691. if (symbolEventNames) {
  1692. const symbolEventName = symbolEventNames[FALSE_STR];
  1693. const symbolCaptureEventName = symbolEventNames[TRUE_STR];
  1694. const tasks = target[symbolEventName];
  1695. const captureTasks = target[symbolCaptureEventName];
  1696. if (tasks) {
  1697. const removeTasks = tasks.slice();
  1698. for (let i = 0; i < removeTasks.length; i++) {
  1699. const task = removeTasks[i];
  1700. let delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  1701. this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
  1702. }
  1703. }
  1704. if (captureTasks) {
  1705. const removeTasks = captureTasks.slice();
  1706. for (let i = 0; i < removeTasks.length; i++) {
  1707. const task = removeTasks[i];
  1708. let delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  1709. this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
  1710. }
  1711. }
  1712. }
  1713. }
  1714. if (returnTarget) {
  1715. return this;
  1716. }
  1717. };
  1718. // for native toString patch
  1719. attachOriginToPatched(proto[ADD_EVENT_LISTENER], nativeAddEventListener);
  1720. attachOriginToPatched(proto[REMOVE_EVENT_LISTENER], nativeRemoveEventListener);
  1721. if (nativeRemoveAllListeners) {
  1722. attachOriginToPatched(proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER], nativeRemoveAllListeners);
  1723. }
  1724. if (nativeListeners) {
  1725. attachOriginToPatched(proto[LISTENERS_EVENT_LISTENER], nativeListeners);
  1726. }
  1727. return true;
  1728. }
  1729. let results = [];
  1730. for (let i = 0; i < apis.length; i++) {
  1731. results[i] = patchEventTargetMethods(apis[i], patchOptions);
  1732. }
  1733. return results;
  1734. }
  1735. function findEventTasks(target, eventName) {
  1736. if (!eventName) {
  1737. const foundTasks = [];
  1738. for (let prop in target) {
  1739. const match = EVENT_NAME_SYMBOL_REGX.exec(prop);
  1740. let evtName = match && match[1];
  1741. if (evtName && (!eventName || evtName === eventName)) {
  1742. const tasks = target[prop];
  1743. if (tasks) {
  1744. for (let i = 0; i < tasks.length; i++) {
  1745. foundTasks.push(tasks[i]);
  1746. }
  1747. }
  1748. }
  1749. }
  1750. return foundTasks;
  1751. }
  1752. let symbolEventName = zoneSymbolEventNames[eventName];
  1753. if (!symbolEventName) {
  1754. prepareEventNames(eventName);
  1755. symbolEventName = zoneSymbolEventNames[eventName];
  1756. }
  1757. const captureFalseTasks = target[symbolEventName[FALSE_STR]];
  1758. const captureTrueTasks = target[symbolEventName[TRUE_STR]];
  1759. if (!captureFalseTasks) {
  1760. return captureTrueTasks ? captureTrueTasks.slice() : [];
  1761. }
  1762. else {
  1763. return captureTrueTasks
  1764. ? captureFalseTasks.concat(captureTrueTasks)
  1765. : captureFalseTasks.slice();
  1766. }
  1767. }
  1768. function patchEventPrototype(global, api) {
  1769. const Event = global['Event'];
  1770. if (Event && Event.prototype) {
  1771. api.patchMethod(Event.prototype, 'stopImmediatePropagation', (delegate) => function (self, args) {
  1772. self[IMMEDIATE_PROPAGATION_SYMBOL] = true;
  1773. // we need to call the native stopImmediatePropagation
  1774. // in case in some hybrid application, some part of
  1775. // application will be controlled by zone, some are not
  1776. delegate && delegate.apply(self, args);
  1777. });
  1778. }
  1779. }
  1780. /**
  1781. * @fileoverview
  1782. * @suppress {missingRequire}
  1783. */
  1784. function patchQueueMicrotask(global, api) {
  1785. api.patchMethod(global, 'queueMicrotask', (delegate) => {
  1786. return function (self, args) {
  1787. Zone.current.scheduleMicroTask('queueMicrotask', args[0]);
  1788. };
  1789. });
  1790. }
  1791. /**
  1792. * @fileoverview
  1793. * @suppress {missingRequire}
  1794. */
  1795. const taskSymbol = zoneSymbol('zoneTask');
  1796. function patchTimer(window, setName, cancelName, nameSuffix) {
  1797. let setNative = null;
  1798. let clearNative = null;
  1799. setName += nameSuffix;
  1800. cancelName += nameSuffix;
  1801. const tasksByHandleId = {};
  1802. function scheduleTask(task) {
  1803. const data = task.data;
  1804. data.args[0] = function () {
  1805. return task.invoke.apply(this, arguments);
  1806. };
  1807. const handleOrId = setNative.apply(window, data.args);
  1808. // Whlist on Node.js when get can the ID by using `[Symbol.toPrimitive]()` we do
  1809. // to this so that we do not cause potentally leaks when using `setTimeout`
  1810. // since this can be periodic when using `.refresh`.
  1811. if (isNumber(handleOrId)) {
  1812. data.handleId = handleOrId;
  1813. }
  1814. else {
  1815. data.handle = handleOrId;
  1816. // On Node.js a timeout and interval can be restarted over and over again by using the `.refresh` method.
  1817. data.isRefreshable = isFunction(handleOrId.refresh);
  1818. }
  1819. return task;
  1820. }
  1821. function clearTask(task) {
  1822. const { handle, handleId } = task.data;
  1823. return clearNative.call(window, handle ?? handleId);
  1824. }
  1825. setNative = patchMethod(window, setName, (delegate) => function (self, args) {
  1826. if (isFunction(args[0])) {
  1827. const options = {
  1828. isRefreshable: false,
  1829. isPeriodic: nameSuffix === 'Interval',
  1830. delay: nameSuffix === 'Timeout' || nameSuffix === 'Interval' ? args[1] || 0 : undefined,
  1831. args: args,
  1832. };
  1833. const callback = args[0];
  1834. args[0] = function timer() {
  1835. try {
  1836. return callback.apply(this, arguments);
  1837. }
  1838. finally {
  1839. // issue-934, task will be cancelled
  1840. // even it is a periodic task such as
  1841. // setInterval
  1842. // https://github.com/angular/angular/issues/40387
  1843. // Cleanup tasksByHandleId should be handled before scheduleTask
  1844. // Since some zoneSpec may intercept and doesn't trigger
  1845. // scheduleFn(scheduleTask) provided here.
  1846. const { handle, handleId, isPeriodic, isRefreshable } = options;
  1847. if (!isPeriodic && !isRefreshable) {
  1848. if (handleId) {
  1849. // in non-nodejs env, we remove timerId
  1850. // from local cache
  1851. delete tasksByHandleId[handleId];
  1852. }
  1853. else if (handle) {
  1854. // Node returns complex objects as handleIds
  1855. // we remove task reference from timer object
  1856. handle[taskSymbol] = null;
  1857. }
  1858. }
  1859. }
  1860. };
  1861. const task = scheduleMacroTaskWithCurrentZone(setName, args[0], options, scheduleTask, clearTask);
  1862. if (!task) {
  1863. return task;
  1864. }
  1865. // Node.js must additionally support the ref and unref functions.
  1866. const { handleId, handle, isRefreshable, isPeriodic } = task.data;
  1867. if (handleId) {
  1868. // for non nodejs env, we save handleId: task
  1869. // mapping in local cache for clearTimeout
  1870. tasksByHandleId[handleId] = task;
  1871. }
  1872. else if (handle) {
  1873. // for nodejs env, we save task
  1874. // reference in timerId Object for clearTimeout
  1875. handle[taskSymbol] = task;
  1876. if (isRefreshable && !isPeriodic) {
  1877. const originalRefresh = handle.refresh;
  1878. handle.refresh = function () {
  1879. const { zone, state } = task;
  1880. if (state === 'notScheduled') {
  1881. task._state = 'scheduled';
  1882. zone._updateTaskCount(task, 1);
  1883. }
  1884. else if (state === 'running') {
  1885. task._state = 'scheduling';
  1886. }
  1887. return originalRefresh.call(this);
  1888. };
  1889. }
  1890. }
  1891. return handle ?? handleId ?? task;
  1892. }
  1893. else {
  1894. // cause an error by calling it directly.
  1895. return delegate.apply(window, args);
  1896. }
  1897. });
  1898. clearNative = patchMethod(window, cancelName, (delegate) => function (self, args) {
  1899. const id = args[0];
  1900. let task;
  1901. if (isNumber(id)) {
  1902. // non nodejs env.
  1903. task = tasksByHandleId[id];
  1904. delete tasksByHandleId[id];
  1905. }
  1906. else {
  1907. // nodejs env ?? other environments.
  1908. task = id?.[taskSymbol];
  1909. if (task) {
  1910. id[taskSymbol] = null;
  1911. }
  1912. else {
  1913. task = id;
  1914. }
  1915. }
  1916. if (task?.type) {
  1917. if (task.cancelFn) {
  1918. // Do not cancel already canceled functions
  1919. task.zone.cancelTask(task);
  1920. }
  1921. }
  1922. else {
  1923. // cause an error by calling it directly.
  1924. delegate.apply(window, args);
  1925. }
  1926. });
  1927. }
  1928. function patchCustomElements(_global, api) {
  1929. const { isBrowser, isMix } = api.getGlobalObjects();
  1930. if ((!isBrowser && !isMix) || !_global['customElements'] || !('customElements' in _global)) {
  1931. return;
  1932. }
  1933. // https://html.spec.whatwg.org/multipage/custom-elements.html#concept-custom-element-definition-lifecycle-callbacks
  1934. const callbacks = [
  1935. 'connectedCallback',
  1936. 'disconnectedCallback',
  1937. 'adoptedCallback',
  1938. 'attributeChangedCallback',
  1939. 'formAssociatedCallback',
  1940. 'formDisabledCallback',
  1941. 'formResetCallback',
  1942. 'formStateRestoreCallback',
  1943. ];
  1944. api.patchCallbacks(api, _global.customElements, 'customElements', 'define', callbacks);
  1945. }
  1946. function eventTargetPatch(_global, api) {
  1947. if (Zone[api.symbol('patchEventTarget')]) {
  1948. // EventTarget is already patched.
  1949. return;
  1950. }
  1951. const { eventNames, zoneSymbolEventNames, TRUE_STR, FALSE_STR, ZONE_SYMBOL_PREFIX } = api.getGlobalObjects();
  1952. // predefine all __zone_symbol__ + eventName + true/false string
  1953. for (let i = 0; i < eventNames.length; i++) {
  1954. const eventName = eventNames[i];
  1955. const falseEventName = eventName + FALSE_STR;
  1956. const trueEventName = eventName + TRUE_STR;
  1957. const symbol = ZONE_SYMBOL_PREFIX + falseEventName;
  1958. const symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
  1959. zoneSymbolEventNames[eventName] = {};
  1960. zoneSymbolEventNames[eventName][FALSE_STR] = symbol;
  1961. zoneSymbolEventNames[eventName][TRUE_STR] = symbolCapture;
  1962. }
  1963. const EVENT_TARGET = _global['EventTarget'];
  1964. if (!EVENT_TARGET || !EVENT_TARGET.prototype) {
  1965. return;
  1966. }
  1967. api.patchEventTarget(_global, api, [EVENT_TARGET && EVENT_TARGET.prototype]);
  1968. return true;
  1969. }
  1970. function patchEvent(global, api) {
  1971. api.patchEventPrototype(global, api);
  1972. }
  1973. /**
  1974. * @fileoverview
  1975. * @suppress {globalThis}
  1976. */
  1977. function filterProperties(target, onProperties, ignoreProperties) {
  1978. if (!ignoreProperties || ignoreProperties.length === 0) {
  1979. return onProperties;
  1980. }
  1981. const tip = ignoreProperties.filter((ip) => ip.target === target);
  1982. if (!tip || tip.length === 0) {
  1983. return onProperties;
  1984. }
  1985. const targetIgnoreProperties = tip[0].ignoreProperties;
  1986. return onProperties.filter((op) => targetIgnoreProperties.indexOf(op) === -1);
  1987. }
  1988. function patchFilteredProperties(target, onProperties, ignoreProperties, prototype) {
  1989. // check whether target is available, sometimes target will be undefined
  1990. // because different browser or some 3rd party plugin.
  1991. if (!target) {
  1992. return;
  1993. }
  1994. const filteredProperties = filterProperties(target, onProperties, ignoreProperties);
  1995. patchOnProperties(target, filteredProperties, prototype);
  1996. }
  1997. /**
  1998. * Get all event name properties which the event name startsWith `on`
  1999. * from the target object itself, inherited properties are not considered.
  2000. */
  2001. function getOnEventNames(target) {
  2002. return Object.getOwnPropertyNames(target)
  2003. .filter((name) => name.startsWith('on') && name.length > 2)
  2004. .map((name) => name.substring(2));
  2005. }
  2006. function propertyDescriptorPatch(api, _global) {
  2007. if (isNode && !isMix) {
  2008. return;
  2009. }
  2010. if (Zone[api.symbol('patchEvents')]) {
  2011. // events are already been patched by legacy patch.
  2012. return;
  2013. }
  2014. const ignoreProperties = _global['__Zone_ignore_on_properties'];
  2015. // for browsers that we can patch the descriptor: Chrome & Firefox
  2016. let patchTargets = [];
  2017. if (isBrowser) {
  2018. const internalWindow = window;
  2019. patchTargets = patchTargets.concat([
  2020. 'Document',
  2021. 'SVGElement',
  2022. 'Element',
  2023. 'HTMLElement',
  2024. 'HTMLBodyElement',
  2025. 'HTMLMediaElement',
  2026. 'HTMLFrameSetElement',
  2027. 'HTMLFrameElement',
  2028. 'HTMLIFrameElement',
  2029. 'HTMLMarqueeElement',
  2030. 'Worker',
  2031. ]);
  2032. const ignoreErrorProperties = isIE()
  2033. ? [{ target: internalWindow, ignoreProperties: ['error'] }]
  2034. : [];
  2035. // in IE/Edge, onProp not exist in window object, but in WindowPrototype
  2036. // so we need to pass WindowPrototype to check onProp exist or not
  2037. patchFilteredProperties(internalWindow, getOnEventNames(internalWindow), ignoreProperties ? ignoreProperties.concat(ignoreErrorProperties) : ignoreProperties, ObjectGetPrototypeOf(internalWindow));
  2038. }
  2039. patchTargets = patchTargets.concat([
  2040. 'XMLHttpRequest',
  2041. 'XMLHttpRequestEventTarget',
  2042. 'IDBIndex',
  2043. 'IDBRequest',
  2044. 'IDBOpenDBRequest',
  2045. 'IDBDatabase',
  2046. 'IDBTransaction',
  2047. 'IDBCursor',
  2048. 'WebSocket',
  2049. ]);
  2050. for (let i = 0; i < patchTargets.length; i++) {
  2051. const target = _global[patchTargets[i]];
  2052. target &&
  2053. target.prototype &&
  2054. patchFilteredProperties(target.prototype, getOnEventNames(target.prototype), ignoreProperties);
  2055. }
  2056. }
  2057. /**
  2058. * @fileoverview
  2059. * @suppress {missingRequire}
  2060. */
  2061. function patchBrowser(Zone) {
  2062. Zone.__load_patch('legacy', (global) => {
  2063. const legacyPatch = global[Zone.__symbol__('legacyPatch')];
  2064. if (legacyPatch) {
  2065. legacyPatch();
  2066. }
  2067. });
  2068. Zone.__load_patch('timers', (global) => {
  2069. const set = 'set';
  2070. const clear = 'clear';
  2071. patchTimer(global, set, clear, 'Timeout');
  2072. patchTimer(global, set, clear, 'Interval');
  2073. patchTimer(global, set, clear, 'Immediate');
  2074. });
  2075. Zone.__load_patch('requestAnimationFrame', (global) => {
  2076. patchTimer(global, 'request', 'cancel', 'AnimationFrame');
  2077. patchTimer(global, 'mozRequest', 'mozCancel', 'AnimationFrame');
  2078. patchTimer(global, 'webkitRequest', 'webkitCancel', 'AnimationFrame');
  2079. });
  2080. Zone.__load_patch('blocking', (global, Zone) => {
  2081. const blockingMethods = ['alert', 'prompt', 'confirm'];
  2082. for (let i = 0; i < blockingMethods.length; i++) {
  2083. const name = blockingMethods[i];
  2084. patchMethod(global, name, (delegate, symbol, name) => {
  2085. return function (s, args) {
  2086. return Zone.current.run(delegate, global, args, name);
  2087. };
  2088. });
  2089. }
  2090. });
  2091. Zone.__load_patch('EventTarget', (global, Zone, api) => {
  2092. patchEvent(global, api);
  2093. eventTargetPatch(global, api);
  2094. // patch XMLHttpRequestEventTarget's addEventListener/removeEventListener
  2095. const XMLHttpRequestEventTarget = global['XMLHttpRequestEventTarget'];
  2096. if (XMLHttpRequestEventTarget && XMLHttpRequestEventTarget.prototype) {
  2097. api.patchEventTarget(global, api, [XMLHttpRequestEventTarget.prototype]);
  2098. }
  2099. });
  2100. Zone.__load_patch('MutationObserver', (global, Zone, api) => {
  2101. patchClass('MutationObserver');
  2102. patchClass('WebKitMutationObserver');
  2103. });
  2104. Zone.__load_patch('IntersectionObserver', (global, Zone, api) => {
  2105. patchClass('IntersectionObserver');
  2106. });
  2107. Zone.__load_patch('FileReader', (global, Zone, api) => {
  2108. patchClass('FileReader');
  2109. });
  2110. Zone.__load_patch('on_property', (global, Zone, api) => {
  2111. propertyDescriptorPatch(api, global);
  2112. });
  2113. Zone.__load_patch('customElements', (global, Zone, api) => {
  2114. patchCustomElements(global, api);
  2115. });
  2116. Zone.__load_patch('XHR', (global, Zone) => {
  2117. // Treat XMLHttpRequest as a macrotask.
  2118. patchXHR(global);
  2119. const XHR_TASK = zoneSymbol('xhrTask');
  2120. const XHR_SYNC = zoneSymbol('xhrSync');
  2121. const XHR_LISTENER = zoneSymbol('xhrListener');
  2122. const XHR_SCHEDULED = zoneSymbol('xhrScheduled');
  2123. const XHR_URL = zoneSymbol('xhrURL');
  2124. const XHR_ERROR_BEFORE_SCHEDULED = zoneSymbol('xhrErrorBeforeScheduled');
  2125. function patchXHR(window) {
  2126. const XMLHttpRequest = window['XMLHttpRequest'];
  2127. if (!XMLHttpRequest) {
  2128. // XMLHttpRequest is not available in service worker
  2129. return;
  2130. }
  2131. const XMLHttpRequestPrototype = XMLHttpRequest.prototype;
  2132. function findPendingTask(target) {
  2133. return target[XHR_TASK];
  2134. }
  2135. let oriAddListener = XMLHttpRequestPrototype[ZONE_SYMBOL_ADD_EVENT_LISTENER];
  2136. let oriRemoveListener = XMLHttpRequestPrototype[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
  2137. if (!oriAddListener) {
  2138. const XMLHttpRequestEventTarget = window['XMLHttpRequestEventTarget'];
  2139. if (XMLHttpRequestEventTarget) {
  2140. const XMLHttpRequestEventTargetPrototype = XMLHttpRequestEventTarget.prototype;
  2141. oriAddListener = XMLHttpRequestEventTargetPrototype[ZONE_SYMBOL_ADD_EVENT_LISTENER];
  2142. oriRemoveListener = XMLHttpRequestEventTargetPrototype[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
  2143. }
  2144. }
  2145. const READY_STATE_CHANGE = 'readystatechange';
  2146. const SCHEDULED = 'scheduled';
  2147. function scheduleTask(task) {
  2148. const data = task.data;
  2149. const target = data.target;
  2150. target[XHR_SCHEDULED] = false;
  2151. target[XHR_ERROR_BEFORE_SCHEDULED] = false;
  2152. // remove existing event listener
  2153. const listener = target[XHR_LISTENER];
  2154. if (!oriAddListener) {
  2155. oriAddListener = target[ZONE_SYMBOL_ADD_EVENT_LISTENER];
  2156. oriRemoveListener = target[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
  2157. }
  2158. if (listener) {
  2159. oriRemoveListener.call(target, READY_STATE_CHANGE, listener);
  2160. }
  2161. const newListener = (target[XHR_LISTENER] = () => {
  2162. if (target.readyState === target.DONE) {
  2163. // sometimes on some browsers XMLHttpRequest will fire onreadystatechange with
  2164. // readyState=4 multiple times, so we need to check task state here
  2165. if (!data.aborted && target[XHR_SCHEDULED] && task.state === SCHEDULED) {
  2166. // check whether the xhr has registered onload listener
  2167. // if that is the case, the task should invoke after all
  2168. // onload listeners finish.
  2169. // Also if the request failed without response (status = 0), the load event handler
  2170. // will not be triggered, in that case, we should also invoke the placeholder callback
  2171. // to close the XMLHttpRequest::send macroTask.
  2172. // https://github.com/angular/angular/issues/38795
  2173. const loadTasks = target[Zone.__symbol__('loadfalse')];
  2174. if (target.status !== 0 && loadTasks && loadTasks.length > 0) {
  2175. const oriInvoke = task.invoke;
  2176. task.invoke = function () {
  2177. // need to load the tasks again, because in other
  2178. // load listener, they may remove themselves
  2179. const loadTasks = target[Zone.__symbol__('loadfalse')];
  2180. for (let i = 0; i < loadTasks.length; i++) {
  2181. if (loadTasks[i] === task) {
  2182. loadTasks.splice(i, 1);
  2183. }
  2184. }
  2185. if (!data.aborted && task.state === SCHEDULED) {
  2186. oriInvoke.call(task);
  2187. }
  2188. };
  2189. loadTasks.push(task);
  2190. }
  2191. else {
  2192. task.invoke();
  2193. }
  2194. }
  2195. else if (!data.aborted && target[XHR_SCHEDULED] === false) {
  2196. // error occurs when xhr.send()
  2197. target[XHR_ERROR_BEFORE_SCHEDULED] = true;
  2198. }
  2199. }
  2200. });
  2201. oriAddListener.call(target, READY_STATE_CHANGE, newListener);
  2202. const storedTask = target[XHR_TASK];
  2203. if (!storedTask) {
  2204. target[XHR_TASK] = task;
  2205. }
  2206. sendNative.apply(target, data.args);
  2207. target[XHR_SCHEDULED] = true;
  2208. return task;
  2209. }
  2210. function placeholderCallback() { }
  2211. function clearTask(task) {
  2212. const data = task.data;
  2213. // Note - ideally, we would call data.target.removeEventListener here, but it's too late
  2214. // to prevent it from firing. So instead, we store info for the event listener.
  2215. data.aborted = true;
  2216. return abortNative.apply(data.target, data.args);
  2217. }
  2218. const openNative = patchMethod(XMLHttpRequestPrototype, 'open', () => function (self, args) {
  2219. self[XHR_SYNC] = args[2] == false;
  2220. self[XHR_URL] = args[1];
  2221. return openNative.apply(self, args);
  2222. });
  2223. const XMLHTTPREQUEST_SOURCE = 'XMLHttpRequest.send';
  2224. const fetchTaskAborting = zoneSymbol('fetchTaskAborting');
  2225. const fetchTaskScheduling = zoneSymbol('fetchTaskScheduling');
  2226. const sendNative = patchMethod(XMLHttpRequestPrototype, 'send', () => function (self, args) {
  2227. if (Zone.current[fetchTaskScheduling] === true) {
  2228. // a fetch is scheduling, so we are using xhr to polyfill fetch
  2229. // and because we already schedule macroTask for fetch, we should
  2230. // not schedule a macroTask for xhr again
  2231. return sendNative.apply(self, args);
  2232. }
  2233. if (self[XHR_SYNC]) {
  2234. // if the XHR is sync there is no task to schedule, just execute the code.
  2235. return sendNative.apply(self, args);
  2236. }
  2237. else {
  2238. const options = {
  2239. target: self,
  2240. url: self[XHR_URL],
  2241. isPeriodic: false,
  2242. args: args,
  2243. aborted: false,
  2244. };
  2245. const task = scheduleMacroTaskWithCurrentZone(XMLHTTPREQUEST_SOURCE, placeholderCallback, options, scheduleTask, clearTask);
  2246. if (self &&
  2247. self[XHR_ERROR_BEFORE_SCHEDULED] === true &&
  2248. !options.aborted &&
  2249. task.state === SCHEDULED) {
  2250. // xhr request throw error when send
  2251. // we should invoke task instead of leaving a scheduled
  2252. // pending macroTask
  2253. task.invoke();
  2254. }
  2255. }
  2256. });
  2257. const abortNative = patchMethod(XMLHttpRequestPrototype, 'abort', () => function (self, args) {
  2258. const task = findPendingTask(self);
  2259. if (task && typeof task.type == 'string') {
  2260. // If the XHR has already completed, do nothing.
  2261. // If the XHR has already been aborted, do nothing.
  2262. // Fix #569, call abort multiple times before done will cause
  2263. // macroTask task count be negative number
  2264. if (task.cancelFn == null || (task.data && task.data.aborted)) {
  2265. return;
  2266. }
  2267. task.zone.cancelTask(task);
  2268. }
  2269. else if (Zone.current[fetchTaskAborting] === true) {
  2270. // the abort is called from fetch polyfill, we need to call native abort of XHR.
  2271. return abortNative.apply(self, args);
  2272. }
  2273. // Otherwise, we are trying to abort an XHR which has not yet been sent, so there is no
  2274. // task
  2275. // to cancel. Do nothing.
  2276. });
  2277. }
  2278. });
  2279. Zone.__load_patch('geolocation', (global) => {
  2280. /// GEO_LOCATION
  2281. if (global['navigator'] && global['navigator'].geolocation) {
  2282. patchPrototype(global['navigator'].geolocation, ['getCurrentPosition', 'watchPosition']);
  2283. }
  2284. });
  2285. Zone.__load_patch('PromiseRejectionEvent', (global, Zone) => {
  2286. // handle unhandled promise rejection
  2287. function findPromiseRejectionHandler(evtName) {
  2288. return function (e) {
  2289. const eventTasks = findEventTasks(global, evtName);
  2290. eventTasks.forEach((eventTask) => {
  2291. // windows has added unhandledrejection event listener
  2292. // trigger the event listener
  2293. const PromiseRejectionEvent = global['PromiseRejectionEvent'];
  2294. if (PromiseRejectionEvent) {
  2295. const evt = new PromiseRejectionEvent(evtName, {
  2296. promise: e.promise,
  2297. reason: e.rejection,
  2298. });
  2299. eventTask.invoke(evt);
  2300. }
  2301. });
  2302. };
  2303. }
  2304. if (global['PromiseRejectionEvent']) {
  2305. Zone[zoneSymbol('unhandledPromiseRejectionHandler')] =
  2306. findPromiseRejectionHandler('unhandledrejection');
  2307. Zone[zoneSymbol('rejectionHandledHandler')] =
  2308. findPromiseRejectionHandler('rejectionhandled');
  2309. }
  2310. });
  2311. Zone.__load_patch('queueMicrotask', (global, Zone, api) => {
  2312. patchQueueMicrotask(global, api);
  2313. });
  2314. }
  2315. function patchPromise(Zone) {
  2316. Zone.__load_patch('ZoneAwarePromise', (global, Zone, api) => {
  2317. const ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  2318. const ObjectDefineProperty = Object.defineProperty;
  2319. function readableObjectToString(obj) {
  2320. if (obj && obj.toString === Object.prototype.toString) {
  2321. const className = obj.constructor && obj.constructor.name;
  2322. return (className ? className : '') + ': ' + JSON.stringify(obj);
  2323. }
  2324. return obj ? obj.toString() : Object.prototype.toString.call(obj);
  2325. }
  2326. const __symbol__ = api.symbol;
  2327. const _uncaughtPromiseErrors = [];
  2328. const isDisableWrappingUncaughtPromiseRejection = global[__symbol__('DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION')] !== false;
  2329. const symbolPromise = __symbol__('Promise');
  2330. const symbolThen = __symbol__('then');
  2331. const creationTrace = '__creationTrace__';
  2332. api.onUnhandledError = (e) => {
  2333. if (api.showUncaughtError()) {
  2334. const rejection = e && e.rejection;
  2335. if (rejection) {
  2336. 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);
  2337. }
  2338. else {
  2339. console.error(e);
  2340. }
  2341. }
  2342. };
  2343. api.microtaskDrainDone = () => {
  2344. while (_uncaughtPromiseErrors.length) {
  2345. const uncaughtPromiseError = _uncaughtPromiseErrors.shift();
  2346. try {
  2347. uncaughtPromiseError.zone.runGuarded(() => {
  2348. if (uncaughtPromiseError.throwOriginal) {
  2349. throw uncaughtPromiseError.rejection;
  2350. }
  2351. throw uncaughtPromiseError;
  2352. });
  2353. }
  2354. catch (error) {
  2355. handleUnhandledRejection(error);
  2356. }
  2357. }
  2358. };
  2359. const UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL = __symbol__('unhandledPromiseRejectionHandler');
  2360. function handleUnhandledRejection(e) {
  2361. api.onUnhandledError(e);
  2362. try {
  2363. const handler = Zone[UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL];
  2364. if (typeof handler === 'function') {
  2365. handler.call(this, e);
  2366. }
  2367. }
  2368. catch (err) { }
  2369. }
  2370. function isThenable(value) {
  2371. return value && value.then;
  2372. }
  2373. function forwardResolution(value) {
  2374. return value;
  2375. }
  2376. function forwardRejection(rejection) {
  2377. return ZoneAwarePromise.reject(rejection);
  2378. }
  2379. const symbolState = __symbol__('state');
  2380. const symbolValue = __symbol__('value');
  2381. const symbolFinally = __symbol__('finally');
  2382. const symbolParentPromiseValue = __symbol__('parentPromiseValue');
  2383. const symbolParentPromiseState = __symbol__('parentPromiseState');
  2384. const source = 'Promise.then';
  2385. const UNRESOLVED = null;
  2386. const RESOLVED = true;
  2387. const REJECTED = false;
  2388. const REJECTED_NO_CATCH = 0;
  2389. function makeResolver(promise, state) {
  2390. return (v) => {
  2391. try {
  2392. resolvePromise(promise, state, v);
  2393. }
  2394. catch (err) {
  2395. resolvePromise(promise, false, err);
  2396. }
  2397. // Do not return value or you will break the Promise spec.
  2398. };
  2399. }
  2400. const once = function () {
  2401. let wasCalled = false;
  2402. return function wrapper(wrappedFunction) {
  2403. return function () {
  2404. if (wasCalled) {
  2405. return;
  2406. }
  2407. wasCalled = true;
  2408. wrappedFunction.apply(null, arguments);
  2409. };
  2410. };
  2411. };
  2412. const TYPE_ERROR = 'Promise resolved with itself';
  2413. const CURRENT_TASK_TRACE_SYMBOL = __symbol__('currentTaskTrace');
  2414. // Promise Resolution
  2415. function resolvePromise(promise, state, value) {
  2416. const onceWrapper = once();
  2417. if (promise === value) {
  2418. throw new TypeError(TYPE_ERROR);
  2419. }
  2420. if (promise[symbolState] === UNRESOLVED) {
  2421. // should only get value.then once based on promise spec.
  2422. let then = null;
  2423. try {
  2424. if (typeof value === 'object' || typeof value === 'function') {
  2425. then = value && value.then;
  2426. }
  2427. }
  2428. catch (err) {
  2429. onceWrapper(() => {
  2430. resolvePromise(promise, false, err);
  2431. })();
  2432. return promise;
  2433. }
  2434. // if (value instanceof ZoneAwarePromise) {
  2435. if (state !== REJECTED &&
  2436. value instanceof ZoneAwarePromise &&
  2437. value.hasOwnProperty(symbolState) &&
  2438. value.hasOwnProperty(symbolValue) &&
  2439. value[symbolState] !== UNRESOLVED) {
  2440. clearRejectedNoCatch(value);
  2441. resolvePromise(promise, value[symbolState], value[symbolValue]);
  2442. }
  2443. else if (state !== REJECTED && typeof then === 'function') {
  2444. try {
  2445. then.call(value, onceWrapper(makeResolver(promise, state)), onceWrapper(makeResolver(promise, false)));
  2446. }
  2447. catch (err) {
  2448. onceWrapper(() => {
  2449. resolvePromise(promise, false, err);
  2450. })();
  2451. }
  2452. }
  2453. else {
  2454. promise[symbolState] = state;
  2455. const queue = promise[symbolValue];
  2456. promise[symbolValue] = value;
  2457. if (promise[symbolFinally] === symbolFinally) {
  2458. // the promise is generated by Promise.prototype.finally
  2459. if (state === RESOLVED) {
  2460. // the state is resolved, should ignore the value
  2461. // and use parent promise value
  2462. promise[symbolState] = promise[symbolParentPromiseState];
  2463. promise[symbolValue] = promise[symbolParentPromiseValue];
  2464. }
  2465. }
  2466. // record task information in value when error occurs, so we can
  2467. // do some additional work such as render longStackTrace
  2468. if (state === REJECTED && value instanceof Error) {
  2469. // check if longStackTraceZone is here
  2470. const trace = Zone.currentTask &&
  2471. Zone.currentTask.data &&
  2472. Zone.currentTask.data[creationTrace];
  2473. if (trace) {
  2474. // only keep the long stack trace into error when in longStackTraceZone
  2475. ObjectDefineProperty(value, CURRENT_TASK_TRACE_SYMBOL, {
  2476. configurable: true,
  2477. enumerable: false,
  2478. writable: true,
  2479. value: trace,
  2480. });
  2481. }
  2482. }
  2483. for (let i = 0; i < queue.length;) {
  2484. scheduleResolveOrReject(promise, queue[i++], queue[i++], queue[i++], queue[i++]);
  2485. }
  2486. if (queue.length == 0 && state == REJECTED) {
  2487. promise[symbolState] = REJECTED_NO_CATCH;
  2488. let uncaughtPromiseError = value;
  2489. try {
  2490. // Here we throws a new Error to print more readable error log
  2491. // and if the value is not an error, zone.js builds an `Error`
  2492. // Object here to attach the stack information.
  2493. throw new Error('Uncaught (in promise): ' +
  2494. readableObjectToString(value) +
  2495. (value && value.stack ? '\n' + value.stack : ''));
  2496. }
  2497. catch (err) {
  2498. uncaughtPromiseError = err;
  2499. }
  2500. if (isDisableWrappingUncaughtPromiseRejection) {
  2501. // If disable wrapping uncaught promise reject
  2502. // use the value instead of wrapping it.
  2503. uncaughtPromiseError.throwOriginal = true;
  2504. }
  2505. uncaughtPromiseError.rejection = value;
  2506. uncaughtPromiseError.promise = promise;
  2507. uncaughtPromiseError.zone = Zone.current;
  2508. uncaughtPromiseError.task = Zone.currentTask;
  2509. _uncaughtPromiseErrors.push(uncaughtPromiseError);
  2510. api.scheduleMicroTask(); // to make sure that it is running
  2511. }
  2512. }
  2513. }
  2514. // Resolving an already resolved promise is a noop.
  2515. return promise;
  2516. }
  2517. const REJECTION_HANDLED_HANDLER = __symbol__('rejectionHandledHandler');
  2518. function clearRejectedNoCatch(promise) {
  2519. if (promise[symbolState] === REJECTED_NO_CATCH) {
  2520. // if the promise is rejected no catch status
  2521. // and queue.length > 0, means there is a error handler
  2522. // here to handle the rejected promise, we should trigger
  2523. // windows.rejectionhandled eventHandler or nodejs rejectionHandled
  2524. // eventHandler
  2525. try {
  2526. const handler = Zone[REJECTION_HANDLED_HANDLER];
  2527. if (handler && typeof handler === 'function') {
  2528. handler.call(this, { rejection: promise[symbolValue], promise: promise });
  2529. }
  2530. }
  2531. catch (err) { }
  2532. promise[symbolState] = REJECTED;
  2533. for (let i = 0; i < _uncaughtPromiseErrors.length; i++) {
  2534. if (promise === _uncaughtPromiseErrors[i].promise) {
  2535. _uncaughtPromiseErrors.splice(i, 1);
  2536. }
  2537. }
  2538. }
  2539. }
  2540. function scheduleResolveOrReject(promise, zone, chainPromise, onFulfilled, onRejected) {
  2541. clearRejectedNoCatch(promise);
  2542. const promiseState = promise[symbolState];
  2543. const delegate = promiseState
  2544. ? typeof onFulfilled === 'function'
  2545. ? onFulfilled
  2546. : forwardResolution
  2547. : typeof onRejected === 'function'
  2548. ? onRejected
  2549. : forwardRejection;
  2550. zone.scheduleMicroTask(source, () => {
  2551. try {
  2552. const parentPromiseValue = promise[symbolValue];
  2553. const isFinallyPromise = !!chainPromise && symbolFinally === chainPromise[symbolFinally];
  2554. if (isFinallyPromise) {
  2555. // if the promise is generated from finally call, keep parent promise's state and value
  2556. chainPromise[symbolParentPromiseValue] = parentPromiseValue;
  2557. chainPromise[symbolParentPromiseState] = promiseState;
  2558. }
  2559. // should not pass value to finally callback
  2560. const value = zone.run(delegate, undefined, isFinallyPromise && delegate !== forwardRejection && delegate !== forwardResolution
  2561. ? []
  2562. : [parentPromiseValue]);
  2563. resolvePromise(chainPromise, true, value);
  2564. }
  2565. catch (error) {
  2566. // if error occurs, should always return this error
  2567. resolvePromise(chainPromise, false, error);
  2568. }
  2569. }, chainPromise);
  2570. }
  2571. const ZONE_AWARE_PROMISE_TO_STRING = 'function ZoneAwarePromise() { [native code] }';
  2572. const noop = function () { };
  2573. const AggregateError = global.AggregateError;
  2574. class ZoneAwarePromise {
  2575. static toString() {
  2576. return ZONE_AWARE_PROMISE_TO_STRING;
  2577. }
  2578. static resolve(value) {
  2579. if (value instanceof ZoneAwarePromise) {
  2580. return value;
  2581. }
  2582. return resolvePromise(new this(null), RESOLVED, value);
  2583. }
  2584. static reject(error) {
  2585. return resolvePromise(new this(null), REJECTED, error);
  2586. }
  2587. static withResolvers() {
  2588. const result = {};
  2589. result.promise = new ZoneAwarePromise((res, rej) => {
  2590. result.resolve = res;
  2591. result.reject = rej;
  2592. });
  2593. return result;
  2594. }
  2595. static any(values) {
  2596. if (!values || typeof values[Symbol.iterator] !== 'function') {
  2597. return Promise.reject(new AggregateError([], 'All promises were rejected'));
  2598. }
  2599. const promises = [];
  2600. let count = 0;
  2601. try {
  2602. for (let v of values) {
  2603. count++;
  2604. promises.push(ZoneAwarePromise.resolve(v));
  2605. }
  2606. }
  2607. catch (err) {
  2608. return Promise.reject(new AggregateError([], 'All promises were rejected'));
  2609. }
  2610. if (count === 0) {
  2611. return Promise.reject(new AggregateError([], 'All promises were rejected'));
  2612. }
  2613. let finished = false;
  2614. const errors = [];
  2615. return new ZoneAwarePromise((resolve, reject) => {
  2616. for (let i = 0; i < promises.length; i++) {
  2617. promises[i].then((v) => {
  2618. if (finished) {
  2619. return;
  2620. }
  2621. finished = true;
  2622. resolve(v);
  2623. }, (err) => {
  2624. errors.push(err);
  2625. count--;
  2626. if (count === 0) {
  2627. finished = true;
  2628. reject(new AggregateError(errors, 'All promises were rejected'));
  2629. }
  2630. });
  2631. }
  2632. });
  2633. }
  2634. static race(values) {
  2635. let resolve;
  2636. let reject;
  2637. let promise = new this((res, rej) => {
  2638. resolve = res;
  2639. reject = rej;
  2640. });
  2641. function onResolve(value) {
  2642. resolve(value);
  2643. }
  2644. function onReject(error) {
  2645. reject(error);
  2646. }
  2647. for (let value of values) {
  2648. if (!isThenable(value)) {
  2649. value = this.resolve(value);
  2650. }
  2651. value.then(onResolve, onReject);
  2652. }
  2653. return promise;
  2654. }
  2655. static all(values) {
  2656. return ZoneAwarePromise.allWithCallback(values);
  2657. }
  2658. static allSettled(values) {
  2659. const P = this && this.prototype instanceof ZoneAwarePromise ? this : ZoneAwarePromise;
  2660. return P.allWithCallback(values, {
  2661. thenCallback: (value) => ({ status: 'fulfilled', value }),
  2662. errorCallback: (err) => ({ status: 'rejected', reason: err }),
  2663. });
  2664. }
  2665. static allWithCallback(values, callback) {
  2666. let resolve;
  2667. let reject;
  2668. let promise = new this((res, rej) => {
  2669. resolve = res;
  2670. reject = rej;
  2671. });
  2672. // Start at 2 to prevent prematurely resolving if .then is called immediately.
  2673. let unresolvedCount = 2;
  2674. let valueIndex = 0;
  2675. const resolvedValues = [];
  2676. for (let value of values) {
  2677. if (!isThenable(value)) {
  2678. value = this.resolve(value);
  2679. }
  2680. const curValueIndex = valueIndex;
  2681. try {
  2682. value.then((value) => {
  2683. resolvedValues[curValueIndex] = callback ? callback.thenCallback(value) : value;
  2684. unresolvedCount--;
  2685. if (unresolvedCount === 0) {
  2686. resolve(resolvedValues);
  2687. }
  2688. }, (err) => {
  2689. if (!callback) {
  2690. reject(err);
  2691. }
  2692. else {
  2693. resolvedValues[curValueIndex] = callback.errorCallback(err);
  2694. unresolvedCount--;
  2695. if (unresolvedCount === 0) {
  2696. resolve(resolvedValues);
  2697. }
  2698. }
  2699. });
  2700. }
  2701. catch (thenErr) {
  2702. reject(thenErr);
  2703. }
  2704. unresolvedCount++;
  2705. valueIndex++;
  2706. }
  2707. // Make the unresolvedCount zero-based again.
  2708. unresolvedCount -= 2;
  2709. if (unresolvedCount === 0) {
  2710. resolve(resolvedValues);
  2711. }
  2712. return promise;
  2713. }
  2714. constructor(executor) {
  2715. const promise = this;
  2716. if (!(promise instanceof ZoneAwarePromise)) {
  2717. throw new Error('Must be an instanceof Promise.');
  2718. }
  2719. promise[symbolState] = UNRESOLVED;
  2720. promise[symbolValue] = []; // queue;
  2721. try {
  2722. const onceWrapper = once();
  2723. executor &&
  2724. executor(onceWrapper(makeResolver(promise, RESOLVED)), onceWrapper(makeResolver(promise, REJECTED)));
  2725. }
  2726. catch (error) {
  2727. resolvePromise(promise, false, error);
  2728. }
  2729. }
  2730. get [Symbol.toStringTag]() {
  2731. return 'Promise';
  2732. }
  2733. get [Symbol.species]() {
  2734. return ZoneAwarePromise;
  2735. }
  2736. then(onFulfilled, onRejected) {
  2737. // We must read `Symbol.species` safely because `this` may be anything. For instance, `this`
  2738. // may be an object without a prototype (created through `Object.create(null)`); thus
  2739. // `this.constructor` will be undefined. One of the use cases is SystemJS creating
  2740. // prototype-less objects (modules) via `Object.create(null)`. The SystemJS creates an empty
  2741. // object and copies promise properties into that object (within the `getOrCreateLoad`
  2742. // function). The zone.js then checks if the resolved value has the `then` method and
  2743. // invokes it with the `value` context. Otherwise, this will throw an error: `TypeError:
  2744. // Cannot read properties of undefined (reading 'Symbol(Symbol.species)')`.
  2745. let C = this.constructor?.[Symbol.species];
  2746. if (!C || typeof C !== 'function') {
  2747. C = this.constructor || ZoneAwarePromise;
  2748. }
  2749. const chainPromise = new C(noop);
  2750. const zone = Zone.current;
  2751. if (this[symbolState] == UNRESOLVED) {
  2752. this[symbolValue].push(zone, chainPromise, onFulfilled, onRejected);
  2753. }
  2754. else {
  2755. scheduleResolveOrReject(this, zone, chainPromise, onFulfilled, onRejected);
  2756. }
  2757. return chainPromise;
  2758. }
  2759. catch(onRejected) {
  2760. return this.then(null, onRejected);
  2761. }
  2762. finally(onFinally) {
  2763. // See comment on the call to `then` about why thee `Symbol.species` is safely accessed.
  2764. let C = this.constructor?.[Symbol.species];
  2765. if (!C || typeof C !== 'function') {
  2766. C = ZoneAwarePromise;
  2767. }
  2768. const chainPromise = new C(noop);
  2769. chainPromise[symbolFinally] = symbolFinally;
  2770. const zone = Zone.current;
  2771. if (this[symbolState] == UNRESOLVED) {
  2772. this[symbolValue].push(zone, chainPromise, onFinally, onFinally);
  2773. }
  2774. else {
  2775. scheduleResolveOrReject(this, zone, chainPromise, onFinally, onFinally);
  2776. }
  2777. return chainPromise;
  2778. }
  2779. }
  2780. // Protect against aggressive optimizers dropping seemingly unused properties.
  2781. // E.g. Closure Compiler in advanced mode.
  2782. ZoneAwarePromise['resolve'] = ZoneAwarePromise.resolve;
  2783. ZoneAwarePromise['reject'] = ZoneAwarePromise.reject;
  2784. ZoneAwarePromise['race'] = ZoneAwarePromise.race;
  2785. ZoneAwarePromise['all'] = ZoneAwarePromise.all;
  2786. const NativePromise = (global[symbolPromise] = global['Promise']);
  2787. global['Promise'] = ZoneAwarePromise;
  2788. const symbolThenPatched = __symbol__('thenPatched');
  2789. function patchThen(Ctor) {
  2790. const proto = Ctor.prototype;
  2791. const prop = ObjectGetOwnPropertyDescriptor(proto, 'then');
  2792. if (prop && (prop.writable === false || !prop.configurable)) {
  2793. // check Ctor.prototype.then propertyDescriptor is writable or not
  2794. // in meteor env, writable is false, we should ignore such case
  2795. return;
  2796. }
  2797. const originalThen = proto.then;
  2798. // Keep a reference to the original method.
  2799. proto[symbolThen] = originalThen;
  2800. Ctor.prototype.then = function (onResolve, onReject) {
  2801. const wrapped = new ZoneAwarePromise((resolve, reject) => {
  2802. originalThen.call(this, resolve, reject);
  2803. });
  2804. return wrapped.then(onResolve, onReject);
  2805. };
  2806. Ctor[symbolThenPatched] = true;
  2807. }
  2808. api.patchThen = patchThen;
  2809. function zoneify(fn) {
  2810. return function (self, args) {
  2811. let resultPromise = fn.apply(self, args);
  2812. if (resultPromise instanceof ZoneAwarePromise) {
  2813. return resultPromise;
  2814. }
  2815. let ctor = resultPromise.constructor;
  2816. if (!ctor[symbolThenPatched]) {
  2817. patchThen(ctor);
  2818. }
  2819. return resultPromise;
  2820. };
  2821. }
  2822. if (NativePromise) {
  2823. patchThen(NativePromise);
  2824. patchMethod(global, 'fetch', (delegate) => zoneify(delegate));
  2825. }
  2826. // This is not part of public API, but it is useful for tests, so we expose it.
  2827. Promise[Zone.__symbol__('uncaughtPromiseErrors')] = _uncaughtPromiseErrors;
  2828. return ZoneAwarePromise;
  2829. });
  2830. }
  2831. function patchToString(Zone) {
  2832. // override Function.prototype.toString to make zone.js patched function
  2833. // look like native function
  2834. Zone.__load_patch('toString', (global) => {
  2835. // patch Func.prototype.toString to let them look like native
  2836. const originalFunctionToString = Function.prototype.toString;
  2837. const ORIGINAL_DELEGATE_SYMBOL = zoneSymbol('OriginalDelegate');
  2838. const PROMISE_SYMBOL = zoneSymbol('Promise');
  2839. const ERROR_SYMBOL = zoneSymbol('Error');
  2840. const newFunctionToString = function toString() {
  2841. if (typeof this === 'function') {
  2842. const originalDelegate = this[ORIGINAL_DELEGATE_SYMBOL];
  2843. if (originalDelegate) {
  2844. if (typeof originalDelegate === 'function') {
  2845. return originalFunctionToString.call(originalDelegate);
  2846. }
  2847. else {
  2848. return Object.prototype.toString.call(originalDelegate);
  2849. }
  2850. }
  2851. if (this === Promise) {
  2852. const nativePromise = global[PROMISE_SYMBOL];
  2853. if (nativePromise) {
  2854. return originalFunctionToString.call(nativePromise);
  2855. }
  2856. }
  2857. if (this === Error) {
  2858. const nativeError = global[ERROR_SYMBOL];
  2859. if (nativeError) {
  2860. return originalFunctionToString.call(nativeError);
  2861. }
  2862. }
  2863. }
  2864. return originalFunctionToString.call(this);
  2865. };
  2866. newFunctionToString[ORIGINAL_DELEGATE_SYMBOL] = originalFunctionToString;
  2867. Function.prototype.toString = newFunctionToString;
  2868. // patch Object.prototype.toString to let them look like native
  2869. const originalObjectToString = Object.prototype.toString;
  2870. const PROMISE_OBJECT_TO_STRING = '[object Promise]';
  2871. Object.prototype.toString = function () {
  2872. if (typeof Promise === 'function' && this instanceof Promise) {
  2873. return PROMISE_OBJECT_TO_STRING;
  2874. }
  2875. return originalObjectToString.call(this);
  2876. };
  2877. });
  2878. }
  2879. function patchCallbacks(api, target, targetName, method, callbacks) {
  2880. const symbol = Zone.__symbol__(method);
  2881. if (target[symbol]) {
  2882. return;
  2883. }
  2884. const nativeDelegate = (target[symbol] = target[method]);
  2885. target[method] = function (name, opts, options) {
  2886. if (opts && opts.prototype) {
  2887. callbacks.forEach(function (callback) {
  2888. const source = `${targetName}.${method}::` + callback;
  2889. const prototype = opts.prototype;
  2890. // Note: the `patchCallbacks` is used for patching the `document.registerElement` and
  2891. // `customElements.define`. We explicitly wrap the patching code into try-catch since
  2892. // callbacks may be already patched by other web components frameworks (e.g. LWC), and they
  2893. // make those properties non-writable. This means that patching callback will throw an error
  2894. // `cannot assign to read-only property`. See this code as an example:
  2895. // https://github.com/salesforce/lwc/blob/master/packages/@lwc/engine-core/src/framework/base-bridge-element.ts#L180-L186
  2896. // We don't want to stop the application rendering if we couldn't patch some
  2897. // callback, e.g. `attributeChangedCallback`.
  2898. try {
  2899. if (prototype.hasOwnProperty(callback)) {
  2900. const descriptor = api.ObjectGetOwnPropertyDescriptor(prototype, callback);
  2901. if (descriptor && descriptor.value) {
  2902. descriptor.value = api.wrapWithCurrentZone(descriptor.value, source);
  2903. api._redefineProperty(opts.prototype, callback, descriptor);
  2904. }
  2905. else if (prototype[callback]) {
  2906. prototype[callback] = api.wrapWithCurrentZone(prototype[callback], source);
  2907. }
  2908. }
  2909. else if (prototype[callback]) {
  2910. prototype[callback] = api.wrapWithCurrentZone(prototype[callback], source);
  2911. }
  2912. }
  2913. catch {
  2914. // Note: we leave the catch block empty since there's no way to handle the error related
  2915. // to non-writable property.
  2916. }
  2917. });
  2918. }
  2919. return nativeDelegate.call(target, name, opts, options);
  2920. };
  2921. api.attachOriginToPatched(target[method], nativeDelegate);
  2922. }
  2923. function patchUtil(Zone) {
  2924. Zone.__load_patch('util', (global, Zone, api) => {
  2925. // Collect native event names by looking at properties
  2926. // on the global namespace, e.g. 'onclick'.
  2927. const eventNames = getOnEventNames(global);
  2928. api.patchOnProperties = patchOnProperties;
  2929. api.patchMethod = patchMethod;
  2930. api.bindArguments = bindArguments;
  2931. api.patchMacroTask = patchMacroTask;
  2932. // In earlier version of zone.js (<0.9.0), we use env name `__zone_symbol__BLACK_LISTED_EVENTS`
  2933. // to define which events will not be patched by `Zone.js`. In newer version (>=0.9.0), we
  2934. // change the env name to `__zone_symbol__UNPATCHED_EVENTS` to keep the name consistent with
  2935. // angular repo. The `__zone_symbol__BLACK_LISTED_EVENTS` is deprecated, but it is still be
  2936. // supported for backwards compatibility.
  2937. const SYMBOL_BLACK_LISTED_EVENTS = Zone.__symbol__('BLACK_LISTED_EVENTS');
  2938. const SYMBOL_UNPATCHED_EVENTS = Zone.__symbol__('UNPATCHED_EVENTS');
  2939. if (global[SYMBOL_UNPATCHED_EVENTS]) {
  2940. global[SYMBOL_BLACK_LISTED_EVENTS] = global[SYMBOL_UNPATCHED_EVENTS];
  2941. }
  2942. if (global[SYMBOL_BLACK_LISTED_EVENTS]) {
  2943. Zone[SYMBOL_BLACK_LISTED_EVENTS] = Zone[SYMBOL_UNPATCHED_EVENTS] =
  2944. global[SYMBOL_BLACK_LISTED_EVENTS];
  2945. }
  2946. api.patchEventPrototype = patchEventPrototype;
  2947. api.patchEventTarget = patchEventTarget;
  2948. api.isIEOrEdge = isIEOrEdge;
  2949. api.ObjectDefineProperty = ObjectDefineProperty;
  2950. api.ObjectGetOwnPropertyDescriptor = ObjectGetOwnPropertyDescriptor;
  2951. api.ObjectCreate = ObjectCreate;
  2952. api.ArraySlice = ArraySlice;
  2953. api.patchClass = patchClass;
  2954. api.wrapWithCurrentZone = wrapWithCurrentZone;
  2955. api.filterProperties = filterProperties;
  2956. api.attachOriginToPatched = attachOriginToPatched;
  2957. api._redefineProperty = Object.defineProperty;
  2958. api.patchCallbacks = patchCallbacks;
  2959. api.getGlobalObjects = () => ({
  2960. globalSources,
  2961. zoneSymbolEventNames,
  2962. eventNames,
  2963. isBrowser,
  2964. isMix,
  2965. isNode,
  2966. TRUE_STR,
  2967. FALSE_STR,
  2968. ZONE_SYMBOL_PREFIX,
  2969. ADD_EVENT_LISTENER_STR,
  2970. REMOVE_EVENT_LISTENER_STR,
  2971. });
  2972. });
  2973. }
  2974. function patchCommon(Zone) {
  2975. patchPromise(Zone);
  2976. patchToString(Zone);
  2977. patchUtil(Zone);
  2978. }
  2979. function patchEvents(Zone) {
  2980. Zone.__load_patch('EventEmitter', (global, Zone, api) => {
  2981. // For EventEmitter
  2982. const EE_ADD_LISTENER = 'addListener';
  2983. const EE_PREPEND_LISTENER = 'prependListener';
  2984. const EE_REMOVE_LISTENER = 'removeListener';
  2985. const EE_REMOVE_ALL_LISTENER = 'removeAllListeners';
  2986. const EE_LISTENERS = 'listeners';
  2987. const EE_ON = 'on';
  2988. const EE_OFF = 'off';
  2989. const compareTaskCallbackVsDelegate = function (task, delegate) {
  2990. // same callback, same capture, same event name, just return
  2991. return task.callback === delegate || task.callback.listener === delegate;
  2992. };
  2993. const eventNameToString = function (eventName) {
  2994. if (typeof eventName === 'string') {
  2995. return eventName;
  2996. }
  2997. if (!eventName) {
  2998. return '';
  2999. }
  3000. return eventName.toString().replace('(', '_').replace(')', '_');
  3001. };
  3002. function patchEventEmitterMethods(obj) {
  3003. const result = patchEventTarget(global, api, [obj], {
  3004. useG: false,
  3005. add: EE_ADD_LISTENER,
  3006. rm: EE_REMOVE_LISTENER,
  3007. prepend: EE_PREPEND_LISTENER,
  3008. rmAll: EE_REMOVE_ALL_LISTENER,
  3009. listeners: EE_LISTENERS,
  3010. chkDup: false,
  3011. rt: true,
  3012. diff: compareTaskCallbackVsDelegate,
  3013. eventNameToString: eventNameToString,
  3014. });
  3015. if (result && result[0]) {
  3016. obj[EE_ON] = obj[EE_ADD_LISTENER];
  3017. obj[EE_OFF] = obj[EE_REMOVE_LISTENER];
  3018. }
  3019. }
  3020. // EventEmitter
  3021. let events;
  3022. try {
  3023. events = require('events');
  3024. }
  3025. catch (err) { }
  3026. if (events && events.EventEmitter) {
  3027. patchEventEmitterMethods(events.EventEmitter.prototype);
  3028. }
  3029. });
  3030. }
  3031. function patchFs(Zone) {
  3032. Zone.__load_patch('fs', (global, Zone, api) => {
  3033. let fs;
  3034. try {
  3035. fs = require('fs');
  3036. }
  3037. catch (err) { }
  3038. if (!fs)
  3039. return;
  3040. // watch, watchFile, unwatchFile has been patched
  3041. // because EventEmitter has been patched
  3042. const TO_PATCH_MACROTASK_METHODS = [
  3043. 'access',
  3044. 'appendFile',
  3045. 'chmod',
  3046. 'chown',
  3047. 'close',
  3048. 'exists',
  3049. 'fchmod',
  3050. 'fchown',
  3051. 'fdatasync',
  3052. 'fstat',
  3053. 'fsync',
  3054. 'ftruncate',
  3055. 'futimes',
  3056. 'lchmod',
  3057. 'lchown',
  3058. 'lutimes',
  3059. 'link',
  3060. 'lstat',
  3061. 'mkdir',
  3062. 'mkdtemp',
  3063. 'open',
  3064. 'opendir',
  3065. 'read',
  3066. 'readdir',
  3067. 'readFile',
  3068. 'readlink',
  3069. 'realpath',
  3070. 'rename',
  3071. 'rmdir',
  3072. 'stat',
  3073. 'symlink',
  3074. 'truncate',
  3075. 'unlink',
  3076. 'utimes',
  3077. 'write',
  3078. 'writeFile',
  3079. 'writev',
  3080. ];
  3081. TO_PATCH_MACROTASK_METHODS.filter((name) => !!fs[name] && typeof fs[name] === 'function').forEach((name) => {
  3082. patchMacroTask(fs, name, (self, args) => {
  3083. return {
  3084. name: 'fs.' + name,
  3085. args: args,
  3086. cbIdx: args.length > 0 ? args.length - 1 : -1,
  3087. target: self,
  3088. };
  3089. });
  3090. });
  3091. const realpathOriginalDelegate = fs.realpath?.[api.symbol('OriginalDelegate')];
  3092. // This is the only specific method that should be additionally patched because the previous
  3093. // `patchMacroTask` has overridden the `realpath` function and its `native` property.
  3094. if (realpathOriginalDelegate?.native) {
  3095. fs.realpath.native = realpathOriginalDelegate.native;
  3096. patchMacroTask(fs.realpath, 'native', (self, args) => ({
  3097. args,
  3098. target: self,
  3099. cbIdx: args.length > 0 ? args.length - 1 : -1,
  3100. name: 'fs.realpath.native',
  3101. }));
  3102. }
  3103. });
  3104. }
  3105. function patchNodeUtil(Zone) {
  3106. Zone.__load_patch('node_util', (global, Zone, api) => {
  3107. api.patchOnProperties = patchOnProperties;
  3108. api.patchMethod = patchMethod;
  3109. api.bindArguments = bindArguments;
  3110. api.patchMacroTask = patchMacroTask;
  3111. setShouldCopySymbolProperties(true);
  3112. });
  3113. }
  3114. const set = 'set';
  3115. const clear = 'clear';
  3116. function patchNode(Zone) {
  3117. patchNodeUtil(Zone);
  3118. patchEvents(Zone);
  3119. patchFs(Zone);
  3120. Zone.__load_patch('node_timers', (global, Zone) => {
  3121. // Timers
  3122. let globalUseTimeoutFromTimer = false;
  3123. try {
  3124. const timers = require('timers');
  3125. let globalEqualTimersTimeout = global.setTimeout === timers.setTimeout;
  3126. if (!globalEqualTimersTimeout && !isMix) {
  3127. // 1. if isMix, then we are in mix environment such as Electron
  3128. // we should only patch timers.setTimeout because global.setTimeout
  3129. // have been patched
  3130. // 2. if global.setTimeout not equal timers.setTimeout, check
  3131. // whether global.setTimeout use timers.setTimeout or not
  3132. const originSetTimeout = timers.setTimeout;
  3133. timers.setTimeout = function () {
  3134. globalUseTimeoutFromTimer = true;
  3135. return originSetTimeout.apply(this, arguments);
  3136. };
  3137. const detectTimeout = global.setTimeout(() => { }, 100);
  3138. clearTimeout(detectTimeout);
  3139. timers.setTimeout = originSetTimeout;
  3140. }
  3141. patchTimer(timers, set, clear, 'Timeout');
  3142. patchTimer(timers, set, clear, 'Interval');
  3143. patchTimer(timers, set, clear, 'Immediate');
  3144. }
  3145. catch (error) {
  3146. // timers module not exists, for example, when we using nativeScript
  3147. // timers is not available
  3148. }
  3149. if (isMix) {
  3150. // if we are in mix environment, such as Electron,
  3151. // the global.setTimeout has already been patched,
  3152. // so we just patch timers.setTimeout
  3153. return;
  3154. }
  3155. if (!globalUseTimeoutFromTimer) {
  3156. // 1. global setTimeout equals timers setTimeout
  3157. // 2. or global don't use timers setTimeout(maybe some other library patch setTimeout)
  3158. // 3. or load timers module error happens, we should patch global setTimeout
  3159. patchTimer(global, set, clear, 'Timeout');
  3160. patchTimer(global, set, clear, 'Interval');
  3161. patchTimer(global, set, clear, 'Immediate');
  3162. }
  3163. else {
  3164. // global use timers setTimeout, but not equals
  3165. // this happens when use nodejs v0.10.x, global setTimeout will
  3166. // use a lazy load version of timers setTimeout
  3167. // we should not double patch timer's setTimeout
  3168. // so we only store the __symbol__ for consistency
  3169. global[Zone.__symbol__('setTimeout')] = global.setTimeout;
  3170. global[Zone.__symbol__('setInterval')] = global.setInterval;
  3171. global[Zone.__symbol__('setImmediate')] = global.setImmediate;
  3172. }
  3173. });
  3174. // patch process related methods
  3175. Zone.__load_patch('nextTick', () => {
  3176. // patch nextTick as microTask
  3177. patchMicroTask(process, 'nextTick', (self, args) => {
  3178. return {
  3179. name: 'process.nextTick',
  3180. args: args,
  3181. cbIdx: args.length > 0 && typeof args[0] === 'function' ? 0 : -1,
  3182. target: process,
  3183. };
  3184. });
  3185. });
  3186. Zone.__load_patch('handleUnhandledPromiseRejection', (global, Zone, api) => {
  3187. Zone[api.symbol('unhandledPromiseRejectionHandler')] =
  3188. findProcessPromiseRejectionHandler('unhandledRejection');
  3189. Zone[api.symbol('rejectionHandledHandler')] =
  3190. findProcessPromiseRejectionHandler('rejectionHandled');
  3191. // handle unhandled promise rejection
  3192. function findProcessPromiseRejectionHandler(evtName) {
  3193. return function (e) {
  3194. const eventTasks = findEventTasks(process, evtName);
  3195. eventTasks.forEach((eventTask) => {
  3196. // process has added unhandledrejection event listener
  3197. // trigger the event listener
  3198. if (evtName === 'unhandledRejection') {
  3199. eventTask.invoke(e.rejection, e.promise);
  3200. }
  3201. else if (evtName === 'rejectionHandled') {
  3202. eventTask.invoke(e.promise);
  3203. }
  3204. });
  3205. };
  3206. }
  3207. });
  3208. // Crypto
  3209. Zone.__load_patch('crypto', () => {
  3210. let crypto;
  3211. try {
  3212. crypto = require('crypto');
  3213. }
  3214. catch (err) { }
  3215. // use the generic patchMacroTask to patch crypto
  3216. if (crypto) {
  3217. const methodNames = ['randomBytes', 'pbkdf2'];
  3218. methodNames.forEach((name) => {
  3219. patchMacroTask(crypto, name, (self, args) => {
  3220. return {
  3221. name: 'crypto.' + name,
  3222. args: args,
  3223. cbIdx: args.length > 0 && typeof args[args.length - 1] === 'function' ? args.length - 1 : -1,
  3224. target: crypto,
  3225. };
  3226. });
  3227. });
  3228. }
  3229. });
  3230. Zone.__load_patch('console', (global, Zone) => {
  3231. const consoleMethods = [
  3232. 'dir',
  3233. 'log',
  3234. 'info',
  3235. 'error',
  3236. 'warn',
  3237. 'assert',
  3238. 'debug',
  3239. 'timeEnd',
  3240. 'trace',
  3241. ];
  3242. consoleMethods.forEach((m) => {
  3243. const originalMethod = (console[Zone.__symbol__(m)] = console[m]);
  3244. if (originalMethod) {
  3245. console[m] = function () {
  3246. const args = ArraySlice.call(arguments);
  3247. if (Zone.current === Zone.root) {
  3248. return originalMethod.apply(this, args);
  3249. }
  3250. else {
  3251. return Zone.root.run(originalMethod, this, args);
  3252. }
  3253. };
  3254. }
  3255. });
  3256. });
  3257. Zone.__load_patch('queueMicrotask', (global, Zone, api) => {
  3258. patchQueueMicrotask(global, api);
  3259. });
  3260. }
  3261. function loadZone() {
  3262. // if global['Zone'] already exists (maybe zone.js was already loaded or
  3263. // some other lib also registered a global object named Zone), we may need
  3264. // to throw an error, but sometimes user may not want this error.
  3265. // For example,
  3266. // we have two web pages, page1 includes zone.js, page2 doesn't.
  3267. // and the 1st time user load page1 and page2, everything work fine,
  3268. // but when user load page2 again, error occurs because global['Zone'] already exists.
  3269. // so we add a flag to let user choose whether to throw this error or not.
  3270. // By default, if existing Zone is from zone.js, we will not throw the error.
  3271. const global = globalThis;
  3272. const checkDuplicate = global[__symbol__('forceDuplicateZoneCheck')] === true;
  3273. if (global['Zone'] && (checkDuplicate || typeof global['Zone'].__symbol__ !== 'function')) {
  3274. throw new Error('Zone already loaded.');
  3275. }
  3276. // Initialize global `Zone` constant.
  3277. global['Zone'] ??= initZone();
  3278. return global['Zone'];
  3279. }
  3280. const Zone$1 = loadZone();
  3281. patchCommon(Zone$1);
  3282. patchBrowser(Zone$1);
  3283. patchNode(Zone$1);