zone-mix.js 144 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301
  1. 'use strict';
  2. /**
  3. * @license Angular v<unknown>
  4. * (c) 2010-2025 Google LLC. https://angular.io/
  5. * License: MIT
  6. */
  7. const global = globalThis;
  8. // __Zone_symbol_prefix global can be used to override the default zone
  9. // symbol prefix with a custom one if needed.
  10. function __symbol__(name) {
  11. const symbolPrefix = global['__Zone_symbol_prefix'] || '__zone_symbol__';
  12. return symbolPrefix + name;
  13. }
  14. function initZone() {
  15. const performance = global['performance'];
  16. function mark(name) {
  17. performance && performance['mark'] && performance['mark'](name);
  18. }
  19. function performanceMeasure(name, label) {
  20. performance && performance['measure'] && performance['measure'](name, label);
  21. }
  22. mark('Zone');
  23. class ZoneImpl {
  24. static __symbol__ = __symbol__;
  25. static assertZonePatched() {
  26. if (global['Promise'] !== patches['ZoneAwarePromise']) {
  27. throw new Error('Zone.js has detected that ZoneAwarePromise `(window|global).Promise` ' +
  28. 'has been overwritten.\n' +
  29. 'Most likely cause is that a Promise polyfill has been loaded ' +
  30. 'after Zone.js (Polyfilling Promise api is not necessary when zone.js is loaded. ' +
  31. 'If you must load one, do so before loading zone.js.)');
  32. }
  33. }
  34. static get root() {
  35. let zone = ZoneImpl.current;
  36. while (zone.parent) {
  37. zone = zone.parent;
  38. }
  39. return zone;
  40. }
  41. static get current() {
  42. return _currentZoneFrame.zone;
  43. }
  44. static get currentTask() {
  45. return _currentTask;
  46. }
  47. static __load_patch(name, fn, ignoreDuplicate = false) {
  48. if (patches.hasOwnProperty(name)) {
  49. // `checkDuplicate` option is defined from global variable
  50. // so it works for all modules.
  51. // `ignoreDuplicate` can work for the specified module
  52. const checkDuplicate = global[__symbol__('forceDuplicateZoneCheck')] === true;
  53. if (!ignoreDuplicate && checkDuplicate) {
  54. throw Error('Already loaded patch: ' + name);
  55. }
  56. }
  57. else if (!global['__Zone_disable_' + name]) {
  58. const perfName = 'Zone:' + name;
  59. mark(perfName);
  60. patches[name] = fn(global, ZoneImpl, _api);
  61. performanceMeasure(perfName, perfName);
  62. }
  63. }
  64. get parent() {
  65. return this._parent;
  66. }
  67. get name() {
  68. return this._name;
  69. }
  70. _parent;
  71. _name;
  72. _properties;
  73. _zoneDelegate;
  74. constructor(parent, zoneSpec) {
  75. this._parent = parent;
  76. this._name = zoneSpec ? zoneSpec.name || 'unnamed' : '<root>';
  77. this._properties = (zoneSpec && zoneSpec.properties) || {};
  78. this._zoneDelegate = new _ZoneDelegate(this, this._parent && this._parent._zoneDelegate, zoneSpec);
  79. }
  80. get(key) {
  81. const zone = this.getZoneWith(key);
  82. if (zone)
  83. return zone._properties[key];
  84. }
  85. getZoneWith(key) {
  86. let current = this;
  87. while (current) {
  88. if (current._properties.hasOwnProperty(key)) {
  89. return current;
  90. }
  91. current = current._parent;
  92. }
  93. return null;
  94. }
  95. fork(zoneSpec) {
  96. if (!zoneSpec)
  97. throw new Error('ZoneSpec required!');
  98. return this._zoneDelegate.fork(this, zoneSpec);
  99. }
  100. wrap(callback, source) {
  101. if (typeof callback !== 'function') {
  102. throw new Error('Expecting function got: ' + callback);
  103. }
  104. const _callback = this._zoneDelegate.intercept(this, callback, source);
  105. const zone = this;
  106. return function () {
  107. return zone.runGuarded(_callback, this, arguments, source);
  108. };
  109. }
  110. run(callback, applyThis, applyArgs, source) {
  111. _currentZoneFrame = { parent: _currentZoneFrame, zone: this };
  112. try {
  113. return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
  114. }
  115. finally {
  116. _currentZoneFrame = _currentZoneFrame.parent;
  117. }
  118. }
  119. runGuarded(callback, applyThis = null, applyArgs, source) {
  120. _currentZoneFrame = { parent: _currentZoneFrame, zone: this };
  121. try {
  122. try {
  123. return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
  124. }
  125. catch (error) {
  126. if (this._zoneDelegate.handleError(this, error)) {
  127. throw error;
  128. }
  129. }
  130. }
  131. finally {
  132. _currentZoneFrame = _currentZoneFrame.parent;
  133. }
  134. }
  135. runTask(task, applyThis, applyArgs) {
  136. if (task.zone != this) {
  137. throw new Error('A task can only be run in the zone of creation! (Creation: ' +
  138. (task.zone || NO_ZONE).name +
  139. '; Execution: ' +
  140. this.name +
  141. ')');
  142. }
  143. const zoneTask = task;
  144. // https://github.com/angular/zone.js/issues/778, sometimes eventTask
  145. // will run in notScheduled(canceled) state, we should not try to
  146. // run such kind of task but just return
  147. const { type, data: { isPeriodic = false, isRefreshable = false } = {} } = task;
  148. if (task.state === notScheduled && (type === eventTask || type === macroTask)) {
  149. return;
  150. }
  151. const reEntryGuard = task.state != running;
  152. reEntryGuard && zoneTask._transitionTo(running, scheduled);
  153. const previousTask = _currentTask;
  154. _currentTask = zoneTask;
  155. _currentZoneFrame = { parent: _currentZoneFrame, zone: this };
  156. try {
  157. if (type == macroTask && task.data && !isPeriodic && !isRefreshable) {
  158. task.cancelFn = undefined;
  159. }
  160. try {
  161. return this._zoneDelegate.invokeTask(this, zoneTask, applyThis, applyArgs);
  162. }
  163. catch (error) {
  164. if (this._zoneDelegate.handleError(this, error)) {
  165. throw error;
  166. }
  167. }
  168. }
  169. finally {
  170. // if the task's state is notScheduled or unknown, then it has already been cancelled
  171. // we should not reset the state to scheduled
  172. const state = task.state;
  173. if (state !== notScheduled && state !== unknown) {
  174. if (type == eventTask || isPeriodic || (isRefreshable && state === scheduling)) {
  175. reEntryGuard && zoneTask._transitionTo(scheduled, running, scheduling);
  176. }
  177. else {
  178. const zoneDelegates = zoneTask._zoneDelegates;
  179. this._updateTaskCount(zoneTask, -1);
  180. reEntryGuard && zoneTask._transitionTo(notScheduled, running, notScheduled);
  181. if (isRefreshable) {
  182. zoneTask._zoneDelegates = zoneDelegates;
  183. }
  184. }
  185. }
  186. _currentZoneFrame = _currentZoneFrame.parent;
  187. _currentTask = previousTask;
  188. }
  189. }
  190. scheduleTask(task) {
  191. if (task.zone && task.zone !== this) {
  192. // check if the task was rescheduled, the newZone
  193. // should not be the children of the original zone
  194. let newZone = this;
  195. while (newZone) {
  196. if (newZone === task.zone) {
  197. throw Error(`can not reschedule task to ${this.name} which is descendants of the original zone ${task.zone.name}`);
  198. }
  199. newZone = newZone.parent;
  200. }
  201. }
  202. task._transitionTo(scheduling, notScheduled);
  203. const zoneDelegates = [];
  204. task._zoneDelegates = zoneDelegates;
  205. task._zone = this;
  206. try {
  207. task = this._zoneDelegate.scheduleTask(this, task);
  208. }
  209. catch (err) {
  210. // should set task's state to unknown when scheduleTask throw error
  211. // because the err may from reschedule, so the fromState maybe notScheduled
  212. task._transitionTo(unknown, scheduling, notScheduled);
  213. // TODO: @JiaLiPassion, should we check the result from handleError?
  214. this._zoneDelegate.handleError(this, err);
  215. throw err;
  216. }
  217. if (task._zoneDelegates === zoneDelegates) {
  218. // we have to check because internally the delegate can reschedule the task.
  219. this._updateTaskCount(task, 1);
  220. }
  221. if (task.state == scheduling) {
  222. task._transitionTo(scheduled, scheduling);
  223. }
  224. return task;
  225. }
  226. scheduleMicroTask(source, callback, data, customSchedule) {
  227. return this.scheduleTask(new ZoneTask(microTask, source, callback, data, customSchedule, undefined));
  228. }
  229. scheduleMacroTask(source, callback, data, customSchedule, customCancel) {
  230. return this.scheduleTask(new ZoneTask(macroTask, source, callback, data, customSchedule, customCancel));
  231. }
  232. scheduleEventTask(source, callback, data, customSchedule, customCancel) {
  233. return this.scheduleTask(new ZoneTask(eventTask, source, callback, data, customSchedule, customCancel));
  234. }
  235. cancelTask(task) {
  236. if (task.zone != this)
  237. throw new Error('A task can only be cancelled in the zone of creation! (Creation: ' +
  238. (task.zone || NO_ZONE).name +
  239. '; Execution: ' +
  240. this.name +
  241. ')');
  242. if (task.state !== scheduled && task.state !== running) {
  243. return;
  244. }
  245. task._transitionTo(canceling, scheduled, running);
  246. try {
  247. this._zoneDelegate.cancelTask(this, task);
  248. }
  249. catch (err) {
  250. // if error occurs when cancelTask, transit the state to unknown
  251. task._transitionTo(unknown, canceling);
  252. this._zoneDelegate.handleError(this, err);
  253. throw err;
  254. }
  255. this._updateTaskCount(task, -1);
  256. task._transitionTo(notScheduled, canceling);
  257. task.runCount = -1;
  258. return task;
  259. }
  260. _updateTaskCount(task, count) {
  261. const zoneDelegates = task._zoneDelegates;
  262. if (count == -1) {
  263. task._zoneDelegates = null;
  264. }
  265. for (let i = 0; i < zoneDelegates.length; i++) {
  266. zoneDelegates[i]._updateTaskCount(task.type, count);
  267. }
  268. }
  269. }
  270. const DELEGATE_ZS = {
  271. name: '',
  272. onHasTask: (delegate, _, target, hasTaskState) => delegate.hasTask(target, hasTaskState),
  273. onScheduleTask: (delegate, _, target, task) => delegate.scheduleTask(target, task),
  274. onInvokeTask: (delegate, _, target, task, applyThis, applyArgs) => delegate.invokeTask(target, task, applyThis, applyArgs),
  275. onCancelTask: (delegate, _, target, task) => delegate.cancelTask(target, task),
  276. };
  277. class _ZoneDelegate {
  278. get zone() {
  279. return this._zone;
  280. }
  281. _zone;
  282. _taskCounts = {
  283. 'microTask': 0,
  284. 'macroTask': 0,
  285. 'eventTask': 0,
  286. };
  287. _parentDelegate;
  288. _forkDlgt;
  289. _forkZS;
  290. _forkCurrZone;
  291. _interceptDlgt;
  292. _interceptZS;
  293. _interceptCurrZone;
  294. _invokeDlgt;
  295. _invokeZS;
  296. _invokeCurrZone;
  297. _handleErrorDlgt;
  298. _handleErrorZS;
  299. _handleErrorCurrZone;
  300. _scheduleTaskDlgt;
  301. _scheduleTaskZS;
  302. _scheduleTaskCurrZone;
  303. _invokeTaskDlgt;
  304. _invokeTaskZS;
  305. _invokeTaskCurrZone;
  306. _cancelTaskDlgt;
  307. _cancelTaskZS;
  308. _cancelTaskCurrZone;
  309. _hasTaskDlgt;
  310. _hasTaskDlgtOwner;
  311. _hasTaskZS;
  312. _hasTaskCurrZone;
  313. constructor(zone, parentDelegate, zoneSpec) {
  314. this._zone = zone;
  315. this._parentDelegate = parentDelegate;
  316. this._forkZS = zoneSpec && (zoneSpec && zoneSpec.onFork ? zoneSpec : parentDelegate._forkZS);
  317. this._forkDlgt = zoneSpec && (zoneSpec.onFork ? parentDelegate : parentDelegate._forkDlgt);
  318. this._forkCurrZone =
  319. zoneSpec && (zoneSpec.onFork ? this._zone : parentDelegate._forkCurrZone);
  320. this._interceptZS =
  321. zoneSpec && (zoneSpec.onIntercept ? zoneSpec : parentDelegate._interceptZS);
  322. this._interceptDlgt =
  323. zoneSpec && (zoneSpec.onIntercept ? parentDelegate : parentDelegate._interceptDlgt);
  324. this._interceptCurrZone =
  325. zoneSpec && (zoneSpec.onIntercept ? this._zone : parentDelegate._interceptCurrZone);
  326. this._invokeZS = zoneSpec && (zoneSpec.onInvoke ? zoneSpec : parentDelegate._invokeZS);
  327. this._invokeDlgt =
  328. zoneSpec && (zoneSpec.onInvoke ? parentDelegate : parentDelegate._invokeDlgt);
  329. this._invokeCurrZone =
  330. zoneSpec && (zoneSpec.onInvoke ? this._zone : parentDelegate._invokeCurrZone);
  331. this._handleErrorZS =
  332. zoneSpec && (zoneSpec.onHandleError ? zoneSpec : parentDelegate._handleErrorZS);
  333. this._handleErrorDlgt =
  334. zoneSpec && (zoneSpec.onHandleError ? parentDelegate : parentDelegate._handleErrorDlgt);
  335. this._handleErrorCurrZone =
  336. zoneSpec && (zoneSpec.onHandleError ? this._zone : parentDelegate._handleErrorCurrZone);
  337. this._scheduleTaskZS =
  338. zoneSpec && (zoneSpec.onScheduleTask ? zoneSpec : parentDelegate._scheduleTaskZS);
  339. this._scheduleTaskDlgt =
  340. zoneSpec && (zoneSpec.onScheduleTask ? parentDelegate : parentDelegate._scheduleTaskDlgt);
  341. this._scheduleTaskCurrZone =
  342. zoneSpec && (zoneSpec.onScheduleTask ? this._zone : parentDelegate._scheduleTaskCurrZone);
  343. this._invokeTaskZS =
  344. zoneSpec && (zoneSpec.onInvokeTask ? zoneSpec : parentDelegate._invokeTaskZS);
  345. this._invokeTaskDlgt =
  346. zoneSpec && (zoneSpec.onInvokeTask ? parentDelegate : parentDelegate._invokeTaskDlgt);
  347. this._invokeTaskCurrZone =
  348. zoneSpec && (zoneSpec.onInvokeTask ? this._zone : parentDelegate._invokeTaskCurrZone);
  349. this._cancelTaskZS =
  350. zoneSpec && (zoneSpec.onCancelTask ? zoneSpec : parentDelegate._cancelTaskZS);
  351. this._cancelTaskDlgt =
  352. zoneSpec && (zoneSpec.onCancelTask ? parentDelegate : parentDelegate._cancelTaskDlgt);
  353. this._cancelTaskCurrZone =
  354. zoneSpec && (zoneSpec.onCancelTask ? this._zone : parentDelegate._cancelTaskCurrZone);
  355. this._hasTaskZS = null;
  356. this._hasTaskDlgt = null;
  357. this._hasTaskDlgtOwner = null;
  358. this._hasTaskCurrZone = null;
  359. const zoneSpecHasTask = zoneSpec && zoneSpec.onHasTask;
  360. const parentHasTask = parentDelegate && parentDelegate._hasTaskZS;
  361. if (zoneSpecHasTask || parentHasTask) {
  362. // If we need to report hasTask, than this ZS needs to do ref counting on tasks. In such
  363. // a case all task related interceptors must go through this ZD. We can't short circuit it.
  364. this._hasTaskZS = zoneSpecHasTask ? zoneSpec : DELEGATE_ZS;
  365. this._hasTaskDlgt = parentDelegate;
  366. this._hasTaskDlgtOwner = this;
  367. this._hasTaskCurrZone = this._zone;
  368. if (!zoneSpec.onScheduleTask) {
  369. this._scheduleTaskZS = DELEGATE_ZS;
  370. this._scheduleTaskDlgt = parentDelegate;
  371. this._scheduleTaskCurrZone = this._zone;
  372. }
  373. if (!zoneSpec.onInvokeTask) {
  374. this._invokeTaskZS = DELEGATE_ZS;
  375. this._invokeTaskDlgt = parentDelegate;
  376. this._invokeTaskCurrZone = this._zone;
  377. }
  378. if (!zoneSpec.onCancelTask) {
  379. this._cancelTaskZS = DELEGATE_ZS;
  380. this._cancelTaskDlgt = parentDelegate;
  381. this._cancelTaskCurrZone = this._zone;
  382. }
  383. }
  384. }
  385. fork(targetZone, zoneSpec) {
  386. return this._forkZS
  387. ? this._forkZS.onFork(this._forkDlgt, this.zone, targetZone, zoneSpec)
  388. : new ZoneImpl(targetZone, zoneSpec);
  389. }
  390. intercept(targetZone, callback, source) {
  391. return this._interceptZS
  392. ? this._interceptZS.onIntercept(this._interceptDlgt, this._interceptCurrZone, targetZone, callback, source)
  393. : callback;
  394. }
  395. invoke(targetZone, callback, applyThis, applyArgs, source) {
  396. return this._invokeZS
  397. ? this._invokeZS.onInvoke(this._invokeDlgt, this._invokeCurrZone, targetZone, callback, applyThis, applyArgs, source)
  398. : callback.apply(applyThis, applyArgs);
  399. }
  400. handleError(targetZone, error) {
  401. return this._handleErrorZS
  402. ? this._handleErrorZS.onHandleError(this._handleErrorDlgt, this._handleErrorCurrZone, targetZone, error)
  403. : true;
  404. }
  405. scheduleTask(targetZone, task) {
  406. let returnTask = task;
  407. if (this._scheduleTaskZS) {
  408. if (this._hasTaskZS) {
  409. returnTask._zoneDelegates.push(this._hasTaskDlgtOwner);
  410. }
  411. returnTask = this._scheduleTaskZS.onScheduleTask(this._scheduleTaskDlgt, this._scheduleTaskCurrZone, targetZone, task);
  412. if (!returnTask)
  413. returnTask = task;
  414. }
  415. else {
  416. if (task.scheduleFn) {
  417. task.scheduleFn(task);
  418. }
  419. else if (task.type == microTask) {
  420. scheduleMicroTask(task);
  421. }
  422. else {
  423. throw new Error('Task is missing scheduleFn.');
  424. }
  425. }
  426. return returnTask;
  427. }
  428. invokeTask(targetZone, task, applyThis, applyArgs) {
  429. return this._invokeTaskZS
  430. ? this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt, this._invokeTaskCurrZone, targetZone, task, applyThis, applyArgs)
  431. : task.callback.apply(applyThis, applyArgs);
  432. }
  433. cancelTask(targetZone, task) {
  434. let value;
  435. if (this._cancelTaskZS) {
  436. value = this._cancelTaskZS.onCancelTask(this._cancelTaskDlgt, this._cancelTaskCurrZone, targetZone, task);
  437. }
  438. else {
  439. if (!task.cancelFn) {
  440. throw Error('Task is not cancelable');
  441. }
  442. value = task.cancelFn(task);
  443. }
  444. return value;
  445. }
  446. hasTask(targetZone, isEmpty) {
  447. // hasTask should not throw error so other ZoneDelegate
  448. // can still trigger hasTask callback
  449. try {
  450. this._hasTaskZS &&
  451. this._hasTaskZS.onHasTask(this._hasTaskDlgt, this._hasTaskCurrZone, targetZone, isEmpty);
  452. }
  453. catch (err) {
  454. this.handleError(targetZone, err);
  455. }
  456. }
  457. _updateTaskCount(type, count) {
  458. const counts = this._taskCounts;
  459. const prev = counts[type];
  460. const next = (counts[type] = prev + count);
  461. if (next < 0) {
  462. throw new Error('More tasks executed then were scheduled.');
  463. }
  464. if (prev == 0 || next == 0) {
  465. const isEmpty = {
  466. microTask: counts['microTask'] > 0,
  467. macroTask: counts['macroTask'] > 0,
  468. eventTask: counts['eventTask'] > 0,
  469. change: type,
  470. };
  471. this.hasTask(this._zone, isEmpty);
  472. }
  473. }
  474. }
  475. class ZoneTask {
  476. type;
  477. source;
  478. invoke;
  479. callback;
  480. data;
  481. scheduleFn;
  482. cancelFn;
  483. _zone = null;
  484. runCount = 0;
  485. _zoneDelegates = null;
  486. _state = 'notScheduled';
  487. constructor(type, source, callback, options, scheduleFn, cancelFn) {
  488. this.type = type;
  489. this.source = source;
  490. this.data = options;
  491. this.scheduleFn = scheduleFn;
  492. this.cancelFn = cancelFn;
  493. if (!callback) {
  494. throw new Error('callback is not defined');
  495. }
  496. this.callback = callback;
  497. const self = this;
  498. // TODO: @JiaLiPassion options should have interface
  499. if (type === eventTask && options && options.useG) {
  500. this.invoke = ZoneTask.invokeTask;
  501. }
  502. else {
  503. this.invoke = function () {
  504. return ZoneTask.invokeTask.call(global, self, this, arguments);
  505. };
  506. }
  507. }
  508. static invokeTask(task, target, args) {
  509. if (!task) {
  510. task = this;
  511. }
  512. _numberOfNestedTaskFrames++;
  513. try {
  514. task.runCount++;
  515. return task.zone.runTask(task, target, args);
  516. }
  517. finally {
  518. if (_numberOfNestedTaskFrames == 1) {
  519. drainMicroTaskQueue();
  520. }
  521. _numberOfNestedTaskFrames--;
  522. }
  523. }
  524. get zone() {
  525. return this._zone;
  526. }
  527. get state() {
  528. return this._state;
  529. }
  530. cancelScheduleRequest() {
  531. this._transitionTo(notScheduled, scheduling);
  532. }
  533. _transitionTo(toState, fromState1, fromState2) {
  534. if (this._state === fromState1 || this._state === fromState2) {
  535. this._state = toState;
  536. if (toState == notScheduled) {
  537. this._zoneDelegates = null;
  538. }
  539. }
  540. else {
  541. throw new Error(`${this.type} '${this.source}': can not transition to '${toState}', expecting state '${fromState1}'${fromState2 ? " or '" + fromState2 + "'" : ''}, was '${this._state}'.`);
  542. }
  543. }
  544. toString() {
  545. if (this.data && typeof this.data.handleId !== 'undefined') {
  546. return this.data.handleId.toString();
  547. }
  548. else {
  549. return Object.prototype.toString.call(this);
  550. }
  551. }
  552. // add toJSON method to prevent cyclic error when
  553. // call JSON.stringify(zoneTask)
  554. toJSON() {
  555. return {
  556. type: this.type,
  557. state: this.state,
  558. source: this.source,
  559. zone: this.zone.name,
  560. runCount: this.runCount,
  561. };
  562. }
  563. }
  564. //////////////////////////////////////////////////////
  565. //////////////////////////////////////////////////////
  566. /// MICROTASK QUEUE
  567. //////////////////////////////////////////////////////
  568. //////////////////////////////////////////////////////
  569. const symbolSetTimeout = __symbol__('setTimeout');
  570. const symbolPromise = __symbol__('Promise');
  571. const symbolThen = __symbol__('then');
  572. let _microTaskQueue = [];
  573. let _isDrainingMicrotaskQueue = false;
  574. let nativeMicroTaskQueuePromise;
  575. function nativeScheduleMicroTask(func) {
  576. if (!nativeMicroTaskQueuePromise) {
  577. if (global[symbolPromise]) {
  578. nativeMicroTaskQueuePromise = global[symbolPromise].resolve(0);
  579. }
  580. }
  581. if (nativeMicroTaskQueuePromise) {
  582. let nativeThen = nativeMicroTaskQueuePromise[symbolThen];
  583. if (!nativeThen) {
  584. // native Promise is not patchable, we need to use `then` directly
  585. // issue 1078
  586. nativeThen = nativeMicroTaskQueuePromise['then'];
  587. }
  588. nativeThen.call(nativeMicroTaskQueuePromise, func);
  589. }
  590. else {
  591. global[symbolSetTimeout](func, 0);
  592. }
  593. }
  594. function scheduleMicroTask(task) {
  595. // if we are not running in any task, and there has not been anything scheduled
  596. // we must bootstrap the initial task creation by manually scheduling the drain
  597. if (_numberOfNestedTaskFrames === 0 && _microTaskQueue.length === 0) {
  598. // We are not running in Task, so we need to kickstart the microtask queue.
  599. nativeScheduleMicroTask(drainMicroTaskQueue);
  600. }
  601. task && _microTaskQueue.push(task);
  602. }
  603. function drainMicroTaskQueue() {
  604. if (!_isDrainingMicrotaskQueue) {
  605. _isDrainingMicrotaskQueue = true;
  606. while (_microTaskQueue.length) {
  607. const queue = _microTaskQueue;
  608. _microTaskQueue = [];
  609. for (let i = 0; i < queue.length; i++) {
  610. const task = queue[i];
  611. try {
  612. task.zone.runTask(task, null, null);
  613. }
  614. catch (error) {
  615. _api.onUnhandledError(error);
  616. }
  617. }
  618. }
  619. _api.microtaskDrainDone();
  620. _isDrainingMicrotaskQueue = false;
  621. }
  622. }
  623. //////////////////////////////////////////////////////
  624. //////////////////////////////////////////////////////
  625. /// BOOTSTRAP
  626. //////////////////////////////////////////////////////
  627. //////////////////////////////////////////////////////
  628. const NO_ZONE = { name: 'NO ZONE' };
  629. const notScheduled = 'notScheduled', scheduling = 'scheduling', scheduled = 'scheduled', running = 'running', canceling = 'canceling', unknown = 'unknown';
  630. const microTask = 'microTask', macroTask = 'macroTask', eventTask = 'eventTask';
  631. const patches = {};
  632. const _api = {
  633. symbol: __symbol__,
  634. currentZoneFrame: () => _currentZoneFrame,
  635. onUnhandledError: noop,
  636. microtaskDrainDone: noop,
  637. scheduleMicroTask: scheduleMicroTask,
  638. showUncaughtError: () => !ZoneImpl[__symbol__('ignoreConsoleErrorUncaughtError')],
  639. patchEventTarget: () => [],
  640. patchOnProperties: noop,
  641. patchMethod: () => noop,
  642. bindArguments: () => [],
  643. patchThen: () => noop,
  644. patchMacroTask: () => noop,
  645. patchEventPrototype: () => noop,
  646. isIEOrEdge: () => false,
  647. getGlobalObjects: () => undefined,
  648. ObjectDefineProperty: () => noop,
  649. ObjectGetOwnPropertyDescriptor: () => undefined,
  650. ObjectCreate: () => undefined,
  651. ArraySlice: () => [],
  652. patchClass: () => noop,
  653. wrapWithCurrentZone: () => noop,
  654. filterProperties: () => [],
  655. attachOriginToPatched: () => noop,
  656. _redefineProperty: () => noop,
  657. patchCallbacks: () => noop,
  658. nativeScheduleMicroTask: nativeScheduleMicroTask,
  659. };
  660. let _currentZoneFrame = { parent: null, zone: new ZoneImpl(null, null) };
  661. let _currentTask = null;
  662. let _numberOfNestedTaskFrames = 0;
  663. function noop() { }
  664. performanceMeasure('Zone', 'Zone');
  665. return ZoneImpl;
  666. }
  667. /**
  668. * Suppress closure compiler errors about unknown 'Zone' variable
  669. * @fileoverview
  670. * @suppress {undefinedVars,globalThis,missingRequire}
  671. */
  672. /// <reference types="node"/>
  673. // issue #989, to reduce bundle size, use short name
  674. /** Object.getOwnPropertyDescriptor */
  675. const ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  676. /** Object.defineProperty */
  677. const ObjectDefineProperty = Object.defineProperty;
  678. /** Object.getPrototypeOf */
  679. const ObjectGetPrototypeOf = Object.getPrototypeOf;
  680. /** Object.create */
  681. const ObjectCreate = Object.create;
  682. /** Array.prototype.slice */
  683. const ArraySlice = Array.prototype.slice;
  684. /** addEventListener string const */
  685. const ADD_EVENT_LISTENER_STR = 'addEventListener';
  686. /** removeEventListener string const */
  687. const REMOVE_EVENT_LISTENER_STR = 'removeEventListener';
  688. /** zoneSymbol addEventListener */
  689. const ZONE_SYMBOL_ADD_EVENT_LISTENER = __symbol__(ADD_EVENT_LISTENER_STR);
  690. /** zoneSymbol removeEventListener */
  691. const ZONE_SYMBOL_REMOVE_EVENT_LISTENER = __symbol__(REMOVE_EVENT_LISTENER_STR);
  692. /** true string const */
  693. const TRUE_STR = 'true';
  694. /** false string const */
  695. const FALSE_STR = 'false';
  696. /** Zone symbol prefix string const. */
  697. const ZONE_SYMBOL_PREFIX = __symbol__('');
  698. function wrapWithCurrentZone(callback, source) {
  699. return Zone.current.wrap(callback, source);
  700. }
  701. function scheduleMacroTaskWithCurrentZone(source, callback, data, customSchedule, customCancel) {
  702. return Zone.current.scheduleMacroTask(source, callback, data, customSchedule, customCancel);
  703. }
  704. const zoneSymbol = __symbol__;
  705. const isWindowExists = typeof window !== 'undefined';
  706. const internalWindow = isWindowExists ? window : undefined;
  707. const _global = (isWindowExists && internalWindow) || globalThis;
  708. const REMOVE_ATTRIBUTE = 'removeAttribute';
  709. function bindArguments(args, source) {
  710. for (let i = args.length - 1; i >= 0; i--) {
  711. if (typeof args[i] === 'function') {
  712. args[i] = wrapWithCurrentZone(args[i], source + '_' + i);
  713. }
  714. }
  715. return args;
  716. }
  717. function patchPrototype(prototype, fnNames) {
  718. const source = prototype.constructor['name'];
  719. for (let i = 0; i < fnNames.length; i++) {
  720. const name = fnNames[i];
  721. const delegate = prototype[name];
  722. if (delegate) {
  723. const prototypeDesc = ObjectGetOwnPropertyDescriptor(prototype, name);
  724. if (!isPropertyWritable(prototypeDesc)) {
  725. continue;
  726. }
  727. prototype[name] = ((delegate) => {
  728. const patched = function () {
  729. return delegate.apply(this, bindArguments(arguments, source + '.' + name));
  730. };
  731. attachOriginToPatched(patched, delegate);
  732. return patched;
  733. })(delegate);
  734. }
  735. }
  736. }
  737. function isPropertyWritable(propertyDesc) {
  738. if (!propertyDesc) {
  739. return true;
  740. }
  741. if (propertyDesc.writable === false) {
  742. return false;
  743. }
  744. return !(typeof propertyDesc.get === 'function' && typeof propertyDesc.set === 'undefined');
  745. }
  746. const isWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
  747. // Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
  748. // this code.
  749. const isNode = !('nw' in _global) &&
  750. typeof _global.process !== 'undefined' &&
  751. _global.process.toString() === '[object process]';
  752. const isBrowser = !isNode && !isWebWorker && !!(isWindowExists && internalWindow['HTMLElement']);
  753. // we are in electron of nw, so we are both browser and nodejs
  754. // Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
  755. // this code.
  756. const isMix = typeof _global.process !== 'undefined' &&
  757. _global.process.toString() === '[object process]' &&
  758. !isWebWorker &&
  759. !!(isWindowExists && internalWindow['HTMLElement']);
  760. const zoneSymbolEventNames$1 = {};
  761. const enableBeforeunloadSymbol = zoneSymbol('enable_beforeunload');
  762. const wrapFn = function (event) {
  763. // https://github.com/angular/zone.js/issues/911, in IE, sometimes
  764. // event will be undefined, so we need to use window.event
  765. event = event || _global.event;
  766. if (!event) {
  767. return;
  768. }
  769. let eventNameSymbol = zoneSymbolEventNames$1[event.type];
  770. if (!eventNameSymbol) {
  771. eventNameSymbol = zoneSymbolEventNames$1[event.type] = zoneSymbol('ON_PROPERTY' + event.type);
  772. }
  773. const target = this || event.target || _global;
  774. const listener = target[eventNameSymbol];
  775. let result;
  776. if (isBrowser && target === internalWindow && event.type === 'error') {
  777. // window.onerror have different signature
  778. // https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror#window.onerror
  779. // and onerror callback will prevent default when callback return true
  780. const errorEvent = event;
  781. result =
  782. listener &&
  783. listener.call(this, errorEvent.message, errorEvent.filename, errorEvent.lineno, errorEvent.colno, errorEvent.error);
  784. if (result === true) {
  785. event.preventDefault();
  786. }
  787. }
  788. else {
  789. result = listener && listener.apply(this, arguments);
  790. if (
  791. // https://github.com/angular/angular/issues/47579
  792. // https://www.w3.org/TR/2011/WD-html5-20110525/history.html#beforeunloadevent
  793. // This is the only specific case we should check for. The spec defines that the
  794. // `returnValue` attribute represents the message to show the user. When the event
  795. // is created, this attribute must be set to the empty string.
  796. event.type === 'beforeunload' &&
  797. // To prevent any breaking changes resulting from this change, given that
  798. // it was already causing a significant number of failures in G3, we have hidden
  799. // that behavior behind a global configuration flag. Consumers can enable this
  800. // flag explicitly if they want the `beforeunload` event to be handled as defined
  801. // in the specification.
  802. _global[enableBeforeunloadSymbol] &&
  803. // The IDL event definition is `attribute DOMString returnValue`, so we check whether
  804. // `typeof result` is a string.
  805. typeof result === 'string') {
  806. event.returnValue = result;
  807. }
  808. else if (result != undefined && !result) {
  809. event.preventDefault();
  810. }
  811. }
  812. return result;
  813. };
  814. function patchProperty(obj, prop, prototype) {
  815. let desc = ObjectGetOwnPropertyDescriptor(obj, prop);
  816. if (!desc && prototype) {
  817. // when patch window object, use prototype to check prop exist or not
  818. const prototypeDesc = ObjectGetOwnPropertyDescriptor(prototype, prop);
  819. if (prototypeDesc) {
  820. desc = { enumerable: true, configurable: true };
  821. }
  822. }
  823. // if the descriptor not exists or is not configurable
  824. // just return
  825. if (!desc || !desc.configurable) {
  826. return;
  827. }
  828. const onPropPatchedSymbol = zoneSymbol('on' + prop + 'patched');
  829. if (obj.hasOwnProperty(onPropPatchedSymbol) && obj[onPropPatchedSymbol]) {
  830. return;
  831. }
  832. // A property descriptor cannot have getter/setter and be writable
  833. // deleting the writable and value properties avoids this error:
  834. //
  835. // TypeError: property descriptors must not specify a value or be writable when a
  836. // getter or setter has been specified
  837. delete desc.writable;
  838. delete desc.value;
  839. const originalDescGet = desc.get;
  840. const originalDescSet = desc.set;
  841. // slice(2) cuz 'onclick' -> 'click', etc
  842. const eventName = prop.slice(2);
  843. let eventNameSymbol = zoneSymbolEventNames$1[eventName];
  844. if (!eventNameSymbol) {
  845. eventNameSymbol = zoneSymbolEventNames$1[eventName] = zoneSymbol('ON_PROPERTY' + eventName);
  846. }
  847. desc.set = function (newValue) {
  848. // In some versions of Windows, the `this` context may be undefined
  849. // in on-property callbacks.
  850. // To handle this edge case, we check if `this` is falsy and
  851. // fallback to `_global` if needed.
  852. let target = this;
  853. if (!target && obj === _global) {
  854. target = _global;
  855. }
  856. if (!target) {
  857. return;
  858. }
  859. const previousValue = target[eventNameSymbol];
  860. if (typeof previousValue === 'function') {
  861. target.removeEventListener(eventName, wrapFn);
  862. }
  863. // https://github.com/angular/zone.js/issues/978
  864. // If an inline handler (like `onload`) was defined before zone.js was loaded,
  865. // call the original descriptor's setter to clean it up.
  866. originalDescSet?.call(target, null);
  867. target[eventNameSymbol] = newValue;
  868. if (typeof newValue === 'function') {
  869. target.addEventListener(eventName, wrapFn, false);
  870. }
  871. };
  872. // The getter would return undefined for unassigned properties but the default value of an
  873. // unassigned property is null
  874. desc.get = function () {
  875. // in some of windows's onproperty callback, this is undefined
  876. // so we need to check it
  877. let target = this;
  878. if (!target && obj === _global) {
  879. target = _global;
  880. }
  881. if (!target) {
  882. return null;
  883. }
  884. const listener = target[eventNameSymbol];
  885. if (listener) {
  886. return listener;
  887. }
  888. else if (originalDescGet) {
  889. // result will be null when use inline event attribute,
  890. // such as <button onclick="func();">OK</button>
  891. // because the onclick function is internal raw uncompiled handler
  892. // the onclick will be evaluated when first time event was triggered or
  893. // the property is accessed, https://github.com/angular/zone.js/issues/525
  894. // so we should use original native get to retrieve the handler
  895. let value = originalDescGet.call(this);
  896. if (value) {
  897. desc.set.call(this, value);
  898. if (typeof target[REMOVE_ATTRIBUTE] === 'function') {
  899. target.removeAttribute(prop);
  900. }
  901. return value;
  902. }
  903. }
  904. return null;
  905. };
  906. ObjectDefineProperty(obj, prop, desc);
  907. obj[onPropPatchedSymbol] = true;
  908. }
  909. function patchOnProperties(obj, properties, prototype) {
  910. if (properties) {
  911. for (let i = 0; i < properties.length; i++) {
  912. patchProperty(obj, 'on' + properties[i], prototype);
  913. }
  914. }
  915. else {
  916. const onProperties = [];
  917. for (const prop in obj) {
  918. if (prop.slice(0, 2) == 'on') {
  919. onProperties.push(prop);
  920. }
  921. }
  922. for (let j = 0; j < onProperties.length; j++) {
  923. patchProperty(obj, onProperties[j], prototype);
  924. }
  925. }
  926. }
  927. const originalInstanceKey = zoneSymbol('originalInstance');
  928. // wrap some native API on `window`
  929. function patchClass(className) {
  930. const OriginalClass = _global[className];
  931. if (!OriginalClass)
  932. return;
  933. // keep original class in global
  934. _global[zoneSymbol(className)] = OriginalClass;
  935. _global[className] = function () {
  936. const a = bindArguments(arguments, className);
  937. switch (a.length) {
  938. case 0:
  939. this[originalInstanceKey] = new OriginalClass();
  940. break;
  941. case 1:
  942. this[originalInstanceKey] = new OriginalClass(a[0]);
  943. break;
  944. case 2:
  945. this[originalInstanceKey] = new OriginalClass(a[0], a[1]);
  946. break;
  947. case 3:
  948. this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2]);
  949. break;
  950. case 4:
  951. this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2], a[3]);
  952. break;
  953. default:
  954. throw new Error('Arg list too long.');
  955. }
  956. };
  957. // attach original delegate to patched function
  958. attachOriginToPatched(_global[className], OriginalClass);
  959. const instance = new OriginalClass(function () { });
  960. let prop;
  961. for (prop in instance) {
  962. // https://bugs.webkit.org/show_bug.cgi?id=44721
  963. if (className === 'XMLHttpRequest' && prop === 'responseBlob')
  964. continue;
  965. (function (prop) {
  966. if (typeof instance[prop] === 'function') {
  967. _global[className].prototype[prop] = function () {
  968. return this[originalInstanceKey][prop].apply(this[originalInstanceKey], arguments);
  969. };
  970. }
  971. else {
  972. ObjectDefineProperty(_global[className].prototype, prop, {
  973. set: function (fn) {
  974. if (typeof fn === 'function') {
  975. this[originalInstanceKey][prop] = wrapWithCurrentZone(fn, className + '.' + prop);
  976. // keep callback in wrapped function so we can
  977. // use it in Function.prototype.toString to return
  978. // the native one.
  979. attachOriginToPatched(this[originalInstanceKey][prop], fn);
  980. }
  981. else {
  982. this[originalInstanceKey][prop] = fn;
  983. }
  984. },
  985. get: function () {
  986. return this[originalInstanceKey][prop];
  987. },
  988. });
  989. }
  990. })(prop);
  991. }
  992. for (prop in OriginalClass) {
  993. if (prop !== 'prototype' && OriginalClass.hasOwnProperty(prop)) {
  994. _global[className][prop] = OriginalClass[prop];
  995. }
  996. }
  997. }
  998. function copySymbolProperties(src, dest) {
  999. if (typeof Object.getOwnPropertySymbols !== 'function') {
  1000. return;
  1001. }
  1002. const symbols = Object.getOwnPropertySymbols(src);
  1003. symbols.forEach((symbol) => {
  1004. const desc = Object.getOwnPropertyDescriptor(src, symbol);
  1005. Object.defineProperty(dest, symbol, {
  1006. get: function () {
  1007. return src[symbol];
  1008. },
  1009. set: function (value) {
  1010. if (desc && (!desc.writable || typeof desc.set !== 'function')) {
  1011. // if src[symbol] is not writable or not have a setter, just return
  1012. return;
  1013. }
  1014. src[symbol] = value;
  1015. },
  1016. enumerable: desc ? desc.enumerable : true,
  1017. configurable: desc ? desc.configurable : true,
  1018. });
  1019. });
  1020. }
  1021. let shouldCopySymbolProperties = false;
  1022. function setShouldCopySymbolProperties(flag) {
  1023. shouldCopySymbolProperties = flag;
  1024. }
  1025. function patchMethod(target, name, patchFn) {
  1026. let proto = target;
  1027. while (proto && !proto.hasOwnProperty(name)) {
  1028. proto = ObjectGetPrototypeOf(proto);
  1029. }
  1030. if (!proto && target[name]) {
  1031. // somehow we did not find it, but we can see it. This happens on IE for Window properties.
  1032. proto = target;
  1033. }
  1034. const delegateName = zoneSymbol(name);
  1035. let delegate = null;
  1036. if (proto && (!(delegate = proto[delegateName]) || !proto.hasOwnProperty(delegateName))) {
  1037. delegate = proto[delegateName] = proto[name];
  1038. // check whether proto[name] is writable
  1039. // some property is readonly in safari, such as HtmlCanvasElement.prototype.toBlob
  1040. const desc = proto && ObjectGetOwnPropertyDescriptor(proto, name);
  1041. if (isPropertyWritable(desc)) {
  1042. const patchDelegate = patchFn(delegate, delegateName, name);
  1043. proto[name] = function () {
  1044. return patchDelegate(this, arguments);
  1045. };
  1046. attachOriginToPatched(proto[name], delegate);
  1047. if (shouldCopySymbolProperties) {
  1048. copySymbolProperties(delegate, proto[name]);
  1049. }
  1050. }
  1051. }
  1052. return delegate;
  1053. }
  1054. // TODO: @JiaLiPassion, support cancel task later if necessary
  1055. function patchMacroTask(obj, funcName, metaCreator) {
  1056. let setNative = null;
  1057. function scheduleTask(task) {
  1058. const data = task.data;
  1059. data.args[data.cbIdx] = function () {
  1060. task.invoke.apply(this, arguments);
  1061. };
  1062. setNative.apply(data.target, data.args);
  1063. return task;
  1064. }
  1065. setNative = patchMethod(obj, funcName, (delegate) => function (self, args) {
  1066. const meta = metaCreator(self, args);
  1067. if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
  1068. return scheduleMacroTaskWithCurrentZone(meta.name, args[meta.cbIdx], meta, scheduleTask);
  1069. }
  1070. else {
  1071. // cause an error by calling it directly.
  1072. return delegate.apply(self, args);
  1073. }
  1074. });
  1075. }
  1076. function patchMicroTask(obj, funcName, metaCreator) {
  1077. let setNative = null;
  1078. function scheduleTask(task) {
  1079. const data = task.data;
  1080. data.args[data.cbIdx] = function () {
  1081. task.invoke.apply(this, arguments);
  1082. };
  1083. setNative.apply(data.target, data.args);
  1084. return task;
  1085. }
  1086. setNative = patchMethod(obj, funcName, (delegate) => function (self, args) {
  1087. const meta = metaCreator(self, args);
  1088. if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
  1089. return Zone.current.scheduleMicroTask(meta.name, args[meta.cbIdx], meta, scheduleTask);
  1090. }
  1091. else {
  1092. // cause an error by calling it directly.
  1093. return delegate.apply(self, args);
  1094. }
  1095. });
  1096. }
  1097. function attachOriginToPatched(patched, original) {
  1098. patched[zoneSymbol('OriginalDelegate')] = original;
  1099. }
  1100. let isDetectedIEOrEdge = false;
  1101. let ieOrEdge = false;
  1102. function isIEOrEdge() {
  1103. if (isDetectedIEOrEdge) {
  1104. return ieOrEdge;
  1105. }
  1106. isDetectedIEOrEdge = true;
  1107. try {
  1108. const ua = internalWindow.navigator.userAgent;
  1109. if (ua.indexOf('MSIE ') !== -1 || ua.indexOf('Trident/') !== -1 || ua.indexOf('Edge/') !== -1) {
  1110. ieOrEdge = true;
  1111. }
  1112. }
  1113. catch (error) { }
  1114. return ieOrEdge;
  1115. }
  1116. function isFunction(value) {
  1117. return typeof value === 'function';
  1118. }
  1119. function isNumber(value) {
  1120. return typeof value === 'number';
  1121. }
  1122. /**
  1123. * @fileoverview
  1124. * @suppress {missingRequire}
  1125. */
  1126. // an identifier to tell ZoneTask do not create a new invoke closure
  1127. const OPTIMIZED_ZONE_EVENT_TASK_DATA = {
  1128. useG: true,
  1129. };
  1130. const zoneSymbolEventNames = {};
  1131. const globalSources = {};
  1132. const EVENT_NAME_SYMBOL_REGX = new RegExp('^' + ZONE_SYMBOL_PREFIX + '(\\w+)(true|false)$');
  1133. const IMMEDIATE_PROPAGATION_SYMBOL = zoneSymbol('propagationStopped');
  1134. function prepareEventNames(eventName, eventNameToString) {
  1135. const falseEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + FALSE_STR;
  1136. const trueEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + TRUE_STR;
  1137. const symbol = ZONE_SYMBOL_PREFIX + falseEventName;
  1138. const symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
  1139. zoneSymbolEventNames[eventName] = {};
  1140. zoneSymbolEventNames[eventName][FALSE_STR] = symbol;
  1141. zoneSymbolEventNames[eventName][TRUE_STR] = symbolCapture;
  1142. }
  1143. function patchEventTarget(_global, api, apis, patchOptions) {
  1144. const ADD_EVENT_LISTENER = (patchOptions && patchOptions.add) || ADD_EVENT_LISTENER_STR;
  1145. const REMOVE_EVENT_LISTENER = (patchOptions && patchOptions.rm) || REMOVE_EVENT_LISTENER_STR;
  1146. const LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.listeners) || 'eventListeners';
  1147. const REMOVE_ALL_LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.rmAll) || 'removeAllListeners';
  1148. const zoneSymbolAddEventListener = zoneSymbol(ADD_EVENT_LISTENER);
  1149. const ADD_EVENT_LISTENER_SOURCE = '.' + ADD_EVENT_LISTENER + ':';
  1150. const PREPEND_EVENT_LISTENER = 'prependListener';
  1151. const PREPEND_EVENT_LISTENER_SOURCE = '.' + PREPEND_EVENT_LISTENER + ':';
  1152. const invokeTask = function (task, target, event) {
  1153. // for better performance, check isRemoved which is set
  1154. // by removeEventListener
  1155. if (task.isRemoved) {
  1156. return;
  1157. }
  1158. const delegate = task.callback;
  1159. if (typeof delegate === 'object' && delegate.handleEvent) {
  1160. // create the bind version of handleEvent when invoke
  1161. task.callback = (event) => delegate.handleEvent(event);
  1162. task.originalDelegate = delegate;
  1163. }
  1164. // invoke static task.invoke
  1165. // need to try/catch error here, otherwise, the error in one event listener
  1166. // will break the executions of the other event listeners. Also error will
  1167. // not remove the event listener when `once` options is true.
  1168. let error;
  1169. try {
  1170. task.invoke(task, target, [event]);
  1171. }
  1172. catch (err) {
  1173. error = err;
  1174. }
  1175. const options = task.options;
  1176. if (options && typeof options === 'object' && options.once) {
  1177. // if options.once is true, after invoke once remove listener here
  1178. // only browser need to do this, nodejs eventEmitter will cal removeListener
  1179. // inside EventEmitter.once
  1180. const delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  1181. target[REMOVE_EVENT_LISTENER].call(target, event.type, delegate, options);
  1182. }
  1183. return error;
  1184. };
  1185. function globalCallback(context, event, isCapture) {
  1186. // https://github.com/angular/zone.js/issues/911, in IE, sometimes
  1187. // event will be undefined, so we need to use window.event
  1188. event = event || _global.event;
  1189. if (!event) {
  1190. return;
  1191. }
  1192. // event.target is needed for Samsung TV and SourceBuffer
  1193. // || global is needed https://github.com/angular/zone.js/issues/190
  1194. const target = context || event.target || _global;
  1195. const tasks = target[zoneSymbolEventNames[event.type][isCapture ? TRUE_STR : FALSE_STR]];
  1196. if (tasks) {
  1197. const errors = [];
  1198. // invoke all tasks which attached to current target with given event.type and capture = false
  1199. // for performance concern, if task.length === 1, just invoke
  1200. if (tasks.length === 1) {
  1201. const err = invokeTask(tasks[0], target, event);
  1202. err && errors.push(err);
  1203. }
  1204. else {
  1205. // https://github.com/angular/zone.js/issues/836
  1206. // copy the tasks array before invoke, to avoid
  1207. // the callback will remove itself or other listener
  1208. const copyTasks = tasks.slice();
  1209. for (let i = 0; i < copyTasks.length; i++) {
  1210. if (event && event[IMMEDIATE_PROPAGATION_SYMBOL] === true) {
  1211. break;
  1212. }
  1213. const err = invokeTask(copyTasks[i], target, event);
  1214. err && errors.push(err);
  1215. }
  1216. }
  1217. // Since there is only one error, we don't need to schedule microTask
  1218. // to throw the error.
  1219. if (errors.length === 1) {
  1220. throw errors[0];
  1221. }
  1222. else {
  1223. for (let i = 0; i < errors.length; i++) {
  1224. const err = errors[i];
  1225. api.nativeScheduleMicroTask(() => {
  1226. throw err;
  1227. });
  1228. }
  1229. }
  1230. }
  1231. }
  1232. // global shared zoneAwareCallback to handle all event callback with capture = false
  1233. const globalZoneAwareCallback = function (event) {
  1234. return globalCallback(this, event, false);
  1235. };
  1236. // global shared zoneAwareCallback to handle all event callback with capture = true
  1237. const globalZoneAwareCaptureCallback = function (event) {
  1238. return globalCallback(this, event, true);
  1239. };
  1240. function patchEventTargetMethods(obj, patchOptions) {
  1241. if (!obj) {
  1242. return false;
  1243. }
  1244. let useGlobalCallback = true;
  1245. if (patchOptions && patchOptions.useG !== undefined) {
  1246. useGlobalCallback = patchOptions.useG;
  1247. }
  1248. const validateHandler = patchOptions && patchOptions.vh;
  1249. let checkDuplicate = true;
  1250. if (patchOptions && patchOptions.chkDup !== undefined) {
  1251. checkDuplicate = patchOptions.chkDup;
  1252. }
  1253. let returnTarget = false;
  1254. if (patchOptions && patchOptions.rt !== undefined) {
  1255. returnTarget = patchOptions.rt;
  1256. }
  1257. let proto = obj;
  1258. while (proto && !proto.hasOwnProperty(ADD_EVENT_LISTENER)) {
  1259. proto = ObjectGetPrototypeOf(proto);
  1260. }
  1261. if (!proto && obj[ADD_EVENT_LISTENER]) {
  1262. // somehow we did not find it, but we can see it. This happens on IE for Window properties.
  1263. proto = obj;
  1264. }
  1265. if (!proto) {
  1266. return false;
  1267. }
  1268. if (proto[zoneSymbolAddEventListener]) {
  1269. return false;
  1270. }
  1271. const eventNameToString = patchOptions && patchOptions.eventNameToString;
  1272. // We use a shared global `taskData` to pass data for `scheduleEventTask`,
  1273. // eliminating the need to create a new object solely for passing data.
  1274. // WARNING: This object has a static lifetime, meaning it is not created
  1275. // each time `addEventListener` is called. It is instantiated only once
  1276. // and captured by reference inside the `addEventListener` and
  1277. // `removeEventListener` functions. Do not add any new properties to this
  1278. // object, as doing so would necessitate maintaining the information
  1279. // between `addEventListener` calls.
  1280. const taskData = {};
  1281. const nativeAddEventListener = (proto[zoneSymbolAddEventListener] = proto[ADD_EVENT_LISTENER]);
  1282. const nativeRemoveEventListener = (proto[zoneSymbol(REMOVE_EVENT_LISTENER)] =
  1283. proto[REMOVE_EVENT_LISTENER]);
  1284. const nativeListeners = (proto[zoneSymbol(LISTENERS_EVENT_LISTENER)] =
  1285. proto[LISTENERS_EVENT_LISTENER]);
  1286. const nativeRemoveAllListeners = (proto[zoneSymbol(REMOVE_ALL_LISTENERS_EVENT_LISTENER)] =
  1287. proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER]);
  1288. let nativePrependEventListener;
  1289. if (patchOptions && patchOptions.prepend) {
  1290. nativePrependEventListener = proto[zoneSymbol(patchOptions.prepend)] =
  1291. proto[patchOptions.prepend];
  1292. }
  1293. /**
  1294. * This util function will build an option object with passive option
  1295. * to handle all possible input from the user.
  1296. */
  1297. function buildEventListenerOptions(options, passive) {
  1298. if (!passive) {
  1299. return options;
  1300. }
  1301. if (typeof options === 'boolean') {
  1302. return { capture: options, passive: true };
  1303. }
  1304. if (!options) {
  1305. return { passive: true };
  1306. }
  1307. if (typeof options === 'object' && options.passive !== false) {
  1308. return { ...options, passive: true };
  1309. }
  1310. return options;
  1311. }
  1312. const customScheduleGlobal = function (task) {
  1313. // if there is already a task for the eventName + capture,
  1314. // just return, because we use the shared globalZoneAwareCallback here.
  1315. if (taskData.isExisting) {
  1316. return;
  1317. }
  1318. return nativeAddEventListener.call(taskData.target, taskData.eventName, taskData.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, taskData.options);
  1319. };
  1320. /**
  1321. * In the context of events and listeners, this function will be
  1322. * called at the end by `cancelTask`, which, in turn, calls `task.cancelFn`.
  1323. * Cancelling a task is primarily used to remove event listeners from
  1324. * the task target.
  1325. */
  1326. const customCancelGlobal = function (task) {
  1327. // if task is not marked as isRemoved, this call is directly
  1328. // from Zone.prototype.cancelTask, we should remove the task
  1329. // from tasksList of target first
  1330. if (!task.isRemoved) {
  1331. const symbolEventNames = zoneSymbolEventNames[task.eventName];
  1332. let symbolEventName;
  1333. if (symbolEventNames) {
  1334. symbolEventName = symbolEventNames[task.capture ? TRUE_STR : FALSE_STR];
  1335. }
  1336. const existingTasks = symbolEventName && task.target[symbolEventName];
  1337. if (existingTasks) {
  1338. for (let i = 0; i < existingTasks.length; i++) {
  1339. const existingTask = existingTasks[i];
  1340. if (existingTask === task) {
  1341. existingTasks.splice(i, 1);
  1342. // set isRemoved to data for faster invokeTask check
  1343. task.isRemoved = true;
  1344. if (task.removeAbortListener) {
  1345. task.removeAbortListener();
  1346. task.removeAbortListener = null;
  1347. }
  1348. if (existingTasks.length === 0) {
  1349. // all tasks for the eventName + capture have gone,
  1350. // remove globalZoneAwareCallback and remove the task cache from target
  1351. task.allRemoved = true;
  1352. task.target[symbolEventName] = null;
  1353. }
  1354. break;
  1355. }
  1356. }
  1357. }
  1358. }
  1359. // if all tasks for the eventName + capture have gone,
  1360. // we will really remove the global event callback,
  1361. // if not, return
  1362. if (!task.allRemoved) {
  1363. return;
  1364. }
  1365. return nativeRemoveEventListener.call(task.target, task.eventName, task.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, task.options);
  1366. };
  1367. const customScheduleNonGlobal = function (task) {
  1368. return nativeAddEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
  1369. };
  1370. const customSchedulePrepend = function (task) {
  1371. return nativePrependEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
  1372. };
  1373. const customCancelNonGlobal = function (task) {
  1374. return nativeRemoveEventListener.call(task.target, task.eventName, task.invoke, task.options);
  1375. };
  1376. const customSchedule = useGlobalCallback ? customScheduleGlobal : customScheduleNonGlobal;
  1377. const customCancel = useGlobalCallback ? customCancelGlobal : customCancelNonGlobal;
  1378. const compareTaskCallbackVsDelegate = function (task, delegate) {
  1379. const typeOfDelegate = typeof delegate;
  1380. return ((typeOfDelegate === 'function' && task.callback === delegate) ||
  1381. (typeOfDelegate === 'object' && task.originalDelegate === delegate));
  1382. };
  1383. const compare = patchOptions?.diff || compareTaskCallbackVsDelegate;
  1384. const unpatchedEvents = Zone[zoneSymbol('UNPATCHED_EVENTS')];
  1385. const passiveEvents = _global[zoneSymbol('PASSIVE_EVENTS')];
  1386. function copyEventListenerOptions(options) {
  1387. if (typeof options === 'object' && options !== null) {
  1388. // We need to destructure the target `options` object since it may
  1389. // be frozen or sealed (possibly provided implicitly by a third-party
  1390. // library), or its properties may be readonly.
  1391. const newOptions = { ...options };
  1392. // The `signal` option was recently introduced, which caused regressions in
  1393. // third-party scenarios where `AbortController` was directly provided to
  1394. // `addEventListener` as options. For instance, in cases like
  1395. // `document.addEventListener('keydown', callback, abortControllerInstance)`,
  1396. // which is valid because `AbortController` includes a `signal` getter, spreading
  1397. // `{...options}` wouldn't copy the `signal`. Additionally, using `Object.create`
  1398. // isn't feasible since `AbortController` is a built-in object type, and attempting
  1399. // to create a new object directly with it as the prototype might result in
  1400. // unexpected behavior.
  1401. if (options.signal) {
  1402. newOptions.signal = options.signal;
  1403. }
  1404. return newOptions;
  1405. }
  1406. return options;
  1407. }
  1408. const makeAddListener = function (nativeListener, addSource, customScheduleFn, customCancelFn, returnTarget = false, prepend = false) {
  1409. return function () {
  1410. const target = this || _global;
  1411. let eventName = arguments[0];
  1412. if (patchOptions && patchOptions.transferEventName) {
  1413. eventName = patchOptions.transferEventName(eventName);
  1414. }
  1415. let delegate = arguments[1];
  1416. if (!delegate) {
  1417. return nativeListener.apply(this, arguments);
  1418. }
  1419. if (isNode && eventName === 'uncaughtException') {
  1420. // don't patch uncaughtException of nodejs to prevent endless loop
  1421. return nativeListener.apply(this, arguments);
  1422. }
  1423. // To improve `addEventListener` performance, we will create the callback
  1424. // for the task later when the task is invoked.
  1425. let isEventListenerObject = false;
  1426. if (typeof delegate !== 'function') {
  1427. // This checks whether the provided listener argument is an object with
  1428. // a `handleEvent` method (since we can call `addEventListener` with a
  1429. // function `event => ...` or with an object `{ handleEvent: event => ... }`).
  1430. if (!delegate.handleEvent) {
  1431. return nativeListener.apply(this, arguments);
  1432. }
  1433. isEventListenerObject = true;
  1434. }
  1435. if (validateHandler && !validateHandler(nativeListener, delegate, target, arguments)) {
  1436. return;
  1437. }
  1438. const passive = !!passiveEvents && passiveEvents.indexOf(eventName) !== -1;
  1439. const options = copyEventListenerOptions(buildEventListenerOptions(arguments[2], passive));
  1440. const signal = options?.signal;
  1441. if (signal?.aborted) {
  1442. // the signal is an aborted one, just return without attaching the event listener.
  1443. return;
  1444. }
  1445. if (unpatchedEvents) {
  1446. // check unpatched list
  1447. for (let i = 0; i < unpatchedEvents.length; i++) {
  1448. if (eventName === unpatchedEvents[i]) {
  1449. if (passive) {
  1450. return nativeListener.call(target, eventName, delegate, options);
  1451. }
  1452. else {
  1453. return nativeListener.apply(this, arguments);
  1454. }
  1455. }
  1456. }
  1457. }
  1458. const capture = !options ? false : typeof options === 'boolean' ? true : options.capture;
  1459. const once = options && typeof options === 'object' ? options.once : false;
  1460. const zone = Zone.current;
  1461. let symbolEventNames = zoneSymbolEventNames[eventName];
  1462. if (!symbolEventNames) {
  1463. prepareEventNames(eventName, eventNameToString);
  1464. symbolEventNames = zoneSymbolEventNames[eventName];
  1465. }
  1466. const symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
  1467. let existingTasks = target[symbolEventName];
  1468. let isExisting = false;
  1469. if (existingTasks) {
  1470. // already have task registered
  1471. isExisting = true;
  1472. if (checkDuplicate) {
  1473. for (let i = 0; i < existingTasks.length; i++) {
  1474. if (compare(existingTasks[i], delegate)) {
  1475. // same callback, same capture, same event name, just return
  1476. return;
  1477. }
  1478. }
  1479. }
  1480. }
  1481. else {
  1482. existingTasks = target[symbolEventName] = [];
  1483. }
  1484. let source;
  1485. const constructorName = target.constructor['name'];
  1486. const targetSource = globalSources[constructorName];
  1487. if (targetSource) {
  1488. source = targetSource[eventName];
  1489. }
  1490. if (!source) {
  1491. source =
  1492. constructorName +
  1493. addSource +
  1494. (eventNameToString ? eventNameToString(eventName) : eventName);
  1495. }
  1496. // In the code below, `options` should no longer be reassigned; instead, it
  1497. // should only be mutated. This is because we pass that object to the native
  1498. // `addEventListener`.
  1499. // It's generally recommended to use the same object reference for options.
  1500. // This ensures consistency and avoids potential issues.
  1501. taskData.options = options;
  1502. if (once) {
  1503. // When using `addEventListener` with the `once` option, we don't pass
  1504. // the `once` option directly to the native `addEventListener` method.
  1505. // Instead, we keep the `once` setting and handle it ourselves.
  1506. taskData.options.once = false;
  1507. }
  1508. taskData.target = target;
  1509. taskData.capture = capture;
  1510. taskData.eventName = eventName;
  1511. taskData.isExisting = isExisting;
  1512. const data = useGlobalCallback ? OPTIMIZED_ZONE_EVENT_TASK_DATA : undefined;
  1513. // keep taskData into data to allow onScheduleEventTask to access the task information
  1514. if (data) {
  1515. data.taskData = taskData;
  1516. }
  1517. if (signal) {
  1518. // When using `addEventListener` with the `signal` option, we don't pass
  1519. // the `signal` option directly to the native `addEventListener` method.
  1520. // Instead, we keep the `signal` setting and handle it ourselves.
  1521. taskData.options.signal = undefined;
  1522. }
  1523. // The `scheduleEventTask` function will ultimately call `customScheduleGlobal`,
  1524. // which in turn calls the native `addEventListener`. This is why `taskData.options`
  1525. // is updated before scheduling the task, as `customScheduleGlobal` uses
  1526. // `taskData.options` to pass it to the native `addEventListener`.
  1527. const task = zone.scheduleEventTask(source, delegate, data, customScheduleFn, customCancelFn);
  1528. if (signal) {
  1529. // after task is scheduled, we need to store the signal back to task.options
  1530. taskData.options.signal = signal;
  1531. // Wrapping `task` in a weak reference would not prevent memory leaks. Weak references are
  1532. // primarily used for preventing strong references cycles. `onAbort` is always reachable
  1533. // as it's an event listener, so its closure retains a strong reference to the `task`.
  1534. const onAbort = () => task.zone.cancelTask(task);
  1535. nativeListener.call(signal, 'abort', onAbort, { once: true });
  1536. // We need to remove the `abort` listener when the event listener is going to be removed,
  1537. // as it creates a closure that captures `task`. This closure retains a reference to the
  1538. // `task` object even after it goes out of scope, preventing `task` from being garbage
  1539. // collected.
  1540. task.removeAbortListener = () => signal.removeEventListener('abort', onAbort);
  1541. }
  1542. // should clear taskData.target to avoid memory leak
  1543. // issue, https://github.com/angular/angular/issues/20442
  1544. taskData.target = null;
  1545. // need to clear up taskData because it is a global object
  1546. if (data) {
  1547. data.taskData = null;
  1548. }
  1549. // have to save those information to task in case
  1550. // application may call task.zone.cancelTask() directly
  1551. if (once) {
  1552. taskData.options.once = true;
  1553. }
  1554. if (typeof task.options !== 'boolean') {
  1555. // We should save the options on the task (if it's an object) because
  1556. // we'll be using `task.options` later when removing the event listener
  1557. // and passing it back to `removeEventListener`.
  1558. task.options = options;
  1559. }
  1560. task.target = target;
  1561. task.capture = capture;
  1562. task.eventName = eventName;
  1563. if (isEventListenerObject) {
  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.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 = [];
  2033. // In older browsers like IE or Edge, event handler properties (e.g., `onclick`)
  2034. // may not be defined directly on the `window` object but on its prototype (`WindowPrototype`).
  2035. // To ensure complete coverage, we use the prototype when checking
  2036. // for and patching these properties.
  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?.prototype &&
  2053. patchFilteredProperties(target.prototype, getOnEventNames(target.prototype), ignoreProperties);
  2054. }
  2055. }
  2056. /**
  2057. * @fileoverview
  2058. * @suppress {missingRequire}
  2059. */
  2060. function patchBrowser(Zone) {
  2061. Zone.__load_patch('legacy', (global) => {
  2062. const legacyPatch = global[Zone.__symbol__('legacyPatch')];
  2063. if (legacyPatch) {
  2064. legacyPatch();
  2065. }
  2066. });
  2067. Zone.__load_patch('timers', (global) => {
  2068. const set = 'set';
  2069. const clear = 'clear';
  2070. patchTimer(global, set, clear, 'Timeout');
  2071. patchTimer(global, set, clear, 'Interval');
  2072. patchTimer(global, set, clear, 'Immediate');
  2073. });
  2074. Zone.__load_patch('requestAnimationFrame', (global) => {
  2075. patchTimer(global, 'request', 'cancel', 'AnimationFrame');
  2076. patchTimer(global, 'mozRequest', 'mozCancel', 'AnimationFrame');
  2077. patchTimer(global, 'webkitRequest', 'webkitCancel', 'AnimationFrame');
  2078. });
  2079. Zone.__load_patch('blocking', (global, Zone) => {
  2080. const blockingMethods = ['alert', 'prompt', 'confirm'];
  2081. for (let i = 0; i < blockingMethods.length; i++) {
  2082. const name = blockingMethods[i];
  2083. patchMethod(global, name, (delegate, symbol, name) => {
  2084. return function (s, args) {
  2085. return Zone.current.run(delegate, global, args, name);
  2086. };
  2087. });
  2088. }
  2089. });
  2090. Zone.__load_patch('EventTarget', (global, Zone, api) => {
  2091. patchEvent(global, api);
  2092. eventTargetPatch(global, api);
  2093. // patch XMLHttpRequestEventTarget's addEventListener/removeEventListener
  2094. const XMLHttpRequestEventTarget = global['XMLHttpRequestEventTarget'];
  2095. if (XMLHttpRequestEventTarget && XMLHttpRequestEventTarget.prototype) {
  2096. api.patchEventTarget(global, api, [XMLHttpRequestEventTarget.prototype]);
  2097. }
  2098. });
  2099. Zone.__load_patch('MutationObserver', (global, Zone, api) => {
  2100. patchClass('MutationObserver');
  2101. patchClass('WebKitMutationObserver');
  2102. });
  2103. Zone.__load_patch('IntersectionObserver', (global, Zone, api) => {
  2104. patchClass('IntersectionObserver');
  2105. });
  2106. Zone.__load_patch('FileReader', (global, Zone, api) => {
  2107. patchClass('FileReader');
  2108. });
  2109. Zone.__load_patch('on_property', (global, Zone, api) => {
  2110. propertyDescriptorPatch(api, global);
  2111. });
  2112. Zone.__load_patch('customElements', (global, Zone, api) => {
  2113. patchCustomElements(global, api);
  2114. });
  2115. Zone.__load_patch('XHR', (global, Zone) => {
  2116. // Treat XMLHttpRequest as a macrotask.
  2117. patchXHR(global);
  2118. const XHR_TASK = zoneSymbol('xhrTask');
  2119. const XHR_SYNC = zoneSymbol('xhrSync');
  2120. const XHR_LISTENER = zoneSymbol('xhrListener');
  2121. const XHR_SCHEDULED = zoneSymbol('xhrScheduled');
  2122. const XHR_URL = zoneSymbol('xhrURL');
  2123. const XHR_ERROR_BEFORE_SCHEDULED = zoneSymbol('xhrErrorBeforeScheduled');
  2124. function patchXHR(window) {
  2125. const XMLHttpRequest = window['XMLHttpRequest'];
  2126. if (!XMLHttpRequest) {
  2127. // XMLHttpRequest is not available in service worker
  2128. return;
  2129. }
  2130. const XMLHttpRequestPrototype = XMLHttpRequest.prototype;
  2131. function findPendingTask(target) {
  2132. return target[XHR_TASK];
  2133. }
  2134. let oriAddListener = XMLHttpRequestPrototype[ZONE_SYMBOL_ADD_EVENT_LISTENER];
  2135. let oriRemoveListener = XMLHttpRequestPrototype[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
  2136. if (!oriAddListener) {
  2137. const XMLHttpRequestEventTarget = window['XMLHttpRequestEventTarget'];
  2138. if (XMLHttpRequestEventTarget) {
  2139. const XMLHttpRequestEventTargetPrototype = XMLHttpRequestEventTarget.prototype;
  2140. oriAddListener = XMLHttpRequestEventTargetPrototype[ZONE_SYMBOL_ADD_EVENT_LISTENER];
  2141. oriRemoveListener = XMLHttpRequestEventTargetPrototype[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
  2142. }
  2143. }
  2144. const READY_STATE_CHANGE = 'readystatechange';
  2145. const SCHEDULED = 'scheduled';
  2146. function scheduleTask(task) {
  2147. const data = task.data;
  2148. const target = data.target;
  2149. target[XHR_SCHEDULED] = false;
  2150. target[XHR_ERROR_BEFORE_SCHEDULED] = false;
  2151. // remove existing event listener
  2152. const listener = target[XHR_LISTENER];
  2153. if (!oriAddListener) {
  2154. oriAddListener = target[ZONE_SYMBOL_ADD_EVENT_LISTENER];
  2155. oriRemoveListener = target[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
  2156. }
  2157. if (listener) {
  2158. oriRemoveListener.call(target, READY_STATE_CHANGE, listener);
  2159. }
  2160. const newListener = (target[XHR_LISTENER] = () => {
  2161. if (target.readyState === target.DONE) {
  2162. // sometimes on some browsers XMLHttpRequest will fire onreadystatechange with
  2163. // readyState=4 multiple times, so we need to check task state here
  2164. if (!data.aborted && target[XHR_SCHEDULED] && task.state === SCHEDULED) {
  2165. // check whether the xhr has registered onload listener
  2166. // if that is the case, the task should invoke after all
  2167. // onload listeners finish.
  2168. // Also if the request failed without response (status = 0), the load event handler
  2169. // will not be triggered, in that case, we should also invoke the placeholder callback
  2170. // to close the XMLHttpRequest::send macroTask.
  2171. // https://github.com/angular/angular/issues/38795
  2172. const loadTasks = target[Zone.__symbol__('loadfalse')];
  2173. if (target.status !== 0 && loadTasks && loadTasks.length > 0) {
  2174. const oriInvoke = task.invoke;
  2175. task.invoke = function () {
  2176. // need to load the tasks again, because in other
  2177. // load listener, they may remove themselves
  2178. const loadTasks = target[Zone.__symbol__('loadfalse')];
  2179. for (let i = 0; i < loadTasks.length; i++) {
  2180. if (loadTasks[i] === task) {
  2181. loadTasks.splice(i, 1);
  2182. }
  2183. }
  2184. if (!data.aborted && task.state === SCHEDULED) {
  2185. oriInvoke.call(task);
  2186. }
  2187. };
  2188. loadTasks.push(task);
  2189. }
  2190. else {
  2191. task.invoke();
  2192. }
  2193. }
  2194. else if (!data.aborted && target[XHR_SCHEDULED] === false) {
  2195. // error occurs when xhr.send()
  2196. target[XHR_ERROR_BEFORE_SCHEDULED] = true;
  2197. }
  2198. }
  2199. });
  2200. oriAddListener.call(target, READY_STATE_CHANGE, newListener);
  2201. const storedTask = target[XHR_TASK];
  2202. if (!storedTask) {
  2203. target[XHR_TASK] = task;
  2204. }
  2205. sendNative.apply(target, data.args);
  2206. target[XHR_SCHEDULED] = true;
  2207. return task;
  2208. }
  2209. function placeholderCallback() { }
  2210. function clearTask(task) {
  2211. const data = task.data;
  2212. // Note - ideally, we would call data.target.removeEventListener here, but it's too late
  2213. // to prevent it from firing. So instead, we store info for the event listener.
  2214. data.aborted = true;
  2215. return abortNative.apply(data.target, data.args);
  2216. }
  2217. const openNative = patchMethod(XMLHttpRequestPrototype, 'open', () => function (self, args) {
  2218. self[XHR_SYNC] = args[2] == false;
  2219. self[XHR_URL] = args[1];
  2220. return openNative.apply(self, args);
  2221. });
  2222. const XMLHTTPREQUEST_SOURCE = 'XMLHttpRequest.send';
  2223. const fetchTaskAborting = zoneSymbol('fetchTaskAborting');
  2224. const fetchTaskScheduling = zoneSymbol('fetchTaskScheduling');
  2225. const sendNative = patchMethod(XMLHttpRequestPrototype, 'send', () => function (self, args) {
  2226. if (Zone.current[fetchTaskScheduling] === true) {
  2227. // a fetch is scheduling, so we are using xhr to polyfill fetch
  2228. // and because we already schedule macroTask for fetch, we should
  2229. // not schedule a macroTask for xhr again
  2230. return sendNative.apply(self, args);
  2231. }
  2232. if (self[XHR_SYNC]) {
  2233. // if the XHR is sync there is no task to schedule, just execute the code.
  2234. return sendNative.apply(self, args);
  2235. }
  2236. else {
  2237. const options = {
  2238. target: self,
  2239. url: self[XHR_URL],
  2240. isPeriodic: false,
  2241. args: args,
  2242. aborted: false,
  2243. };
  2244. const task = scheduleMacroTaskWithCurrentZone(XMLHTTPREQUEST_SOURCE, placeholderCallback, options, scheduleTask, clearTask);
  2245. if (self &&
  2246. self[XHR_ERROR_BEFORE_SCHEDULED] === true &&
  2247. !options.aborted &&
  2248. task.state === SCHEDULED) {
  2249. // xhr request throw error when send
  2250. // we should invoke task instead of leaving a scheduled
  2251. // pending macroTask
  2252. task.invoke();
  2253. }
  2254. }
  2255. });
  2256. const abortNative = patchMethod(XMLHttpRequestPrototype, 'abort', () => function (self, args) {
  2257. const task = findPendingTask(self);
  2258. if (task && typeof task.type == 'string') {
  2259. // If the XHR has already completed, do nothing.
  2260. // If the XHR has already been aborted, do nothing.
  2261. // Fix #569, call abort multiple times before done will cause
  2262. // macroTask task count be negative number
  2263. if (task.cancelFn == null || (task.data && task.data.aborted)) {
  2264. return;
  2265. }
  2266. task.zone.cancelTask(task);
  2267. }
  2268. else if (Zone.current[fetchTaskAborting] === true) {
  2269. // the abort is called from fetch polyfill, we need to call native abort of XHR.
  2270. return abortNative.apply(self, args);
  2271. }
  2272. // Otherwise, we are trying to abort an XHR which has not yet been sent, so there is no
  2273. // task
  2274. // to cancel. Do nothing.
  2275. });
  2276. }
  2277. });
  2278. Zone.__load_patch('geolocation', (global) => {
  2279. /// GEO_LOCATION
  2280. if (global['navigator'] && global['navigator'].geolocation) {
  2281. patchPrototype(global['navigator'].geolocation, ['getCurrentPosition', 'watchPosition']);
  2282. }
  2283. });
  2284. Zone.__load_patch('PromiseRejectionEvent', (global, Zone) => {
  2285. // handle unhandled promise rejection
  2286. function findPromiseRejectionHandler(evtName) {
  2287. return function (e) {
  2288. const eventTasks = findEventTasks(global, evtName);
  2289. eventTasks.forEach((eventTask) => {
  2290. // windows has added unhandledrejection event listener
  2291. // trigger the event listener
  2292. const PromiseRejectionEvent = global['PromiseRejectionEvent'];
  2293. if (PromiseRejectionEvent) {
  2294. const evt = new PromiseRejectionEvent(evtName, {
  2295. promise: e.promise,
  2296. reason: e.rejection,
  2297. });
  2298. eventTask.invoke(evt);
  2299. }
  2300. });
  2301. };
  2302. }
  2303. if (global['PromiseRejectionEvent']) {
  2304. Zone[zoneSymbol('unhandledPromiseRejectionHandler')] =
  2305. findPromiseRejectionHandler('unhandledrejection');
  2306. Zone[zoneSymbol('rejectionHandledHandler')] =
  2307. findPromiseRejectionHandler('rejectionhandled');
  2308. }
  2309. });
  2310. Zone.__load_patch('queueMicrotask', (global, Zone, api) => {
  2311. patchQueueMicrotask(global, api);
  2312. });
  2313. }
  2314. function patchPromise(Zone) {
  2315. Zone.__load_patch('ZoneAwarePromise', (global, Zone, api) => {
  2316. const ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  2317. const ObjectDefineProperty = Object.defineProperty;
  2318. function readableObjectToString(obj) {
  2319. if (obj && obj.toString === Object.prototype.toString) {
  2320. const className = obj.constructor && obj.constructor.name;
  2321. return (className ? className : '') + ': ' + JSON.stringify(obj);
  2322. }
  2323. return obj ? obj.toString() : Object.prototype.toString.call(obj);
  2324. }
  2325. const __symbol__ = api.symbol;
  2326. const _uncaughtPromiseErrors = [];
  2327. const isDisableWrappingUncaughtPromiseRejection = global[__symbol__('DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION')] !== false;
  2328. const symbolPromise = __symbol__('Promise');
  2329. const symbolThen = __symbol__('then');
  2330. const creationTrace = '__creationTrace__';
  2331. api.onUnhandledError = (e) => {
  2332. if (api.showUncaughtError()) {
  2333. const rejection = e && e.rejection;
  2334. if (rejection) {
  2335. 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);
  2336. }
  2337. else {
  2338. console.error(e);
  2339. }
  2340. }
  2341. };
  2342. api.microtaskDrainDone = () => {
  2343. while (_uncaughtPromiseErrors.length) {
  2344. const uncaughtPromiseError = _uncaughtPromiseErrors.shift();
  2345. try {
  2346. uncaughtPromiseError.zone.runGuarded(() => {
  2347. if (uncaughtPromiseError.throwOriginal) {
  2348. throw uncaughtPromiseError.rejection;
  2349. }
  2350. throw uncaughtPromiseError;
  2351. });
  2352. }
  2353. catch (error) {
  2354. handleUnhandledRejection(error);
  2355. }
  2356. }
  2357. };
  2358. const UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL = __symbol__('unhandledPromiseRejectionHandler');
  2359. function handleUnhandledRejection(e) {
  2360. api.onUnhandledError(e);
  2361. try {
  2362. const handler = Zone[UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL];
  2363. if (typeof handler === 'function') {
  2364. handler.call(this, e);
  2365. }
  2366. }
  2367. catch (err) { }
  2368. }
  2369. function isThenable(value) {
  2370. return value && typeof value.then === 'function';
  2371. }
  2372. function forwardResolution(value) {
  2373. return value;
  2374. }
  2375. function forwardRejection(rejection) {
  2376. return ZoneAwarePromise.reject(rejection);
  2377. }
  2378. const symbolState = __symbol__('state');
  2379. const symbolValue = __symbol__('value');
  2380. const symbolFinally = __symbol__('finally');
  2381. const symbolParentPromiseValue = __symbol__('parentPromiseValue');
  2382. const symbolParentPromiseState = __symbol__('parentPromiseState');
  2383. const source = 'Promise.then';
  2384. const UNRESOLVED = null;
  2385. const RESOLVED = true;
  2386. const REJECTED = false;
  2387. const REJECTED_NO_CATCH = 0;
  2388. function makeResolver(promise, state) {
  2389. return (v) => {
  2390. try {
  2391. resolvePromise(promise, state, v);
  2392. }
  2393. catch (err) {
  2394. resolvePromise(promise, false, err);
  2395. }
  2396. // Do not return value or you will break the Promise spec.
  2397. };
  2398. }
  2399. const once = function () {
  2400. let wasCalled = false;
  2401. return function wrapper(wrappedFunction) {
  2402. return function () {
  2403. if (wasCalled) {
  2404. return;
  2405. }
  2406. wasCalled = true;
  2407. wrappedFunction.apply(null, arguments);
  2408. };
  2409. };
  2410. };
  2411. const TYPE_ERROR = 'Promise resolved with itself';
  2412. const CURRENT_TASK_TRACE_SYMBOL = __symbol__('currentTaskTrace');
  2413. // Promise Resolution
  2414. function resolvePromise(promise, state, value) {
  2415. const onceWrapper = once();
  2416. if (promise === value) {
  2417. throw new TypeError(TYPE_ERROR);
  2418. }
  2419. if (promise[symbolState] === UNRESOLVED) {
  2420. // should only get value.then once based on promise spec.
  2421. let then = null;
  2422. try {
  2423. if (typeof value === 'object' || typeof value === 'function') {
  2424. then = value && value.then;
  2425. }
  2426. }
  2427. catch (err) {
  2428. onceWrapper(() => {
  2429. resolvePromise(promise, false, err);
  2430. })();
  2431. return promise;
  2432. }
  2433. // if (value instanceof ZoneAwarePromise) {
  2434. if (state !== REJECTED &&
  2435. value instanceof ZoneAwarePromise &&
  2436. value.hasOwnProperty(symbolState) &&
  2437. value.hasOwnProperty(symbolValue) &&
  2438. value[symbolState] !== UNRESOLVED) {
  2439. clearRejectedNoCatch(value);
  2440. resolvePromise(promise, value[symbolState], value[symbolValue]);
  2441. }
  2442. else if (state !== REJECTED && typeof then === 'function') {
  2443. try {
  2444. then.call(value, onceWrapper(makeResolver(promise, state)), onceWrapper(makeResolver(promise, false)));
  2445. }
  2446. catch (err) {
  2447. onceWrapper(() => {
  2448. resolvePromise(promise, false, err);
  2449. })();
  2450. }
  2451. }
  2452. else {
  2453. promise[symbolState] = state;
  2454. const queue = promise[symbolValue];
  2455. promise[symbolValue] = value;
  2456. if (promise[symbolFinally] === symbolFinally) {
  2457. // the promise is generated by Promise.prototype.finally
  2458. if (state === RESOLVED) {
  2459. // the state is resolved, should ignore the value
  2460. // and use parent promise value
  2461. promise[symbolState] = promise[symbolParentPromiseState];
  2462. promise[symbolValue] = promise[symbolParentPromiseValue];
  2463. }
  2464. }
  2465. // record task information in value when error occurs, so we can
  2466. // do some additional work such as render longStackTrace
  2467. if (state === REJECTED && value instanceof Error) {
  2468. // check if longStackTraceZone is here
  2469. const trace = Zone.currentTask &&
  2470. Zone.currentTask.data &&
  2471. Zone.currentTask.data[creationTrace];
  2472. if (trace) {
  2473. // only keep the long stack trace into error when in longStackTraceZone
  2474. ObjectDefineProperty(value, CURRENT_TASK_TRACE_SYMBOL, {
  2475. configurable: true,
  2476. enumerable: false,
  2477. writable: true,
  2478. value: trace,
  2479. });
  2480. }
  2481. }
  2482. for (let i = 0; i < queue.length;) {
  2483. scheduleResolveOrReject(promise, queue[i++], queue[i++], queue[i++], queue[i++]);
  2484. }
  2485. if (queue.length == 0 && state == REJECTED) {
  2486. promise[symbolState] = REJECTED_NO_CATCH;
  2487. let uncaughtPromiseError = value;
  2488. try {
  2489. // Here we throws a new Error to print more readable error log
  2490. // and if the value is not an error, zone.js builds an `Error`
  2491. // Object here to attach the stack information.
  2492. throw new Error('Uncaught (in promise): ' +
  2493. readableObjectToString(value) +
  2494. (value && value.stack ? '\n' + value.stack : ''));
  2495. }
  2496. catch (err) {
  2497. uncaughtPromiseError = err;
  2498. }
  2499. if (isDisableWrappingUncaughtPromiseRejection) {
  2500. // If disable wrapping uncaught promise reject
  2501. // use the value instead of wrapping it.
  2502. uncaughtPromiseError.throwOriginal = true;
  2503. }
  2504. uncaughtPromiseError.rejection = value;
  2505. uncaughtPromiseError.promise = promise;
  2506. uncaughtPromiseError.zone = Zone.current;
  2507. uncaughtPromiseError.task = Zone.currentTask;
  2508. _uncaughtPromiseErrors.push(uncaughtPromiseError);
  2509. api.scheduleMicroTask(); // to make sure that it is running
  2510. }
  2511. }
  2512. }
  2513. // Resolving an already resolved promise is a noop.
  2514. return promise;
  2515. }
  2516. const REJECTION_HANDLED_HANDLER = __symbol__('rejectionHandledHandler');
  2517. function clearRejectedNoCatch(promise) {
  2518. if (promise[symbolState] === REJECTED_NO_CATCH) {
  2519. // if the promise is rejected no catch status
  2520. // and queue.length > 0, means there is a error handler
  2521. // here to handle the rejected promise, we should trigger
  2522. // windows.rejectionhandled eventHandler or nodejs rejectionHandled
  2523. // eventHandler
  2524. try {
  2525. const handler = Zone[REJECTION_HANDLED_HANDLER];
  2526. if (handler && typeof handler === 'function') {
  2527. handler.call(this, { rejection: promise[symbolValue], promise: promise });
  2528. }
  2529. }
  2530. catch (err) { }
  2531. promise[symbolState] = REJECTED;
  2532. for (let i = 0; i < _uncaughtPromiseErrors.length; i++) {
  2533. if (promise === _uncaughtPromiseErrors[i].promise) {
  2534. _uncaughtPromiseErrors.splice(i, 1);
  2535. }
  2536. }
  2537. }
  2538. }
  2539. function scheduleResolveOrReject(promise, zone, chainPromise, onFulfilled, onRejected) {
  2540. clearRejectedNoCatch(promise);
  2541. const promiseState = promise[symbolState];
  2542. const delegate = promiseState
  2543. ? typeof onFulfilled === 'function'
  2544. ? onFulfilled
  2545. : forwardResolution
  2546. : typeof onRejected === 'function'
  2547. ? onRejected
  2548. : forwardRejection;
  2549. zone.scheduleMicroTask(source, () => {
  2550. try {
  2551. const parentPromiseValue = promise[symbolValue];
  2552. const isFinallyPromise = !!chainPromise && symbolFinally === chainPromise[symbolFinally];
  2553. if (isFinallyPromise) {
  2554. // if the promise is generated from finally call, keep parent promise's state and value
  2555. chainPromise[symbolParentPromiseValue] = parentPromiseValue;
  2556. chainPromise[symbolParentPromiseState] = promiseState;
  2557. }
  2558. // should not pass value to finally callback
  2559. const value = zone.run(delegate, undefined, isFinallyPromise && delegate !== forwardRejection && delegate !== forwardResolution
  2560. ? []
  2561. : [parentPromiseValue]);
  2562. resolvePromise(chainPromise, true, value);
  2563. }
  2564. catch (error) {
  2565. // if error occurs, should always return this error
  2566. resolvePromise(chainPromise, false, error);
  2567. }
  2568. }, chainPromise);
  2569. }
  2570. const ZONE_AWARE_PROMISE_TO_STRING = 'function ZoneAwarePromise() { [native code] }';
  2571. const noop = function () { };
  2572. const AggregateError = global.AggregateError;
  2573. class ZoneAwarePromise {
  2574. static toString() {
  2575. return ZONE_AWARE_PROMISE_TO_STRING;
  2576. }
  2577. static resolve(value) {
  2578. if (value instanceof ZoneAwarePromise) {
  2579. return value;
  2580. }
  2581. return resolvePromise(new this(null), RESOLVED, value);
  2582. }
  2583. static reject(error) {
  2584. return resolvePromise(new this(null), REJECTED, error);
  2585. }
  2586. static withResolvers() {
  2587. const result = {};
  2588. result.promise = new ZoneAwarePromise((res, rej) => {
  2589. result.resolve = res;
  2590. result.reject = rej;
  2591. });
  2592. return result;
  2593. }
  2594. static any(values) {
  2595. if (!values || typeof values[Symbol.iterator] !== 'function') {
  2596. return Promise.reject(new AggregateError([], 'All promises were rejected'));
  2597. }
  2598. const promises = [];
  2599. let count = 0;
  2600. try {
  2601. for (let v of values) {
  2602. count++;
  2603. promises.push(ZoneAwarePromise.resolve(v));
  2604. }
  2605. }
  2606. catch (err) {
  2607. return Promise.reject(new AggregateError([], 'All promises were rejected'));
  2608. }
  2609. if (count === 0) {
  2610. return Promise.reject(new AggregateError([], 'All promises were rejected'));
  2611. }
  2612. let finished = false;
  2613. const errors = [];
  2614. return new ZoneAwarePromise((resolve, reject) => {
  2615. for (let i = 0; i < promises.length; i++) {
  2616. promises[i].then((v) => {
  2617. if (finished) {
  2618. return;
  2619. }
  2620. finished = true;
  2621. resolve(v);
  2622. }, (err) => {
  2623. errors.push(err);
  2624. count--;
  2625. if (count === 0) {
  2626. finished = true;
  2627. reject(new AggregateError(errors, 'All promises were rejected'));
  2628. }
  2629. });
  2630. }
  2631. });
  2632. }
  2633. static race(values) {
  2634. let resolve;
  2635. let reject;
  2636. let promise = new this((res, rej) => {
  2637. resolve = res;
  2638. reject = rej;
  2639. });
  2640. function onResolve(value) {
  2641. resolve(value);
  2642. }
  2643. function onReject(error) {
  2644. reject(error);
  2645. }
  2646. for (let value of values) {
  2647. if (!isThenable(value)) {
  2648. value = this.resolve(value);
  2649. }
  2650. value.then(onResolve, onReject);
  2651. }
  2652. return promise;
  2653. }
  2654. static all(values) {
  2655. return ZoneAwarePromise.allWithCallback(values);
  2656. }
  2657. static allSettled(values) {
  2658. const P = this && this.prototype instanceof ZoneAwarePromise ? this : ZoneAwarePromise;
  2659. return P.allWithCallback(values, {
  2660. thenCallback: (value) => ({ status: 'fulfilled', value }),
  2661. errorCallback: (err) => ({ status: 'rejected', reason: err }),
  2662. });
  2663. }
  2664. static allWithCallback(values, callback) {
  2665. let resolve;
  2666. let reject;
  2667. let promise = new this((res, rej) => {
  2668. resolve = res;
  2669. reject = rej;
  2670. });
  2671. // Start at 2 to prevent prematurely resolving if .then is called immediately.
  2672. let unresolvedCount = 2;
  2673. let valueIndex = 0;
  2674. const resolvedValues = [];
  2675. for (let value of values) {
  2676. if (!isThenable(value)) {
  2677. value = this.resolve(value);
  2678. }
  2679. const curValueIndex = valueIndex;
  2680. try {
  2681. value.then((value) => {
  2682. resolvedValues[curValueIndex] = callback ? callback.thenCallback(value) : value;
  2683. unresolvedCount--;
  2684. if (unresolvedCount === 0) {
  2685. resolve(resolvedValues);
  2686. }
  2687. }, (err) => {
  2688. if (!callback) {
  2689. reject(err);
  2690. }
  2691. else {
  2692. resolvedValues[curValueIndex] = callback.errorCallback(err);
  2693. unresolvedCount--;
  2694. if (unresolvedCount === 0) {
  2695. resolve(resolvedValues);
  2696. }
  2697. }
  2698. });
  2699. }
  2700. catch (thenErr) {
  2701. reject(thenErr);
  2702. }
  2703. unresolvedCount++;
  2704. valueIndex++;
  2705. }
  2706. // Make the unresolvedCount zero-based again.
  2707. unresolvedCount -= 2;
  2708. if (unresolvedCount === 0) {
  2709. resolve(resolvedValues);
  2710. }
  2711. return promise;
  2712. }
  2713. constructor(executor) {
  2714. const promise = this;
  2715. if (!(promise instanceof ZoneAwarePromise)) {
  2716. throw new Error('Must be an instanceof Promise.');
  2717. }
  2718. promise[symbolState] = UNRESOLVED;
  2719. promise[symbolValue] = []; // queue;
  2720. try {
  2721. const onceWrapper = once();
  2722. executor &&
  2723. executor(onceWrapper(makeResolver(promise, RESOLVED)), onceWrapper(makeResolver(promise, REJECTED)));
  2724. }
  2725. catch (error) {
  2726. resolvePromise(promise, false, error);
  2727. }
  2728. }
  2729. get [Symbol.toStringTag]() {
  2730. return 'Promise';
  2731. }
  2732. get [Symbol.species]() {
  2733. return ZoneAwarePromise;
  2734. }
  2735. then(onFulfilled, onRejected) {
  2736. // We must read `Symbol.species` safely because `this` may be anything. For instance, `this`
  2737. // may be an object without a prototype (created through `Object.create(null)`); thus
  2738. // `this.constructor` will be undefined. One of the use cases is SystemJS creating
  2739. // prototype-less objects (modules) via `Object.create(null)`. The SystemJS creates an empty
  2740. // object and copies promise properties into that object (within the `getOrCreateLoad`
  2741. // function). The zone.js then checks if the resolved value has the `then` method and
  2742. // invokes it with the `value` context. Otherwise, this will throw an error: `TypeError:
  2743. // Cannot read properties of undefined (reading 'Symbol(Symbol.species)')`.
  2744. let C = this.constructor?.[Symbol.species];
  2745. if (!C || typeof C !== 'function') {
  2746. C = this.constructor || ZoneAwarePromise;
  2747. }
  2748. const chainPromise = new C(noop);
  2749. const zone = Zone.current;
  2750. if (this[symbolState] == UNRESOLVED) {
  2751. this[symbolValue].push(zone, chainPromise, onFulfilled, onRejected);
  2752. }
  2753. else {
  2754. scheduleResolveOrReject(this, zone, chainPromise, onFulfilled, onRejected);
  2755. }
  2756. return chainPromise;
  2757. }
  2758. catch(onRejected) {
  2759. return this.then(null, onRejected);
  2760. }
  2761. finally(onFinally) {
  2762. // See comment on the call to `then` about why thee `Symbol.species` is safely accessed.
  2763. let C = this.constructor?.[Symbol.species];
  2764. if (!C || typeof C !== 'function') {
  2765. C = ZoneAwarePromise;
  2766. }
  2767. const chainPromise = new C(noop);
  2768. chainPromise[symbolFinally] = symbolFinally;
  2769. const zone = Zone.current;
  2770. if (this[symbolState] == UNRESOLVED) {
  2771. this[symbolValue].push(zone, chainPromise, onFinally, onFinally);
  2772. }
  2773. else {
  2774. scheduleResolveOrReject(this, zone, chainPromise, onFinally, onFinally);
  2775. }
  2776. return chainPromise;
  2777. }
  2778. }
  2779. // Protect against aggressive optimizers dropping seemingly unused properties.
  2780. // E.g. Closure Compiler in advanced mode.
  2781. ZoneAwarePromise['resolve'] = ZoneAwarePromise.resolve;
  2782. ZoneAwarePromise['reject'] = ZoneAwarePromise.reject;
  2783. ZoneAwarePromise['race'] = ZoneAwarePromise.race;
  2784. ZoneAwarePromise['all'] = ZoneAwarePromise.all;
  2785. const NativePromise = (global[symbolPromise] = global['Promise']);
  2786. global['Promise'] = ZoneAwarePromise;
  2787. const symbolThenPatched = __symbol__('thenPatched');
  2788. function patchThen(Ctor) {
  2789. const proto = Ctor.prototype;
  2790. const prop = ObjectGetOwnPropertyDescriptor(proto, 'then');
  2791. if (prop && (prop.writable === false || !prop.configurable)) {
  2792. // check Ctor.prototype.then propertyDescriptor is writable or not
  2793. // in meteor env, writable is false, we should ignore such case
  2794. return;
  2795. }
  2796. const originalThen = proto.then;
  2797. // Keep a reference to the original method.
  2798. proto[symbolThen] = originalThen;
  2799. Ctor.prototype.then = function (onResolve, onReject) {
  2800. const wrapped = new ZoneAwarePromise((resolve, reject) => {
  2801. originalThen.call(this, resolve, reject);
  2802. });
  2803. return wrapped.then(onResolve, onReject);
  2804. };
  2805. Ctor[symbolThenPatched] = true;
  2806. }
  2807. api.patchThen = patchThen;
  2808. function zoneify(fn) {
  2809. return function (self, args) {
  2810. let resultPromise = fn.apply(self, args);
  2811. if (resultPromise instanceof ZoneAwarePromise) {
  2812. return resultPromise;
  2813. }
  2814. let ctor = resultPromise.constructor;
  2815. if (!ctor[symbolThenPatched]) {
  2816. patchThen(ctor);
  2817. }
  2818. return resultPromise;
  2819. };
  2820. }
  2821. if (NativePromise) {
  2822. patchThen(NativePromise);
  2823. patchMethod(global, 'fetch', (delegate) => zoneify(delegate));
  2824. }
  2825. // This is not part of public API, but it is useful for tests, so we expose it.
  2826. Promise[Zone.__symbol__('uncaughtPromiseErrors')] = _uncaughtPromiseErrors;
  2827. return ZoneAwarePromise;
  2828. });
  2829. }
  2830. function patchToString(Zone) {
  2831. // override Function.prototype.toString to make zone.js patched function
  2832. // look like native function
  2833. Zone.__load_patch('toString', (global) => {
  2834. // patch Func.prototype.toString to let them look like native
  2835. const originalFunctionToString = Function.prototype.toString;
  2836. const ORIGINAL_DELEGATE_SYMBOL = zoneSymbol('OriginalDelegate');
  2837. const PROMISE_SYMBOL = zoneSymbol('Promise');
  2838. const ERROR_SYMBOL = zoneSymbol('Error');
  2839. const newFunctionToString = function toString() {
  2840. if (typeof this === 'function') {
  2841. const originalDelegate = this[ORIGINAL_DELEGATE_SYMBOL];
  2842. if (originalDelegate) {
  2843. if (typeof originalDelegate === 'function') {
  2844. return originalFunctionToString.call(originalDelegate);
  2845. }
  2846. else {
  2847. return Object.prototype.toString.call(originalDelegate);
  2848. }
  2849. }
  2850. if (this === Promise) {
  2851. const nativePromise = global[PROMISE_SYMBOL];
  2852. if (nativePromise) {
  2853. return originalFunctionToString.call(nativePromise);
  2854. }
  2855. }
  2856. if (this === Error) {
  2857. const nativeError = global[ERROR_SYMBOL];
  2858. if (nativeError) {
  2859. return originalFunctionToString.call(nativeError);
  2860. }
  2861. }
  2862. }
  2863. return originalFunctionToString.call(this);
  2864. };
  2865. newFunctionToString[ORIGINAL_DELEGATE_SYMBOL] = originalFunctionToString;
  2866. Function.prototype.toString = newFunctionToString;
  2867. // patch Object.prototype.toString to let them look like native
  2868. const originalObjectToString = Object.prototype.toString;
  2869. const PROMISE_OBJECT_TO_STRING = '[object Promise]';
  2870. Object.prototype.toString = function () {
  2871. if (typeof Promise === 'function' && this instanceof Promise) {
  2872. return PROMISE_OBJECT_TO_STRING;
  2873. }
  2874. return originalObjectToString.call(this);
  2875. };
  2876. });
  2877. }
  2878. function patchCallbacks(api, target, targetName, method, callbacks) {
  2879. const symbol = Zone.__symbol__(method);
  2880. if (target[symbol]) {
  2881. return;
  2882. }
  2883. const nativeDelegate = (target[symbol] = target[method]);
  2884. target[method] = function (name, opts, options) {
  2885. if (opts && opts.prototype) {
  2886. callbacks.forEach(function (callback) {
  2887. const source = `${targetName}.${method}::` + callback;
  2888. const prototype = opts.prototype;
  2889. // Note: the `patchCallbacks` is used for patching the `document.registerElement` and
  2890. // `customElements.define`. We explicitly wrap the patching code into try-catch since
  2891. // callbacks may be already patched by other web components frameworks (e.g. LWC), and they
  2892. // make those properties non-writable. This means that patching callback will throw an error
  2893. // `cannot assign to read-only property`. See this code as an example:
  2894. // https://github.com/salesforce/lwc/blob/master/packages/@lwc/engine-core/src/framework/base-bridge-element.ts#L180-L186
  2895. // We don't want to stop the application rendering if we couldn't patch some
  2896. // callback, e.g. `attributeChangedCallback`.
  2897. try {
  2898. if (prototype.hasOwnProperty(callback)) {
  2899. const descriptor = api.ObjectGetOwnPropertyDescriptor(prototype, callback);
  2900. if (descriptor && descriptor.value) {
  2901. descriptor.value = api.wrapWithCurrentZone(descriptor.value, source);
  2902. api._redefineProperty(opts.prototype, callback, descriptor);
  2903. }
  2904. else if (prototype[callback]) {
  2905. prototype[callback] = api.wrapWithCurrentZone(prototype[callback], source);
  2906. }
  2907. }
  2908. else if (prototype[callback]) {
  2909. prototype[callback] = api.wrapWithCurrentZone(prototype[callback], source);
  2910. }
  2911. }
  2912. catch {
  2913. // Note: we leave the catch block empty since there's no way to handle the error related
  2914. // to non-writable property.
  2915. }
  2916. });
  2917. }
  2918. return nativeDelegate.call(target, name, opts, options);
  2919. };
  2920. api.attachOriginToPatched(target[method], nativeDelegate);
  2921. }
  2922. function patchUtil(Zone) {
  2923. Zone.__load_patch('util', (global, Zone, api) => {
  2924. // Collect native event names by looking at properties
  2925. // on the global namespace, e.g. 'onclick'.
  2926. const eventNames = getOnEventNames(global);
  2927. api.patchOnProperties = patchOnProperties;
  2928. api.patchMethod = patchMethod;
  2929. api.bindArguments = bindArguments;
  2930. api.patchMacroTask = patchMacroTask;
  2931. // In earlier version of zone.js (<0.9.0), we use env name `__zone_symbol__BLACK_LISTED_EVENTS`
  2932. // to define which events will not be patched by `Zone.js`. In newer version (>=0.9.0), we
  2933. // change the env name to `__zone_symbol__UNPATCHED_EVENTS` to keep the name consistent with
  2934. // angular repo. The `__zone_symbol__BLACK_LISTED_EVENTS` is deprecated, but it is still be
  2935. // supported for backwards compatibility.
  2936. const SYMBOL_BLACK_LISTED_EVENTS = Zone.__symbol__('BLACK_LISTED_EVENTS');
  2937. const SYMBOL_UNPATCHED_EVENTS = Zone.__symbol__('UNPATCHED_EVENTS');
  2938. if (global[SYMBOL_UNPATCHED_EVENTS]) {
  2939. global[SYMBOL_BLACK_LISTED_EVENTS] = global[SYMBOL_UNPATCHED_EVENTS];
  2940. }
  2941. if (global[SYMBOL_BLACK_LISTED_EVENTS]) {
  2942. Zone[SYMBOL_BLACK_LISTED_EVENTS] = Zone[SYMBOL_UNPATCHED_EVENTS] =
  2943. global[SYMBOL_BLACK_LISTED_EVENTS];
  2944. }
  2945. api.patchEventPrototype = patchEventPrototype;
  2946. api.patchEventTarget = patchEventTarget;
  2947. api.isIEOrEdge = isIEOrEdge;
  2948. api.ObjectDefineProperty = ObjectDefineProperty;
  2949. api.ObjectGetOwnPropertyDescriptor = ObjectGetOwnPropertyDescriptor;
  2950. api.ObjectCreate = ObjectCreate;
  2951. api.ArraySlice = ArraySlice;
  2952. api.patchClass = patchClass;
  2953. api.wrapWithCurrentZone = wrapWithCurrentZone;
  2954. api.filterProperties = filterProperties;
  2955. api.attachOriginToPatched = attachOriginToPatched;
  2956. api._redefineProperty = Object.defineProperty;
  2957. api.patchCallbacks = patchCallbacks;
  2958. api.getGlobalObjects = () => ({
  2959. globalSources,
  2960. zoneSymbolEventNames,
  2961. eventNames,
  2962. isBrowser,
  2963. isMix,
  2964. isNode,
  2965. TRUE_STR,
  2966. FALSE_STR,
  2967. ZONE_SYMBOL_PREFIX,
  2968. ADD_EVENT_LISTENER_STR,
  2969. REMOVE_EVENT_LISTENER_STR,
  2970. });
  2971. });
  2972. }
  2973. function patchCommon(Zone) {
  2974. patchPromise(Zone);
  2975. patchToString(Zone);
  2976. patchUtil(Zone);
  2977. }
  2978. function patchEvents(Zone) {
  2979. Zone.__load_patch('EventEmitter', (global, Zone, api) => {
  2980. // For EventEmitter
  2981. const EE_ADD_LISTENER = 'addListener';
  2982. const EE_PREPEND_LISTENER = 'prependListener';
  2983. const EE_REMOVE_LISTENER = 'removeListener';
  2984. const EE_REMOVE_ALL_LISTENER = 'removeAllListeners';
  2985. const EE_LISTENERS = 'listeners';
  2986. const EE_ON = 'on';
  2987. const EE_OFF = 'off';
  2988. const compareTaskCallbackVsDelegate = function (task, delegate) {
  2989. // same callback, same capture, same event name, just return
  2990. return task.callback === delegate || task.callback.listener === delegate;
  2991. };
  2992. const eventNameToString = function (eventName) {
  2993. if (typeof eventName === 'string') {
  2994. return eventName;
  2995. }
  2996. if (!eventName) {
  2997. return '';
  2998. }
  2999. return eventName.toString().replace('(', '_').replace(')', '_');
  3000. };
  3001. function patchEventEmitterMethods(obj) {
  3002. const result = patchEventTarget(global, api, [obj], {
  3003. useG: false,
  3004. add: EE_ADD_LISTENER,
  3005. rm: EE_REMOVE_LISTENER,
  3006. prepend: EE_PREPEND_LISTENER,
  3007. rmAll: EE_REMOVE_ALL_LISTENER,
  3008. listeners: EE_LISTENERS,
  3009. chkDup: false,
  3010. rt: true,
  3011. diff: compareTaskCallbackVsDelegate,
  3012. eventNameToString: eventNameToString,
  3013. });
  3014. if (result && result[0]) {
  3015. obj[EE_ON] = obj[EE_ADD_LISTENER];
  3016. obj[EE_OFF] = obj[EE_REMOVE_LISTENER];
  3017. }
  3018. }
  3019. // EventEmitter
  3020. let events;
  3021. try {
  3022. events = require('events');
  3023. }
  3024. catch (err) { }
  3025. if (events && events.EventEmitter) {
  3026. patchEventEmitterMethods(events.EventEmitter.prototype);
  3027. }
  3028. });
  3029. }
  3030. function patchFs(Zone) {
  3031. Zone.__load_patch('fs', (global, Zone, api) => {
  3032. let fs;
  3033. try {
  3034. fs = require('fs');
  3035. }
  3036. catch (err) { }
  3037. if (!fs)
  3038. return;
  3039. // watch, watchFile, unwatchFile has been patched
  3040. // because EventEmitter has been patched
  3041. const TO_PATCH_MACROTASK_METHODS = [
  3042. 'access',
  3043. 'appendFile',
  3044. 'chmod',
  3045. 'chown',
  3046. 'close',
  3047. 'exists',
  3048. 'fchmod',
  3049. 'fchown',
  3050. 'fdatasync',
  3051. 'fstat',
  3052. 'fsync',
  3053. 'ftruncate',
  3054. 'futimes',
  3055. 'lchmod',
  3056. 'lchown',
  3057. 'lutimes',
  3058. 'link',
  3059. 'lstat',
  3060. 'mkdir',
  3061. 'mkdtemp',
  3062. 'open',
  3063. 'opendir',
  3064. 'read',
  3065. 'readdir',
  3066. 'readFile',
  3067. 'readlink',
  3068. 'realpath',
  3069. 'rename',
  3070. 'rmdir',
  3071. 'stat',
  3072. 'symlink',
  3073. 'truncate',
  3074. 'unlink',
  3075. 'utimes',
  3076. 'write',
  3077. 'writeFile',
  3078. 'writev',
  3079. ];
  3080. TO_PATCH_MACROTASK_METHODS.filter((name) => !!fs[name] && typeof fs[name] === 'function').forEach((name) => {
  3081. patchMacroTask(fs, name, (self, args) => {
  3082. return {
  3083. name: 'fs.' + name,
  3084. args: args,
  3085. cbIdx: args.length > 0 ? args.length - 1 : -1,
  3086. target: self,
  3087. };
  3088. });
  3089. });
  3090. const realpathOriginalDelegate = fs.realpath?.[api.symbol('OriginalDelegate')];
  3091. // This is the only specific method that should be additionally patched because the previous
  3092. // `patchMacroTask` has overridden the `realpath` function and its `native` property.
  3093. if (realpathOriginalDelegate?.native) {
  3094. fs.realpath.native = realpathOriginalDelegate.native;
  3095. patchMacroTask(fs.realpath, 'native', (self, args) => ({
  3096. args,
  3097. target: self,
  3098. cbIdx: args.length > 0 ? args.length - 1 : -1,
  3099. name: 'fs.realpath.native',
  3100. }));
  3101. }
  3102. });
  3103. }
  3104. function patchNodeUtil(Zone) {
  3105. Zone.__load_patch('node_util', (global, Zone, api) => {
  3106. api.patchOnProperties = patchOnProperties;
  3107. api.patchMethod = patchMethod;
  3108. api.bindArguments = bindArguments;
  3109. api.patchMacroTask = patchMacroTask;
  3110. setShouldCopySymbolProperties(true);
  3111. });
  3112. }
  3113. const set = 'set';
  3114. const clear = 'clear';
  3115. function patchNode(Zone) {
  3116. patchNodeUtil(Zone);
  3117. patchEvents(Zone);
  3118. patchFs(Zone);
  3119. Zone.__load_patch('node_timers', (global, Zone) => {
  3120. // Timers
  3121. let globalUseTimeoutFromTimer = false;
  3122. try {
  3123. const timers = require('timers');
  3124. let globalEqualTimersTimeout = global.setTimeout === timers.setTimeout;
  3125. if (!globalEqualTimersTimeout && !isMix) {
  3126. // 1. if isMix, then we are in mix environment such as Electron
  3127. // we should only patch timers.setTimeout because global.setTimeout
  3128. // have been patched
  3129. // 2. if global.setTimeout not equal timers.setTimeout, check
  3130. // whether global.setTimeout use timers.setTimeout or not
  3131. const originSetTimeout = timers.setTimeout;
  3132. timers.setTimeout = function () {
  3133. globalUseTimeoutFromTimer = true;
  3134. return originSetTimeout.apply(this, arguments);
  3135. };
  3136. const detectTimeout = global.setTimeout(() => { }, 100);
  3137. clearTimeout(detectTimeout);
  3138. timers.setTimeout = originSetTimeout;
  3139. }
  3140. patchTimer(timers, set, clear, 'Timeout');
  3141. patchTimer(timers, set, clear, 'Interval');
  3142. patchTimer(timers, set, clear, 'Immediate');
  3143. }
  3144. catch (error) {
  3145. // timers module not exists, for example, when we using nativeScript
  3146. // timers is not available
  3147. }
  3148. if (isMix) {
  3149. // if we are in mix environment, such as Electron,
  3150. // the global.setTimeout has already been patched,
  3151. // so we just patch timers.setTimeout
  3152. return;
  3153. }
  3154. if (!globalUseTimeoutFromTimer) {
  3155. // 1. global setTimeout equals timers setTimeout
  3156. // 2. or global don't use timers setTimeout(maybe some other library patch setTimeout)
  3157. // 3. or load timers module error happens, we should patch global setTimeout
  3158. patchTimer(global, set, clear, 'Timeout');
  3159. patchTimer(global, set, clear, 'Interval');
  3160. patchTimer(global, set, clear, 'Immediate');
  3161. }
  3162. else {
  3163. // global use timers setTimeout, but not equals
  3164. // this happens when use nodejs v0.10.x, global setTimeout will
  3165. // use a lazy load version of timers setTimeout
  3166. // we should not double patch timer's setTimeout
  3167. // so we only store the __symbol__ for consistency
  3168. global[Zone.__symbol__('setTimeout')] = global.setTimeout;
  3169. global[Zone.__symbol__('setInterval')] = global.setInterval;
  3170. global[Zone.__symbol__('setImmediate')] = global.setImmediate;
  3171. }
  3172. });
  3173. // patch process related methods
  3174. Zone.__load_patch('nextTick', () => {
  3175. // patch nextTick as microTask
  3176. patchMicroTask(process, 'nextTick', (self, args) => {
  3177. return {
  3178. name: 'process.nextTick',
  3179. args: args,
  3180. cbIdx: args.length > 0 && typeof args[0] === 'function' ? 0 : -1,
  3181. target: process,
  3182. };
  3183. });
  3184. });
  3185. Zone.__load_patch('handleUnhandledPromiseRejection', (global, Zone, api) => {
  3186. Zone[api.symbol('unhandledPromiseRejectionHandler')] =
  3187. findProcessPromiseRejectionHandler('unhandledRejection');
  3188. Zone[api.symbol('rejectionHandledHandler')] =
  3189. findProcessPromiseRejectionHandler('rejectionHandled');
  3190. // handle unhandled promise rejection
  3191. function findProcessPromiseRejectionHandler(evtName) {
  3192. return function (e) {
  3193. const eventTasks = findEventTasks(process, evtName);
  3194. eventTasks.forEach((eventTask) => {
  3195. // process has added unhandledrejection event listener
  3196. // trigger the event listener
  3197. if (evtName === 'unhandledRejection') {
  3198. eventTask.invoke(e.rejection, e.promise);
  3199. }
  3200. else if (evtName === 'rejectionHandled') {
  3201. eventTask.invoke(e.promise);
  3202. }
  3203. });
  3204. };
  3205. }
  3206. });
  3207. // Crypto
  3208. Zone.__load_patch('crypto', () => {
  3209. let crypto;
  3210. try {
  3211. crypto = require('crypto');
  3212. }
  3213. catch (err) { }
  3214. // use the generic patchMacroTask to patch crypto
  3215. if (crypto) {
  3216. const methodNames = ['randomBytes', 'pbkdf2'];
  3217. methodNames.forEach((name) => {
  3218. patchMacroTask(crypto, name, (self, args) => {
  3219. return {
  3220. name: 'crypto.' + name,
  3221. args: args,
  3222. cbIdx: args.length > 0 && typeof args[args.length - 1] === 'function' ? args.length - 1 : -1,
  3223. target: crypto,
  3224. };
  3225. });
  3226. });
  3227. }
  3228. });
  3229. Zone.__load_patch('console', (global, Zone) => {
  3230. const consoleMethods = [
  3231. 'dir',
  3232. 'log',
  3233. 'info',
  3234. 'error',
  3235. 'warn',
  3236. 'assert',
  3237. 'debug',
  3238. 'timeEnd',
  3239. 'trace',
  3240. ];
  3241. consoleMethods.forEach((m) => {
  3242. const originalMethod = (console[Zone.__symbol__(m)] = console[m]);
  3243. if (originalMethod) {
  3244. console[m] = function () {
  3245. const args = ArraySlice.call(arguments);
  3246. if (Zone.current === Zone.root) {
  3247. return originalMethod.apply(this, args);
  3248. }
  3249. else {
  3250. return Zone.root.run(originalMethod, this, args);
  3251. }
  3252. };
  3253. }
  3254. });
  3255. });
  3256. Zone.__load_patch('queueMicrotask', (global, Zone, api) => {
  3257. patchQueueMicrotask(global, api);
  3258. });
  3259. }
  3260. function loadZone() {
  3261. // if global['Zone'] already exists (maybe zone.js was already loaded or
  3262. // some other lib also registered a global object named Zone), we may need
  3263. // to throw an error, but sometimes user may not want this error.
  3264. // For example,
  3265. // we have two web pages, page1 includes zone.js, page2 doesn't.
  3266. // and the 1st time user load page1 and page2, everything work fine,
  3267. // but when user load page2 again, error occurs because global['Zone'] already exists.
  3268. // so we add a flag to let user choose whether to throw this error or not.
  3269. // By default, if existing Zone is from zone.js, we will not throw the error.
  3270. const global = globalThis;
  3271. const checkDuplicate = global[__symbol__('forceDuplicateZoneCheck')] === true;
  3272. if (global['Zone'] && (checkDuplicate || typeof global['Zone'].__symbol__ !== 'function')) {
  3273. throw new Error('Zone already loaded.');
  3274. }
  3275. // Initialize global `Zone` constant.
  3276. global['Zone'] ??= initZone();
  3277. return global['Zone'];
  3278. }
  3279. const Zone$1 = loadZone();
  3280. patchCommon(Zone$1);
  3281. patchBrowser(Zone$1);
  3282. patchNode(Zone$1);