zone-node.js 117 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688
  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. /** Array.prototype.slice */
  681. const ArraySlice = Array.prototype.slice;
  682. /** addEventListener string const */
  683. const ADD_EVENT_LISTENER_STR = 'addEventListener';
  684. /** removeEventListener string const */
  685. const REMOVE_EVENT_LISTENER_STR = 'removeEventListener';
  686. /** true string const */
  687. const TRUE_STR = 'true';
  688. /** false string const */
  689. const FALSE_STR = 'false';
  690. /** Zone symbol prefix string const. */
  691. const ZONE_SYMBOL_PREFIX = __symbol__('');
  692. function wrapWithCurrentZone(callback, source) {
  693. return Zone.current.wrap(callback, source);
  694. }
  695. function scheduleMacroTaskWithCurrentZone(source, callback, data, customSchedule, customCancel) {
  696. return Zone.current.scheduleMacroTask(source, callback, data, customSchedule, customCancel);
  697. }
  698. const zoneSymbol = __symbol__;
  699. const isWindowExists = typeof window !== 'undefined';
  700. const internalWindow = isWindowExists ? window : undefined;
  701. const _global = (isWindowExists && internalWindow) || globalThis;
  702. const REMOVE_ATTRIBUTE = 'removeAttribute';
  703. function bindArguments(args, source) {
  704. for (let i = args.length - 1; i >= 0; i--) {
  705. if (typeof args[i] === 'function') {
  706. args[i] = wrapWithCurrentZone(args[i], source + '_' + i);
  707. }
  708. }
  709. return args;
  710. }
  711. function isPropertyWritable(propertyDesc) {
  712. if (!propertyDesc) {
  713. return true;
  714. }
  715. if (propertyDesc.writable === false) {
  716. return false;
  717. }
  718. return !(typeof propertyDesc.get === 'function' && typeof propertyDesc.set === 'undefined');
  719. }
  720. const isWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
  721. // Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
  722. // this code.
  723. const isNode = !('nw' in _global) &&
  724. typeof _global.process !== 'undefined' &&
  725. _global.process.toString() === '[object process]';
  726. const isBrowser = !isNode && !isWebWorker && !!(isWindowExists && internalWindow['HTMLElement']);
  727. // we are in electron of nw, so we are both browser and nodejs
  728. // Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
  729. // this code.
  730. const isMix = typeof _global.process !== 'undefined' &&
  731. _global.process.toString() === '[object process]' &&
  732. !isWebWorker &&
  733. !!(isWindowExists && internalWindow['HTMLElement']);
  734. const zoneSymbolEventNames$1 = {};
  735. const enableBeforeunloadSymbol = zoneSymbol('enable_beforeunload');
  736. const wrapFn = function (event) {
  737. // https://github.com/angular/zone.js/issues/911, in IE, sometimes
  738. // event will be undefined, so we need to use window.event
  739. event = event || _global.event;
  740. if (!event) {
  741. return;
  742. }
  743. let eventNameSymbol = zoneSymbolEventNames$1[event.type];
  744. if (!eventNameSymbol) {
  745. eventNameSymbol = zoneSymbolEventNames$1[event.type] = zoneSymbol('ON_PROPERTY' + event.type);
  746. }
  747. const target = this || event.target || _global;
  748. const listener = target[eventNameSymbol];
  749. let result;
  750. if (isBrowser && target === internalWindow && event.type === 'error') {
  751. // window.onerror have different signature
  752. // https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror#window.onerror
  753. // and onerror callback will prevent default when callback return true
  754. const errorEvent = event;
  755. result =
  756. listener &&
  757. listener.call(this, errorEvent.message, errorEvent.filename, errorEvent.lineno, errorEvent.colno, errorEvent.error);
  758. if (result === true) {
  759. event.preventDefault();
  760. }
  761. }
  762. else {
  763. result = listener && listener.apply(this, arguments);
  764. if (
  765. // https://github.com/angular/angular/issues/47579
  766. // https://www.w3.org/TR/2011/WD-html5-20110525/history.html#beforeunloadevent
  767. // This is the only specific case we should check for. The spec defines that the
  768. // `returnValue` attribute represents the message to show the user. When the event
  769. // is created, this attribute must be set to the empty string.
  770. event.type === 'beforeunload' &&
  771. // To prevent any breaking changes resulting from this change, given that
  772. // it was already causing a significant number of failures in G3, we have hidden
  773. // that behavior behind a global configuration flag. Consumers can enable this
  774. // flag explicitly if they want the `beforeunload` event to be handled as defined
  775. // in the specification.
  776. _global[enableBeforeunloadSymbol] &&
  777. // The IDL event definition is `attribute DOMString returnValue`, so we check whether
  778. // `typeof result` is a string.
  779. typeof result === 'string') {
  780. event.returnValue = result;
  781. }
  782. else if (result != undefined && !result) {
  783. event.preventDefault();
  784. }
  785. }
  786. return result;
  787. };
  788. function patchProperty(obj, prop, prototype) {
  789. let desc = ObjectGetOwnPropertyDescriptor(obj, prop);
  790. if (!desc && prototype) {
  791. // when patch window object, use prototype to check prop exist or not
  792. const prototypeDesc = ObjectGetOwnPropertyDescriptor(prototype, prop);
  793. if (prototypeDesc) {
  794. desc = { enumerable: true, configurable: true };
  795. }
  796. }
  797. // if the descriptor not exists or is not configurable
  798. // just return
  799. if (!desc || !desc.configurable) {
  800. return;
  801. }
  802. const onPropPatchedSymbol = zoneSymbol('on' + prop + 'patched');
  803. if (obj.hasOwnProperty(onPropPatchedSymbol) && obj[onPropPatchedSymbol]) {
  804. return;
  805. }
  806. // A property descriptor cannot have getter/setter and be writable
  807. // deleting the writable and value properties avoids this error:
  808. //
  809. // TypeError: property descriptors must not specify a value or be writable when a
  810. // getter or setter has been specified
  811. delete desc.writable;
  812. delete desc.value;
  813. const originalDescGet = desc.get;
  814. const originalDescSet = desc.set;
  815. // slice(2) cuz 'onclick' -> 'click', etc
  816. const eventName = prop.slice(2);
  817. let eventNameSymbol = zoneSymbolEventNames$1[eventName];
  818. if (!eventNameSymbol) {
  819. eventNameSymbol = zoneSymbolEventNames$1[eventName] = zoneSymbol('ON_PROPERTY' + eventName);
  820. }
  821. desc.set = function (newValue) {
  822. // In some versions of Windows, the `this` context may be undefined
  823. // in on-property callbacks.
  824. // To handle this edge case, we check if `this` is falsy and
  825. // fallback to `_global` if needed.
  826. let target = this;
  827. if (!target && obj === _global) {
  828. target = _global;
  829. }
  830. if (!target) {
  831. return;
  832. }
  833. const previousValue = target[eventNameSymbol];
  834. if (typeof previousValue === 'function') {
  835. target.removeEventListener(eventName, wrapFn);
  836. }
  837. // https://github.com/angular/zone.js/issues/978
  838. // If an inline handler (like `onload`) was defined before zone.js was loaded,
  839. // call the original descriptor's setter to clean it up.
  840. originalDescSet?.call(target, null);
  841. target[eventNameSymbol] = newValue;
  842. if (typeof newValue === 'function') {
  843. target.addEventListener(eventName, wrapFn, false);
  844. }
  845. };
  846. // The getter would return undefined for unassigned properties but the default value of an
  847. // unassigned property is null
  848. desc.get = function () {
  849. // in some of windows's onproperty callback, this is undefined
  850. // so we need to check it
  851. let target = this;
  852. if (!target && obj === _global) {
  853. target = _global;
  854. }
  855. if (!target) {
  856. return null;
  857. }
  858. const listener = target[eventNameSymbol];
  859. if (listener) {
  860. return listener;
  861. }
  862. else if (originalDescGet) {
  863. // result will be null when use inline event attribute,
  864. // such as <button onclick="func();">OK</button>
  865. // because the onclick function is internal raw uncompiled handler
  866. // the onclick will be evaluated when first time event was triggered or
  867. // the property is accessed, https://github.com/angular/zone.js/issues/525
  868. // so we should use original native get to retrieve the handler
  869. let value = originalDescGet.call(this);
  870. if (value) {
  871. desc.set.call(this, value);
  872. if (typeof target[REMOVE_ATTRIBUTE] === 'function') {
  873. target.removeAttribute(prop);
  874. }
  875. return value;
  876. }
  877. }
  878. return null;
  879. };
  880. ObjectDefineProperty(obj, prop, desc);
  881. obj[onPropPatchedSymbol] = true;
  882. }
  883. function patchOnProperties(obj, properties, prototype) {
  884. if (properties) {
  885. for (let i = 0; i < properties.length; i++) {
  886. patchProperty(obj, 'on' + properties[i], prototype);
  887. }
  888. }
  889. else {
  890. const onProperties = [];
  891. for (const prop in obj) {
  892. if (prop.slice(0, 2) == 'on') {
  893. onProperties.push(prop);
  894. }
  895. }
  896. for (let j = 0; j < onProperties.length; j++) {
  897. patchProperty(obj, onProperties[j], prototype);
  898. }
  899. }
  900. }
  901. function copySymbolProperties(src, dest) {
  902. if (typeof Object.getOwnPropertySymbols !== 'function') {
  903. return;
  904. }
  905. const symbols = Object.getOwnPropertySymbols(src);
  906. symbols.forEach((symbol) => {
  907. const desc = Object.getOwnPropertyDescriptor(src, symbol);
  908. Object.defineProperty(dest, symbol, {
  909. get: function () {
  910. return src[symbol];
  911. },
  912. set: function (value) {
  913. if (desc && (!desc.writable || typeof desc.set !== 'function')) {
  914. // if src[symbol] is not writable or not have a setter, just return
  915. return;
  916. }
  917. src[symbol] = value;
  918. },
  919. enumerable: desc ? desc.enumerable : true,
  920. configurable: desc ? desc.configurable : true,
  921. });
  922. });
  923. }
  924. let shouldCopySymbolProperties = false;
  925. function setShouldCopySymbolProperties(flag) {
  926. shouldCopySymbolProperties = flag;
  927. }
  928. function patchMethod(target, name, patchFn) {
  929. let proto = target;
  930. while (proto && !proto.hasOwnProperty(name)) {
  931. proto = ObjectGetPrototypeOf(proto);
  932. }
  933. if (!proto && target[name]) {
  934. // somehow we did not find it, but we can see it. This happens on IE for Window properties.
  935. proto = target;
  936. }
  937. const delegateName = zoneSymbol(name);
  938. let delegate = null;
  939. if (proto && (!(delegate = proto[delegateName]) || !proto.hasOwnProperty(delegateName))) {
  940. delegate = proto[delegateName] = proto[name];
  941. // check whether proto[name] is writable
  942. // some property is readonly in safari, such as HtmlCanvasElement.prototype.toBlob
  943. const desc = proto && ObjectGetOwnPropertyDescriptor(proto, name);
  944. if (isPropertyWritable(desc)) {
  945. const patchDelegate = patchFn(delegate, delegateName, name);
  946. proto[name] = function () {
  947. return patchDelegate(this, arguments);
  948. };
  949. attachOriginToPatched(proto[name], delegate);
  950. if (shouldCopySymbolProperties) {
  951. copySymbolProperties(delegate, proto[name]);
  952. }
  953. }
  954. }
  955. return delegate;
  956. }
  957. // TODO: @JiaLiPassion, support cancel task later if necessary
  958. function patchMacroTask(obj, funcName, metaCreator) {
  959. let setNative = null;
  960. function scheduleTask(task) {
  961. const data = task.data;
  962. data.args[data.cbIdx] = function () {
  963. task.invoke.apply(this, arguments);
  964. };
  965. setNative.apply(data.target, data.args);
  966. return task;
  967. }
  968. setNative = patchMethod(obj, funcName, (delegate) => function (self, args) {
  969. const meta = metaCreator(self, args);
  970. if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
  971. return scheduleMacroTaskWithCurrentZone(meta.name, args[meta.cbIdx], meta, scheduleTask);
  972. }
  973. else {
  974. // cause an error by calling it directly.
  975. return delegate.apply(self, args);
  976. }
  977. });
  978. }
  979. function patchMicroTask(obj, funcName, metaCreator) {
  980. let setNative = null;
  981. function scheduleTask(task) {
  982. const data = task.data;
  983. data.args[data.cbIdx] = function () {
  984. task.invoke.apply(this, arguments);
  985. };
  986. setNative.apply(data.target, data.args);
  987. return task;
  988. }
  989. setNative = patchMethod(obj, funcName, (delegate) => function (self, args) {
  990. const meta = metaCreator(self, args);
  991. if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
  992. return Zone.current.scheduleMicroTask(meta.name, args[meta.cbIdx], meta, scheduleTask);
  993. }
  994. else {
  995. // cause an error by calling it directly.
  996. return delegate.apply(self, args);
  997. }
  998. });
  999. }
  1000. function attachOriginToPatched(patched, original) {
  1001. patched[zoneSymbol('OriginalDelegate')] = original;
  1002. }
  1003. function isFunction(value) {
  1004. return typeof value === 'function';
  1005. }
  1006. function isNumber(value) {
  1007. return typeof value === 'number';
  1008. }
  1009. function patchPromise(Zone) {
  1010. Zone.__load_patch('ZoneAwarePromise', (global, Zone, api) => {
  1011. const ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  1012. const ObjectDefineProperty = Object.defineProperty;
  1013. function readableObjectToString(obj) {
  1014. if (obj && obj.toString === Object.prototype.toString) {
  1015. const className = obj.constructor && obj.constructor.name;
  1016. return (className ? className : '') + ': ' + JSON.stringify(obj);
  1017. }
  1018. return obj ? obj.toString() : Object.prototype.toString.call(obj);
  1019. }
  1020. const __symbol__ = api.symbol;
  1021. const _uncaughtPromiseErrors = [];
  1022. const isDisableWrappingUncaughtPromiseRejection = global[__symbol__('DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION')] !== false;
  1023. const symbolPromise = __symbol__('Promise');
  1024. const symbolThen = __symbol__('then');
  1025. const creationTrace = '__creationTrace__';
  1026. api.onUnhandledError = (e) => {
  1027. if (api.showUncaughtError()) {
  1028. const rejection = e && e.rejection;
  1029. if (rejection) {
  1030. 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);
  1031. }
  1032. else {
  1033. console.error(e);
  1034. }
  1035. }
  1036. };
  1037. api.microtaskDrainDone = () => {
  1038. while (_uncaughtPromiseErrors.length) {
  1039. const uncaughtPromiseError = _uncaughtPromiseErrors.shift();
  1040. try {
  1041. uncaughtPromiseError.zone.runGuarded(() => {
  1042. if (uncaughtPromiseError.throwOriginal) {
  1043. throw uncaughtPromiseError.rejection;
  1044. }
  1045. throw uncaughtPromiseError;
  1046. });
  1047. }
  1048. catch (error) {
  1049. handleUnhandledRejection(error);
  1050. }
  1051. }
  1052. };
  1053. const UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL = __symbol__('unhandledPromiseRejectionHandler');
  1054. function handleUnhandledRejection(e) {
  1055. api.onUnhandledError(e);
  1056. try {
  1057. const handler = Zone[UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL];
  1058. if (typeof handler === 'function') {
  1059. handler.call(this, e);
  1060. }
  1061. }
  1062. catch (err) { }
  1063. }
  1064. function isThenable(value) {
  1065. return value && typeof value.then === 'function';
  1066. }
  1067. function forwardResolution(value) {
  1068. return value;
  1069. }
  1070. function forwardRejection(rejection) {
  1071. return ZoneAwarePromise.reject(rejection);
  1072. }
  1073. const symbolState = __symbol__('state');
  1074. const symbolValue = __symbol__('value');
  1075. const symbolFinally = __symbol__('finally');
  1076. const symbolParentPromiseValue = __symbol__('parentPromiseValue');
  1077. const symbolParentPromiseState = __symbol__('parentPromiseState');
  1078. const source = 'Promise.then';
  1079. const UNRESOLVED = null;
  1080. const RESOLVED = true;
  1081. const REJECTED = false;
  1082. const REJECTED_NO_CATCH = 0;
  1083. function makeResolver(promise, state) {
  1084. return (v) => {
  1085. try {
  1086. resolvePromise(promise, state, v);
  1087. }
  1088. catch (err) {
  1089. resolvePromise(promise, false, err);
  1090. }
  1091. // Do not return value or you will break the Promise spec.
  1092. };
  1093. }
  1094. const once = function () {
  1095. let wasCalled = false;
  1096. return function wrapper(wrappedFunction) {
  1097. return function () {
  1098. if (wasCalled) {
  1099. return;
  1100. }
  1101. wasCalled = true;
  1102. wrappedFunction.apply(null, arguments);
  1103. };
  1104. };
  1105. };
  1106. const TYPE_ERROR = 'Promise resolved with itself';
  1107. const CURRENT_TASK_TRACE_SYMBOL = __symbol__('currentTaskTrace');
  1108. // Promise Resolution
  1109. function resolvePromise(promise, state, value) {
  1110. const onceWrapper = once();
  1111. if (promise === value) {
  1112. throw new TypeError(TYPE_ERROR);
  1113. }
  1114. if (promise[symbolState] === UNRESOLVED) {
  1115. // should only get value.then once based on promise spec.
  1116. let then = null;
  1117. try {
  1118. if (typeof value === 'object' || typeof value === 'function') {
  1119. then = value && value.then;
  1120. }
  1121. }
  1122. catch (err) {
  1123. onceWrapper(() => {
  1124. resolvePromise(promise, false, err);
  1125. })();
  1126. return promise;
  1127. }
  1128. // if (value instanceof ZoneAwarePromise) {
  1129. if (state !== REJECTED &&
  1130. value instanceof ZoneAwarePromise &&
  1131. value.hasOwnProperty(symbolState) &&
  1132. value.hasOwnProperty(symbolValue) &&
  1133. value[symbolState] !== UNRESOLVED) {
  1134. clearRejectedNoCatch(value);
  1135. resolvePromise(promise, value[symbolState], value[symbolValue]);
  1136. }
  1137. else if (state !== REJECTED && typeof then === 'function') {
  1138. try {
  1139. then.call(value, onceWrapper(makeResolver(promise, state)), onceWrapper(makeResolver(promise, false)));
  1140. }
  1141. catch (err) {
  1142. onceWrapper(() => {
  1143. resolvePromise(promise, false, err);
  1144. })();
  1145. }
  1146. }
  1147. else {
  1148. promise[symbolState] = state;
  1149. const queue = promise[symbolValue];
  1150. promise[symbolValue] = value;
  1151. if (promise[symbolFinally] === symbolFinally) {
  1152. // the promise is generated by Promise.prototype.finally
  1153. if (state === RESOLVED) {
  1154. // the state is resolved, should ignore the value
  1155. // and use parent promise value
  1156. promise[symbolState] = promise[symbolParentPromiseState];
  1157. promise[symbolValue] = promise[symbolParentPromiseValue];
  1158. }
  1159. }
  1160. // record task information in value when error occurs, so we can
  1161. // do some additional work such as render longStackTrace
  1162. if (state === REJECTED && value instanceof Error) {
  1163. // check if longStackTraceZone is here
  1164. const trace = Zone.currentTask &&
  1165. Zone.currentTask.data &&
  1166. Zone.currentTask.data[creationTrace];
  1167. if (trace) {
  1168. // only keep the long stack trace into error when in longStackTraceZone
  1169. ObjectDefineProperty(value, CURRENT_TASK_TRACE_SYMBOL, {
  1170. configurable: true,
  1171. enumerable: false,
  1172. writable: true,
  1173. value: trace,
  1174. });
  1175. }
  1176. }
  1177. for (let i = 0; i < queue.length;) {
  1178. scheduleResolveOrReject(promise, queue[i++], queue[i++], queue[i++], queue[i++]);
  1179. }
  1180. if (queue.length == 0 && state == REJECTED) {
  1181. promise[symbolState] = REJECTED_NO_CATCH;
  1182. let uncaughtPromiseError = value;
  1183. try {
  1184. // Here we throws a new Error to print more readable error log
  1185. // and if the value is not an error, zone.js builds an `Error`
  1186. // Object here to attach the stack information.
  1187. throw new Error('Uncaught (in promise): ' +
  1188. readableObjectToString(value) +
  1189. (value && value.stack ? '\n' + value.stack : ''));
  1190. }
  1191. catch (err) {
  1192. uncaughtPromiseError = err;
  1193. }
  1194. if (isDisableWrappingUncaughtPromiseRejection) {
  1195. // If disable wrapping uncaught promise reject
  1196. // use the value instead of wrapping it.
  1197. uncaughtPromiseError.throwOriginal = true;
  1198. }
  1199. uncaughtPromiseError.rejection = value;
  1200. uncaughtPromiseError.promise = promise;
  1201. uncaughtPromiseError.zone = Zone.current;
  1202. uncaughtPromiseError.task = Zone.currentTask;
  1203. _uncaughtPromiseErrors.push(uncaughtPromiseError);
  1204. api.scheduleMicroTask(); // to make sure that it is running
  1205. }
  1206. }
  1207. }
  1208. // Resolving an already resolved promise is a noop.
  1209. return promise;
  1210. }
  1211. const REJECTION_HANDLED_HANDLER = __symbol__('rejectionHandledHandler');
  1212. function clearRejectedNoCatch(promise) {
  1213. if (promise[symbolState] === REJECTED_NO_CATCH) {
  1214. // if the promise is rejected no catch status
  1215. // and queue.length > 0, means there is a error handler
  1216. // here to handle the rejected promise, we should trigger
  1217. // windows.rejectionhandled eventHandler or nodejs rejectionHandled
  1218. // eventHandler
  1219. try {
  1220. const handler = Zone[REJECTION_HANDLED_HANDLER];
  1221. if (handler && typeof handler === 'function') {
  1222. handler.call(this, { rejection: promise[symbolValue], promise: promise });
  1223. }
  1224. }
  1225. catch (err) { }
  1226. promise[symbolState] = REJECTED;
  1227. for (let i = 0; i < _uncaughtPromiseErrors.length; i++) {
  1228. if (promise === _uncaughtPromiseErrors[i].promise) {
  1229. _uncaughtPromiseErrors.splice(i, 1);
  1230. }
  1231. }
  1232. }
  1233. }
  1234. function scheduleResolveOrReject(promise, zone, chainPromise, onFulfilled, onRejected) {
  1235. clearRejectedNoCatch(promise);
  1236. const promiseState = promise[symbolState];
  1237. const delegate = promiseState
  1238. ? typeof onFulfilled === 'function'
  1239. ? onFulfilled
  1240. : forwardResolution
  1241. : typeof onRejected === 'function'
  1242. ? onRejected
  1243. : forwardRejection;
  1244. zone.scheduleMicroTask(source, () => {
  1245. try {
  1246. const parentPromiseValue = promise[symbolValue];
  1247. const isFinallyPromise = !!chainPromise && symbolFinally === chainPromise[symbolFinally];
  1248. if (isFinallyPromise) {
  1249. // if the promise is generated from finally call, keep parent promise's state and value
  1250. chainPromise[symbolParentPromiseValue] = parentPromiseValue;
  1251. chainPromise[symbolParentPromiseState] = promiseState;
  1252. }
  1253. // should not pass value to finally callback
  1254. const value = zone.run(delegate, undefined, isFinallyPromise && delegate !== forwardRejection && delegate !== forwardResolution
  1255. ? []
  1256. : [parentPromiseValue]);
  1257. resolvePromise(chainPromise, true, value);
  1258. }
  1259. catch (error) {
  1260. // if error occurs, should always return this error
  1261. resolvePromise(chainPromise, false, error);
  1262. }
  1263. }, chainPromise);
  1264. }
  1265. const ZONE_AWARE_PROMISE_TO_STRING = 'function ZoneAwarePromise() { [native code] }';
  1266. const noop = function () { };
  1267. const AggregateError = global.AggregateError;
  1268. class ZoneAwarePromise {
  1269. static toString() {
  1270. return ZONE_AWARE_PROMISE_TO_STRING;
  1271. }
  1272. static resolve(value) {
  1273. if (value instanceof ZoneAwarePromise) {
  1274. return value;
  1275. }
  1276. return resolvePromise(new this(null), RESOLVED, value);
  1277. }
  1278. static reject(error) {
  1279. return resolvePromise(new this(null), REJECTED, error);
  1280. }
  1281. static withResolvers() {
  1282. const result = {};
  1283. result.promise = new ZoneAwarePromise((res, rej) => {
  1284. result.resolve = res;
  1285. result.reject = rej;
  1286. });
  1287. return result;
  1288. }
  1289. static any(values) {
  1290. if (!values || typeof values[Symbol.iterator] !== 'function') {
  1291. return Promise.reject(new AggregateError([], 'All promises were rejected'));
  1292. }
  1293. const promises = [];
  1294. let count = 0;
  1295. try {
  1296. for (let v of values) {
  1297. count++;
  1298. promises.push(ZoneAwarePromise.resolve(v));
  1299. }
  1300. }
  1301. catch (err) {
  1302. return Promise.reject(new AggregateError([], 'All promises were rejected'));
  1303. }
  1304. if (count === 0) {
  1305. return Promise.reject(new AggregateError([], 'All promises were rejected'));
  1306. }
  1307. let finished = false;
  1308. const errors = [];
  1309. return new ZoneAwarePromise((resolve, reject) => {
  1310. for (let i = 0; i < promises.length; i++) {
  1311. promises[i].then((v) => {
  1312. if (finished) {
  1313. return;
  1314. }
  1315. finished = true;
  1316. resolve(v);
  1317. }, (err) => {
  1318. errors.push(err);
  1319. count--;
  1320. if (count === 0) {
  1321. finished = true;
  1322. reject(new AggregateError(errors, 'All promises were rejected'));
  1323. }
  1324. });
  1325. }
  1326. });
  1327. }
  1328. static race(values) {
  1329. let resolve;
  1330. let reject;
  1331. let promise = new this((res, rej) => {
  1332. resolve = res;
  1333. reject = rej;
  1334. });
  1335. function onResolve(value) {
  1336. resolve(value);
  1337. }
  1338. function onReject(error) {
  1339. reject(error);
  1340. }
  1341. for (let value of values) {
  1342. if (!isThenable(value)) {
  1343. value = this.resolve(value);
  1344. }
  1345. value.then(onResolve, onReject);
  1346. }
  1347. return promise;
  1348. }
  1349. static all(values) {
  1350. return ZoneAwarePromise.allWithCallback(values);
  1351. }
  1352. static allSettled(values) {
  1353. const P = this && this.prototype instanceof ZoneAwarePromise ? this : ZoneAwarePromise;
  1354. return P.allWithCallback(values, {
  1355. thenCallback: (value) => ({ status: 'fulfilled', value }),
  1356. errorCallback: (err) => ({ status: 'rejected', reason: err }),
  1357. });
  1358. }
  1359. static allWithCallback(values, callback) {
  1360. let resolve;
  1361. let reject;
  1362. let promise = new this((res, rej) => {
  1363. resolve = res;
  1364. reject = rej;
  1365. });
  1366. // Start at 2 to prevent prematurely resolving if .then is called immediately.
  1367. let unresolvedCount = 2;
  1368. let valueIndex = 0;
  1369. const resolvedValues = [];
  1370. for (let value of values) {
  1371. if (!isThenable(value)) {
  1372. value = this.resolve(value);
  1373. }
  1374. const curValueIndex = valueIndex;
  1375. try {
  1376. value.then((value) => {
  1377. resolvedValues[curValueIndex] = callback ? callback.thenCallback(value) : value;
  1378. unresolvedCount--;
  1379. if (unresolvedCount === 0) {
  1380. resolve(resolvedValues);
  1381. }
  1382. }, (err) => {
  1383. if (!callback) {
  1384. reject(err);
  1385. }
  1386. else {
  1387. resolvedValues[curValueIndex] = callback.errorCallback(err);
  1388. unresolvedCount--;
  1389. if (unresolvedCount === 0) {
  1390. resolve(resolvedValues);
  1391. }
  1392. }
  1393. });
  1394. }
  1395. catch (thenErr) {
  1396. reject(thenErr);
  1397. }
  1398. unresolvedCount++;
  1399. valueIndex++;
  1400. }
  1401. // Make the unresolvedCount zero-based again.
  1402. unresolvedCount -= 2;
  1403. if (unresolvedCount === 0) {
  1404. resolve(resolvedValues);
  1405. }
  1406. return promise;
  1407. }
  1408. constructor(executor) {
  1409. const promise = this;
  1410. if (!(promise instanceof ZoneAwarePromise)) {
  1411. throw new Error('Must be an instanceof Promise.');
  1412. }
  1413. promise[symbolState] = UNRESOLVED;
  1414. promise[symbolValue] = []; // queue;
  1415. try {
  1416. const onceWrapper = once();
  1417. executor &&
  1418. executor(onceWrapper(makeResolver(promise, RESOLVED)), onceWrapper(makeResolver(promise, REJECTED)));
  1419. }
  1420. catch (error) {
  1421. resolvePromise(promise, false, error);
  1422. }
  1423. }
  1424. get [Symbol.toStringTag]() {
  1425. return 'Promise';
  1426. }
  1427. get [Symbol.species]() {
  1428. return ZoneAwarePromise;
  1429. }
  1430. then(onFulfilled, onRejected) {
  1431. // We must read `Symbol.species` safely because `this` may be anything. For instance, `this`
  1432. // may be an object without a prototype (created through `Object.create(null)`); thus
  1433. // `this.constructor` will be undefined. One of the use cases is SystemJS creating
  1434. // prototype-less objects (modules) via `Object.create(null)`. The SystemJS creates an empty
  1435. // object and copies promise properties into that object (within the `getOrCreateLoad`
  1436. // function). The zone.js then checks if the resolved value has the `then` method and
  1437. // invokes it with the `value` context. Otherwise, this will throw an error: `TypeError:
  1438. // Cannot read properties of undefined (reading 'Symbol(Symbol.species)')`.
  1439. let C = this.constructor?.[Symbol.species];
  1440. if (!C || typeof C !== 'function') {
  1441. C = this.constructor || ZoneAwarePromise;
  1442. }
  1443. const chainPromise = new C(noop);
  1444. const zone = Zone.current;
  1445. if (this[symbolState] == UNRESOLVED) {
  1446. this[symbolValue].push(zone, chainPromise, onFulfilled, onRejected);
  1447. }
  1448. else {
  1449. scheduleResolveOrReject(this, zone, chainPromise, onFulfilled, onRejected);
  1450. }
  1451. return chainPromise;
  1452. }
  1453. catch(onRejected) {
  1454. return this.then(null, onRejected);
  1455. }
  1456. finally(onFinally) {
  1457. // See comment on the call to `then` about why thee `Symbol.species` is safely accessed.
  1458. let C = this.constructor?.[Symbol.species];
  1459. if (!C || typeof C !== 'function') {
  1460. C = ZoneAwarePromise;
  1461. }
  1462. const chainPromise = new C(noop);
  1463. chainPromise[symbolFinally] = symbolFinally;
  1464. const zone = Zone.current;
  1465. if (this[symbolState] == UNRESOLVED) {
  1466. this[symbolValue].push(zone, chainPromise, onFinally, onFinally);
  1467. }
  1468. else {
  1469. scheduleResolveOrReject(this, zone, chainPromise, onFinally, onFinally);
  1470. }
  1471. return chainPromise;
  1472. }
  1473. }
  1474. // Protect against aggressive optimizers dropping seemingly unused properties.
  1475. // E.g. Closure Compiler in advanced mode.
  1476. ZoneAwarePromise['resolve'] = ZoneAwarePromise.resolve;
  1477. ZoneAwarePromise['reject'] = ZoneAwarePromise.reject;
  1478. ZoneAwarePromise['race'] = ZoneAwarePromise.race;
  1479. ZoneAwarePromise['all'] = ZoneAwarePromise.all;
  1480. const NativePromise = (global[symbolPromise] = global['Promise']);
  1481. global['Promise'] = ZoneAwarePromise;
  1482. const symbolThenPatched = __symbol__('thenPatched');
  1483. function patchThen(Ctor) {
  1484. const proto = Ctor.prototype;
  1485. const prop = ObjectGetOwnPropertyDescriptor(proto, 'then');
  1486. if (prop && (prop.writable === false || !prop.configurable)) {
  1487. // check Ctor.prototype.then propertyDescriptor is writable or not
  1488. // in meteor env, writable is false, we should ignore such case
  1489. return;
  1490. }
  1491. const originalThen = proto.then;
  1492. // Keep a reference to the original method.
  1493. proto[symbolThen] = originalThen;
  1494. Ctor.prototype.then = function (onResolve, onReject) {
  1495. const wrapped = new ZoneAwarePromise((resolve, reject) => {
  1496. originalThen.call(this, resolve, reject);
  1497. });
  1498. return wrapped.then(onResolve, onReject);
  1499. };
  1500. Ctor[symbolThenPatched] = true;
  1501. }
  1502. api.patchThen = patchThen;
  1503. function zoneify(fn) {
  1504. return function (self, args) {
  1505. let resultPromise = fn.apply(self, args);
  1506. if (resultPromise instanceof ZoneAwarePromise) {
  1507. return resultPromise;
  1508. }
  1509. let ctor = resultPromise.constructor;
  1510. if (!ctor[symbolThenPatched]) {
  1511. patchThen(ctor);
  1512. }
  1513. return resultPromise;
  1514. };
  1515. }
  1516. if (NativePromise) {
  1517. patchThen(NativePromise);
  1518. patchMethod(global, 'fetch', (delegate) => zoneify(delegate));
  1519. }
  1520. // This is not part of public API, but it is useful for tests, so we expose it.
  1521. Promise[Zone.__symbol__('uncaughtPromiseErrors')] = _uncaughtPromiseErrors;
  1522. return ZoneAwarePromise;
  1523. });
  1524. }
  1525. function patchToString(Zone) {
  1526. // override Function.prototype.toString to make zone.js patched function
  1527. // look like native function
  1528. Zone.__load_patch('toString', (global) => {
  1529. // patch Func.prototype.toString to let them look like native
  1530. const originalFunctionToString = Function.prototype.toString;
  1531. const ORIGINAL_DELEGATE_SYMBOL = zoneSymbol('OriginalDelegate');
  1532. const PROMISE_SYMBOL = zoneSymbol('Promise');
  1533. const ERROR_SYMBOL = zoneSymbol('Error');
  1534. const newFunctionToString = function toString() {
  1535. if (typeof this === 'function') {
  1536. const originalDelegate = this[ORIGINAL_DELEGATE_SYMBOL];
  1537. if (originalDelegate) {
  1538. if (typeof originalDelegate === 'function') {
  1539. return originalFunctionToString.call(originalDelegate);
  1540. }
  1541. else {
  1542. return Object.prototype.toString.call(originalDelegate);
  1543. }
  1544. }
  1545. if (this === Promise) {
  1546. const nativePromise = global[PROMISE_SYMBOL];
  1547. if (nativePromise) {
  1548. return originalFunctionToString.call(nativePromise);
  1549. }
  1550. }
  1551. if (this === Error) {
  1552. const nativeError = global[ERROR_SYMBOL];
  1553. if (nativeError) {
  1554. return originalFunctionToString.call(nativeError);
  1555. }
  1556. }
  1557. }
  1558. return originalFunctionToString.call(this);
  1559. };
  1560. newFunctionToString[ORIGINAL_DELEGATE_SYMBOL] = originalFunctionToString;
  1561. Function.prototype.toString = newFunctionToString;
  1562. // patch Object.prototype.toString to let them look like native
  1563. const originalObjectToString = Object.prototype.toString;
  1564. const PROMISE_OBJECT_TO_STRING = '[object Promise]';
  1565. Object.prototype.toString = function () {
  1566. if (typeof Promise === 'function' && this instanceof Promise) {
  1567. return PROMISE_OBJECT_TO_STRING;
  1568. }
  1569. return originalObjectToString.call(this);
  1570. };
  1571. });
  1572. }
  1573. function loadZone() {
  1574. // if global['Zone'] already exists (maybe zone.js was already loaded or
  1575. // some other lib also registered a global object named Zone), we may need
  1576. // to throw an error, but sometimes user may not want this error.
  1577. // For example,
  1578. // we have two web pages, page1 includes zone.js, page2 doesn't.
  1579. // and the 1st time user load page1 and page2, everything work fine,
  1580. // but when user load page2 again, error occurs because global['Zone'] already exists.
  1581. // so we add a flag to let user choose whether to throw this error or not.
  1582. // By default, if existing Zone is from zone.js, we will not throw the error.
  1583. const global = globalThis;
  1584. const checkDuplicate = global[__symbol__('forceDuplicateZoneCheck')] === true;
  1585. if (global['Zone'] && (checkDuplicate || typeof global['Zone'].__symbol__ !== 'function')) {
  1586. throw new Error('Zone already loaded.');
  1587. }
  1588. // Initialize global `Zone` constant.
  1589. global['Zone'] ??= initZone();
  1590. return global['Zone'];
  1591. }
  1592. /**
  1593. * @fileoverview
  1594. * @suppress {missingRequire}
  1595. */
  1596. // an identifier to tell ZoneTask do not create a new invoke closure
  1597. const OPTIMIZED_ZONE_EVENT_TASK_DATA = {
  1598. useG: true,
  1599. };
  1600. const zoneSymbolEventNames = {};
  1601. const globalSources = {};
  1602. const EVENT_NAME_SYMBOL_REGX = new RegExp('^' + ZONE_SYMBOL_PREFIX + '(\\w+)(true|false)$');
  1603. const IMMEDIATE_PROPAGATION_SYMBOL = zoneSymbol('propagationStopped');
  1604. function prepareEventNames(eventName, eventNameToString) {
  1605. const falseEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + FALSE_STR;
  1606. const trueEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + TRUE_STR;
  1607. const symbol = ZONE_SYMBOL_PREFIX + falseEventName;
  1608. const symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
  1609. zoneSymbolEventNames[eventName] = {};
  1610. zoneSymbolEventNames[eventName][FALSE_STR] = symbol;
  1611. zoneSymbolEventNames[eventName][TRUE_STR] = symbolCapture;
  1612. }
  1613. function patchEventTarget(_global, api, apis, patchOptions) {
  1614. const ADD_EVENT_LISTENER = (patchOptions && patchOptions.add) || ADD_EVENT_LISTENER_STR;
  1615. const REMOVE_EVENT_LISTENER = (patchOptions && patchOptions.rm) || REMOVE_EVENT_LISTENER_STR;
  1616. const LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.listeners) || 'eventListeners';
  1617. const REMOVE_ALL_LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.rmAll) || 'removeAllListeners';
  1618. const zoneSymbolAddEventListener = zoneSymbol(ADD_EVENT_LISTENER);
  1619. const ADD_EVENT_LISTENER_SOURCE = '.' + ADD_EVENT_LISTENER + ':';
  1620. const PREPEND_EVENT_LISTENER = 'prependListener';
  1621. const PREPEND_EVENT_LISTENER_SOURCE = '.' + PREPEND_EVENT_LISTENER + ':';
  1622. const invokeTask = function (task, target, event) {
  1623. // for better performance, check isRemoved which is set
  1624. // by removeEventListener
  1625. if (task.isRemoved) {
  1626. return;
  1627. }
  1628. const delegate = task.callback;
  1629. if (typeof delegate === 'object' && delegate.handleEvent) {
  1630. // create the bind version of handleEvent when invoke
  1631. task.callback = (event) => delegate.handleEvent(event);
  1632. task.originalDelegate = delegate;
  1633. }
  1634. // invoke static task.invoke
  1635. // need to try/catch error here, otherwise, the error in one event listener
  1636. // will break the executions of the other event listeners. Also error will
  1637. // not remove the event listener when `once` options is true.
  1638. let error;
  1639. try {
  1640. task.invoke(task, target, [event]);
  1641. }
  1642. catch (err) {
  1643. error = err;
  1644. }
  1645. const options = task.options;
  1646. if (options && typeof options === 'object' && options.once) {
  1647. // if options.once is true, after invoke once remove listener here
  1648. // only browser need to do this, nodejs eventEmitter will cal removeListener
  1649. // inside EventEmitter.once
  1650. const delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  1651. target[REMOVE_EVENT_LISTENER].call(target, event.type, delegate, options);
  1652. }
  1653. return error;
  1654. };
  1655. function globalCallback(context, event, isCapture) {
  1656. // https://github.com/angular/zone.js/issues/911, in IE, sometimes
  1657. // event will be undefined, so we need to use window.event
  1658. event = event || _global.event;
  1659. if (!event) {
  1660. return;
  1661. }
  1662. // event.target is needed for Samsung TV and SourceBuffer
  1663. // || global is needed https://github.com/angular/zone.js/issues/190
  1664. const target = context || event.target || _global;
  1665. const tasks = target[zoneSymbolEventNames[event.type][isCapture ? TRUE_STR : FALSE_STR]];
  1666. if (tasks) {
  1667. const errors = [];
  1668. // invoke all tasks which attached to current target with given event.type and capture = false
  1669. // for performance concern, if task.length === 1, just invoke
  1670. if (tasks.length === 1) {
  1671. const err = invokeTask(tasks[0], target, event);
  1672. err && errors.push(err);
  1673. }
  1674. else {
  1675. // https://github.com/angular/zone.js/issues/836
  1676. // copy the tasks array before invoke, to avoid
  1677. // the callback will remove itself or other listener
  1678. const copyTasks = tasks.slice();
  1679. for (let i = 0; i < copyTasks.length; i++) {
  1680. if (event && event[IMMEDIATE_PROPAGATION_SYMBOL] === true) {
  1681. break;
  1682. }
  1683. const err = invokeTask(copyTasks[i], target, event);
  1684. err && errors.push(err);
  1685. }
  1686. }
  1687. // Since there is only one error, we don't need to schedule microTask
  1688. // to throw the error.
  1689. if (errors.length === 1) {
  1690. throw errors[0];
  1691. }
  1692. else {
  1693. for (let i = 0; i < errors.length; i++) {
  1694. const err = errors[i];
  1695. api.nativeScheduleMicroTask(() => {
  1696. throw err;
  1697. });
  1698. }
  1699. }
  1700. }
  1701. }
  1702. // global shared zoneAwareCallback to handle all event callback with capture = false
  1703. const globalZoneAwareCallback = function (event) {
  1704. return globalCallback(this, event, false);
  1705. };
  1706. // global shared zoneAwareCallback to handle all event callback with capture = true
  1707. const globalZoneAwareCaptureCallback = function (event) {
  1708. return globalCallback(this, event, true);
  1709. };
  1710. function patchEventTargetMethods(obj, patchOptions) {
  1711. if (!obj) {
  1712. return false;
  1713. }
  1714. let useGlobalCallback = true;
  1715. if (patchOptions && patchOptions.useG !== undefined) {
  1716. useGlobalCallback = patchOptions.useG;
  1717. }
  1718. const validateHandler = patchOptions && patchOptions.vh;
  1719. let checkDuplicate = true;
  1720. if (patchOptions && patchOptions.chkDup !== undefined) {
  1721. checkDuplicate = patchOptions.chkDup;
  1722. }
  1723. let returnTarget = false;
  1724. if (patchOptions && patchOptions.rt !== undefined) {
  1725. returnTarget = patchOptions.rt;
  1726. }
  1727. let proto = obj;
  1728. while (proto && !proto.hasOwnProperty(ADD_EVENT_LISTENER)) {
  1729. proto = ObjectGetPrototypeOf(proto);
  1730. }
  1731. if (!proto && obj[ADD_EVENT_LISTENER]) {
  1732. // somehow we did not find it, but we can see it. This happens on IE for Window properties.
  1733. proto = obj;
  1734. }
  1735. if (!proto) {
  1736. return false;
  1737. }
  1738. if (proto[zoneSymbolAddEventListener]) {
  1739. return false;
  1740. }
  1741. const eventNameToString = patchOptions && patchOptions.eventNameToString;
  1742. // We use a shared global `taskData` to pass data for `scheduleEventTask`,
  1743. // eliminating the need to create a new object solely for passing data.
  1744. // WARNING: This object has a static lifetime, meaning it is not created
  1745. // each time `addEventListener` is called. It is instantiated only once
  1746. // and captured by reference inside the `addEventListener` and
  1747. // `removeEventListener` functions. Do not add any new properties to this
  1748. // object, as doing so would necessitate maintaining the information
  1749. // between `addEventListener` calls.
  1750. const taskData = {};
  1751. const nativeAddEventListener = (proto[zoneSymbolAddEventListener] = proto[ADD_EVENT_LISTENER]);
  1752. const nativeRemoveEventListener = (proto[zoneSymbol(REMOVE_EVENT_LISTENER)] =
  1753. proto[REMOVE_EVENT_LISTENER]);
  1754. const nativeListeners = (proto[zoneSymbol(LISTENERS_EVENT_LISTENER)] =
  1755. proto[LISTENERS_EVENT_LISTENER]);
  1756. const nativeRemoveAllListeners = (proto[zoneSymbol(REMOVE_ALL_LISTENERS_EVENT_LISTENER)] =
  1757. proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER]);
  1758. let nativePrependEventListener;
  1759. if (patchOptions && patchOptions.prepend) {
  1760. nativePrependEventListener = proto[zoneSymbol(patchOptions.prepend)] =
  1761. proto[patchOptions.prepend];
  1762. }
  1763. /**
  1764. * This util function will build an option object with passive option
  1765. * to handle all possible input from the user.
  1766. */
  1767. function buildEventListenerOptions(options, passive) {
  1768. if (!passive) {
  1769. return options;
  1770. }
  1771. if (typeof options === 'boolean') {
  1772. return { capture: options, passive: true };
  1773. }
  1774. if (!options) {
  1775. return { passive: true };
  1776. }
  1777. if (typeof options === 'object' && options.passive !== false) {
  1778. return { ...options, passive: true };
  1779. }
  1780. return options;
  1781. }
  1782. const customScheduleGlobal = function (task) {
  1783. // if there is already a task for the eventName + capture,
  1784. // just return, because we use the shared globalZoneAwareCallback here.
  1785. if (taskData.isExisting) {
  1786. return;
  1787. }
  1788. return nativeAddEventListener.call(taskData.target, taskData.eventName, taskData.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, taskData.options);
  1789. };
  1790. /**
  1791. * In the context of events and listeners, this function will be
  1792. * called at the end by `cancelTask`, which, in turn, calls `task.cancelFn`.
  1793. * Cancelling a task is primarily used to remove event listeners from
  1794. * the task target.
  1795. */
  1796. const customCancelGlobal = function (task) {
  1797. // if task is not marked as isRemoved, this call is directly
  1798. // from Zone.prototype.cancelTask, we should remove the task
  1799. // from tasksList of target first
  1800. if (!task.isRemoved) {
  1801. const symbolEventNames = zoneSymbolEventNames[task.eventName];
  1802. let symbolEventName;
  1803. if (symbolEventNames) {
  1804. symbolEventName = symbolEventNames[task.capture ? TRUE_STR : FALSE_STR];
  1805. }
  1806. const existingTasks = symbolEventName && task.target[symbolEventName];
  1807. if (existingTasks) {
  1808. for (let i = 0; i < existingTasks.length; i++) {
  1809. const existingTask = existingTasks[i];
  1810. if (existingTask === task) {
  1811. existingTasks.splice(i, 1);
  1812. // set isRemoved to data for faster invokeTask check
  1813. task.isRemoved = true;
  1814. if (task.removeAbortListener) {
  1815. task.removeAbortListener();
  1816. task.removeAbortListener = null;
  1817. }
  1818. if (existingTasks.length === 0) {
  1819. // all tasks for the eventName + capture have gone,
  1820. // remove globalZoneAwareCallback and remove the task cache from target
  1821. task.allRemoved = true;
  1822. task.target[symbolEventName] = null;
  1823. }
  1824. break;
  1825. }
  1826. }
  1827. }
  1828. }
  1829. // if all tasks for the eventName + capture have gone,
  1830. // we will really remove the global event callback,
  1831. // if not, return
  1832. if (!task.allRemoved) {
  1833. return;
  1834. }
  1835. return nativeRemoveEventListener.call(task.target, task.eventName, task.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, task.options);
  1836. };
  1837. const customScheduleNonGlobal = function (task) {
  1838. return nativeAddEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
  1839. };
  1840. const customSchedulePrepend = function (task) {
  1841. return nativePrependEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
  1842. };
  1843. const customCancelNonGlobal = function (task) {
  1844. return nativeRemoveEventListener.call(task.target, task.eventName, task.invoke, task.options);
  1845. };
  1846. const customSchedule = useGlobalCallback ? customScheduleGlobal : customScheduleNonGlobal;
  1847. const customCancel = useGlobalCallback ? customCancelGlobal : customCancelNonGlobal;
  1848. const compareTaskCallbackVsDelegate = function (task, delegate) {
  1849. const typeOfDelegate = typeof delegate;
  1850. return ((typeOfDelegate === 'function' && task.callback === delegate) ||
  1851. (typeOfDelegate === 'object' && task.originalDelegate === delegate));
  1852. };
  1853. const compare = patchOptions?.diff || compareTaskCallbackVsDelegate;
  1854. const unpatchedEvents = Zone[zoneSymbol('UNPATCHED_EVENTS')];
  1855. const passiveEvents = _global[zoneSymbol('PASSIVE_EVENTS')];
  1856. function copyEventListenerOptions(options) {
  1857. if (typeof options === 'object' && options !== null) {
  1858. // We need to destructure the target `options` object since it may
  1859. // be frozen or sealed (possibly provided implicitly by a third-party
  1860. // library), or its properties may be readonly.
  1861. const newOptions = { ...options };
  1862. // The `signal` option was recently introduced, which caused regressions in
  1863. // third-party scenarios where `AbortController` was directly provided to
  1864. // `addEventListener` as options. For instance, in cases like
  1865. // `document.addEventListener('keydown', callback, abortControllerInstance)`,
  1866. // which is valid because `AbortController` includes a `signal` getter, spreading
  1867. // `{...options}` wouldn't copy the `signal`. Additionally, using `Object.create`
  1868. // isn't feasible since `AbortController` is a built-in object type, and attempting
  1869. // to create a new object directly with it as the prototype might result in
  1870. // unexpected behavior.
  1871. if (options.signal) {
  1872. newOptions.signal = options.signal;
  1873. }
  1874. return newOptions;
  1875. }
  1876. return options;
  1877. }
  1878. const makeAddListener = function (nativeListener, addSource, customScheduleFn, customCancelFn, returnTarget = false, prepend = false) {
  1879. return function () {
  1880. const target = this || _global;
  1881. let eventName = arguments[0];
  1882. if (patchOptions && patchOptions.transferEventName) {
  1883. eventName = patchOptions.transferEventName(eventName);
  1884. }
  1885. let delegate = arguments[1];
  1886. if (!delegate) {
  1887. return nativeListener.apply(this, arguments);
  1888. }
  1889. if (isNode && eventName === 'uncaughtException') {
  1890. // don't patch uncaughtException of nodejs to prevent endless loop
  1891. return nativeListener.apply(this, arguments);
  1892. }
  1893. // To improve `addEventListener` performance, we will create the callback
  1894. // for the task later when the task is invoked.
  1895. let isEventListenerObject = false;
  1896. if (typeof delegate !== 'function') {
  1897. // This checks whether the provided listener argument is an object with
  1898. // a `handleEvent` method (since we can call `addEventListener` with a
  1899. // function `event => ...` or with an object `{ handleEvent: event => ... }`).
  1900. if (!delegate.handleEvent) {
  1901. return nativeListener.apply(this, arguments);
  1902. }
  1903. isEventListenerObject = true;
  1904. }
  1905. if (validateHandler && !validateHandler(nativeListener, delegate, target, arguments)) {
  1906. return;
  1907. }
  1908. const passive = !!passiveEvents && passiveEvents.indexOf(eventName) !== -1;
  1909. const options = copyEventListenerOptions(buildEventListenerOptions(arguments[2], passive));
  1910. const signal = options?.signal;
  1911. if (signal?.aborted) {
  1912. // the signal is an aborted one, just return without attaching the event listener.
  1913. return;
  1914. }
  1915. if (unpatchedEvents) {
  1916. // check unpatched list
  1917. for (let i = 0; i < unpatchedEvents.length; i++) {
  1918. if (eventName === unpatchedEvents[i]) {
  1919. if (passive) {
  1920. return nativeListener.call(target, eventName, delegate, options);
  1921. }
  1922. else {
  1923. return nativeListener.apply(this, arguments);
  1924. }
  1925. }
  1926. }
  1927. }
  1928. const capture = !options ? false : typeof options === 'boolean' ? true : options.capture;
  1929. const once = options && typeof options === 'object' ? options.once : false;
  1930. const zone = Zone.current;
  1931. let symbolEventNames = zoneSymbolEventNames[eventName];
  1932. if (!symbolEventNames) {
  1933. prepareEventNames(eventName, eventNameToString);
  1934. symbolEventNames = zoneSymbolEventNames[eventName];
  1935. }
  1936. const symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
  1937. let existingTasks = target[symbolEventName];
  1938. let isExisting = false;
  1939. if (existingTasks) {
  1940. // already have task registered
  1941. isExisting = true;
  1942. if (checkDuplicate) {
  1943. for (let i = 0; i < existingTasks.length; i++) {
  1944. if (compare(existingTasks[i], delegate)) {
  1945. // same callback, same capture, same event name, just return
  1946. return;
  1947. }
  1948. }
  1949. }
  1950. }
  1951. else {
  1952. existingTasks = target[symbolEventName] = [];
  1953. }
  1954. let source;
  1955. const constructorName = target.constructor['name'];
  1956. const targetSource = globalSources[constructorName];
  1957. if (targetSource) {
  1958. source = targetSource[eventName];
  1959. }
  1960. if (!source) {
  1961. source =
  1962. constructorName +
  1963. addSource +
  1964. (eventNameToString ? eventNameToString(eventName) : eventName);
  1965. }
  1966. // In the code below, `options` should no longer be reassigned; instead, it
  1967. // should only be mutated. This is because we pass that object to the native
  1968. // `addEventListener`.
  1969. // It's generally recommended to use the same object reference for options.
  1970. // This ensures consistency and avoids potential issues.
  1971. taskData.options = options;
  1972. if (once) {
  1973. // When using `addEventListener` with the `once` option, we don't pass
  1974. // the `once` option directly to the native `addEventListener` method.
  1975. // Instead, we keep the `once` setting and handle it ourselves.
  1976. taskData.options.once = false;
  1977. }
  1978. taskData.target = target;
  1979. taskData.capture = capture;
  1980. taskData.eventName = eventName;
  1981. taskData.isExisting = isExisting;
  1982. const data = useGlobalCallback ? OPTIMIZED_ZONE_EVENT_TASK_DATA : undefined;
  1983. // keep taskData into data to allow onScheduleEventTask to access the task information
  1984. if (data) {
  1985. data.taskData = taskData;
  1986. }
  1987. if (signal) {
  1988. // When using `addEventListener` with the `signal` option, we don't pass
  1989. // the `signal` option directly to the native `addEventListener` method.
  1990. // Instead, we keep the `signal` setting and handle it ourselves.
  1991. taskData.options.signal = undefined;
  1992. }
  1993. // The `scheduleEventTask` function will ultimately call `customScheduleGlobal`,
  1994. // which in turn calls the native `addEventListener`. This is why `taskData.options`
  1995. // is updated before scheduling the task, as `customScheduleGlobal` uses
  1996. // `taskData.options` to pass it to the native `addEventListener`.
  1997. const task = zone.scheduleEventTask(source, delegate, data, customScheduleFn, customCancelFn);
  1998. if (signal) {
  1999. // after task is scheduled, we need to store the signal back to task.options
  2000. taskData.options.signal = signal;
  2001. // Wrapping `task` in a weak reference would not prevent memory leaks. Weak references are
  2002. // primarily used for preventing strong references cycles. `onAbort` is always reachable
  2003. // as it's an event listener, so its closure retains a strong reference to the `task`.
  2004. const onAbort = () => task.zone.cancelTask(task);
  2005. nativeListener.call(signal, 'abort', onAbort, { once: true });
  2006. // We need to remove the `abort` listener when the event listener is going to be removed,
  2007. // as it creates a closure that captures `task`. This closure retains a reference to the
  2008. // `task` object even after it goes out of scope, preventing `task` from being garbage
  2009. // collected.
  2010. task.removeAbortListener = () => signal.removeEventListener('abort', onAbort);
  2011. }
  2012. // should clear taskData.target to avoid memory leak
  2013. // issue, https://github.com/angular/angular/issues/20442
  2014. taskData.target = null;
  2015. // need to clear up taskData because it is a global object
  2016. if (data) {
  2017. data.taskData = null;
  2018. }
  2019. // have to save those information to task in case
  2020. // application may call task.zone.cancelTask() directly
  2021. if (once) {
  2022. taskData.options.once = true;
  2023. }
  2024. if (typeof task.options !== 'boolean') {
  2025. // We should save the options on the task (if it's an object) because
  2026. // we'll be using `task.options` later when removing the event listener
  2027. // and passing it back to `removeEventListener`.
  2028. task.options = options;
  2029. }
  2030. task.target = target;
  2031. task.capture = capture;
  2032. task.eventName = eventName;
  2033. if (isEventListenerObject) {
  2034. // save original delegate for compare to check duplicate
  2035. task.originalDelegate = delegate;
  2036. }
  2037. if (!prepend) {
  2038. existingTasks.push(task);
  2039. }
  2040. else {
  2041. existingTasks.unshift(task);
  2042. }
  2043. if (returnTarget) {
  2044. return target;
  2045. }
  2046. };
  2047. };
  2048. proto[ADD_EVENT_LISTENER] = makeAddListener(nativeAddEventListener, ADD_EVENT_LISTENER_SOURCE, customSchedule, customCancel, returnTarget);
  2049. if (nativePrependEventListener) {
  2050. proto[PREPEND_EVENT_LISTENER] = makeAddListener(nativePrependEventListener, PREPEND_EVENT_LISTENER_SOURCE, customSchedulePrepend, customCancel, returnTarget, true);
  2051. }
  2052. proto[REMOVE_EVENT_LISTENER] = function () {
  2053. const target = this || _global;
  2054. let eventName = arguments[0];
  2055. if (patchOptions && patchOptions.transferEventName) {
  2056. eventName = patchOptions.transferEventName(eventName);
  2057. }
  2058. const options = arguments[2];
  2059. const capture = !options ? false : typeof options === 'boolean' ? true : options.capture;
  2060. const delegate = arguments[1];
  2061. if (!delegate) {
  2062. return nativeRemoveEventListener.apply(this, arguments);
  2063. }
  2064. if (validateHandler &&
  2065. !validateHandler(nativeRemoveEventListener, delegate, target, arguments)) {
  2066. return;
  2067. }
  2068. const symbolEventNames = zoneSymbolEventNames[eventName];
  2069. let symbolEventName;
  2070. if (symbolEventNames) {
  2071. symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
  2072. }
  2073. const existingTasks = symbolEventName && target[symbolEventName];
  2074. // `existingTasks` may not exist if the `addEventListener` was called before
  2075. // it was patched by zone.js. Please refer to the attached issue for
  2076. // clarification, particularly after the `if` condition, before calling
  2077. // the native `removeEventListener`.
  2078. if (existingTasks) {
  2079. for (let i = 0; i < existingTasks.length; i++) {
  2080. const existingTask = existingTasks[i];
  2081. if (compare(existingTask, delegate)) {
  2082. existingTasks.splice(i, 1);
  2083. // set isRemoved to data for faster invokeTask check
  2084. existingTask.isRemoved = true;
  2085. if (existingTasks.length === 0) {
  2086. // all tasks for the eventName + capture have gone,
  2087. // remove globalZoneAwareCallback and remove the task cache from target
  2088. existingTask.allRemoved = true;
  2089. target[symbolEventName] = null;
  2090. // in the target, we have an event listener which is added by on_property
  2091. // such as target.onclick = function() {}, so we need to clear this internal
  2092. // property too if all delegates with capture=false were removed
  2093. // https:// github.com/angular/angular/issues/31643
  2094. // https://github.com/angular/angular/issues/54581
  2095. if (!capture && typeof eventName === 'string') {
  2096. const onPropertySymbol = ZONE_SYMBOL_PREFIX + 'ON_PROPERTY' + eventName;
  2097. target[onPropertySymbol] = null;
  2098. }
  2099. }
  2100. // In all other conditions, when `addEventListener` is called after being
  2101. // patched by zone.js, we would always find an event task on the `EventTarget`.
  2102. // This will trigger `cancelFn` on the `existingTask`, leading to `customCancelGlobal`,
  2103. // which ultimately removes an event listener and cleans up the abort listener
  2104. // (if an `AbortSignal` was provided when scheduling a task).
  2105. existingTask.zone.cancelTask(existingTask);
  2106. if (returnTarget) {
  2107. return target;
  2108. }
  2109. return;
  2110. }
  2111. }
  2112. }
  2113. // https://github.com/angular/zone.js/issues/930
  2114. // We may encounter a situation where the `addEventListener` was
  2115. // called on the event target before zone.js is loaded, resulting
  2116. // in no task being stored on the event target due to its invocation
  2117. // of the native implementation. In this scenario, we simply need to
  2118. // invoke the native `removeEventListener`.
  2119. return nativeRemoveEventListener.apply(this, arguments);
  2120. };
  2121. proto[LISTENERS_EVENT_LISTENER] = function () {
  2122. const target = this || _global;
  2123. let eventName = arguments[0];
  2124. if (patchOptions && patchOptions.transferEventName) {
  2125. eventName = patchOptions.transferEventName(eventName);
  2126. }
  2127. const listeners = [];
  2128. const tasks = findEventTasks(target, eventNameToString ? eventNameToString(eventName) : eventName);
  2129. for (let i = 0; i < tasks.length; i++) {
  2130. const task = tasks[i];
  2131. let delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  2132. listeners.push(delegate);
  2133. }
  2134. return listeners;
  2135. };
  2136. proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER] = function () {
  2137. const target = this || _global;
  2138. let eventName = arguments[0];
  2139. if (!eventName) {
  2140. const keys = Object.keys(target);
  2141. for (let i = 0; i < keys.length; i++) {
  2142. const prop = keys[i];
  2143. const match = EVENT_NAME_SYMBOL_REGX.exec(prop);
  2144. let evtName = match && match[1];
  2145. // in nodejs EventEmitter, removeListener event is
  2146. // used for monitoring the removeListener call,
  2147. // so just keep removeListener eventListener until
  2148. // all other eventListeners are removed
  2149. if (evtName && evtName !== 'removeListener') {
  2150. this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, evtName);
  2151. }
  2152. }
  2153. // remove removeListener listener finally
  2154. this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, 'removeListener');
  2155. }
  2156. else {
  2157. if (patchOptions && patchOptions.transferEventName) {
  2158. eventName = patchOptions.transferEventName(eventName);
  2159. }
  2160. const symbolEventNames = zoneSymbolEventNames[eventName];
  2161. if (symbolEventNames) {
  2162. const symbolEventName = symbolEventNames[FALSE_STR];
  2163. const symbolCaptureEventName = symbolEventNames[TRUE_STR];
  2164. const tasks = target[symbolEventName];
  2165. const captureTasks = target[symbolCaptureEventName];
  2166. if (tasks) {
  2167. const removeTasks = tasks.slice();
  2168. for (let i = 0; i < removeTasks.length; i++) {
  2169. const task = removeTasks[i];
  2170. let delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  2171. this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
  2172. }
  2173. }
  2174. if (captureTasks) {
  2175. const removeTasks = captureTasks.slice();
  2176. for (let i = 0; i < removeTasks.length; i++) {
  2177. const task = removeTasks[i];
  2178. let delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  2179. this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
  2180. }
  2181. }
  2182. }
  2183. }
  2184. if (returnTarget) {
  2185. return this;
  2186. }
  2187. };
  2188. // for native toString patch
  2189. attachOriginToPatched(proto[ADD_EVENT_LISTENER], nativeAddEventListener);
  2190. attachOriginToPatched(proto[REMOVE_EVENT_LISTENER], nativeRemoveEventListener);
  2191. if (nativeRemoveAllListeners) {
  2192. attachOriginToPatched(proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER], nativeRemoveAllListeners);
  2193. }
  2194. if (nativeListeners) {
  2195. attachOriginToPatched(proto[LISTENERS_EVENT_LISTENER], nativeListeners);
  2196. }
  2197. return true;
  2198. }
  2199. let results = [];
  2200. for (let i = 0; i < apis.length; i++) {
  2201. results[i] = patchEventTargetMethods(apis[i], patchOptions);
  2202. }
  2203. return results;
  2204. }
  2205. function findEventTasks(target, eventName) {
  2206. if (!eventName) {
  2207. const foundTasks = [];
  2208. for (let prop in target) {
  2209. const match = EVENT_NAME_SYMBOL_REGX.exec(prop);
  2210. let evtName = match && match[1];
  2211. if (evtName && (!eventName || evtName === eventName)) {
  2212. const tasks = target[prop];
  2213. if (tasks) {
  2214. for (let i = 0; i < tasks.length; i++) {
  2215. foundTasks.push(tasks[i]);
  2216. }
  2217. }
  2218. }
  2219. }
  2220. return foundTasks;
  2221. }
  2222. let symbolEventName = zoneSymbolEventNames[eventName];
  2223. if (!symbolEventName) {
  2224. prepareEventNames(eventName);
  2225. symbolEventName = zoneSymbolEventNames[eventName];
  2226. }
  2227. const captureFalseTasks = target[symbolEventName[FALSE_STR]];
  2228. const captureTrueTasks = target[symbolEventName[TRUE_STR]];
  2229. if (!captureFalseTasks) {
  2230. return captureTrueTasks ? captureTrueTasks.slice() : [];
  2231. }
  2232. else {
  2233. return captureTrueTasks
  2234. ? captureFalseTasks.concat(captureTrueTasks)
  2235. : captureFalseTasks.slice();
  2236. }
  2237. }
  2238. /**
  2239. * @fileoverview
  2240. * @suppress {missingRequire}
  2241. */
  2242. function patchQueueMicrotask(global, api) {
  2243. api.patchMethod(global, 'queueMicrotask', (delegate) => {
  2244. return function (self, args) {
  2245. Zone.current.scheduleMicroTask('queueMicrotask', args[0]);
  2246. };
  2247. });
  2248. }
  2249. /**
  2250. * @fileoverview
  2251. * @suppress {missingRequire}
  2252. */
  2253. const taskSymbol = zoneSymbol('zoneTask');
  2254. function patchTimer(window, setName, cancelName, nameSuffix) {
  2255. let setNative = null;
  2256. let clearNative = null;
  2257. setName += nameSuffix;
  2258. cancelName += nameSuffix;
  2259. const tasksByHandleId = {};
  2260. function scheduleTask(task) {
  2261. const data = task.data;
  2262. data.args[0] = function () {
  2263. return task.invoke.apply(this, arguments);
  2264. };
  2265. const handleOrId = setNative.apply(window, data.args);
  2266. // Whlist on Node.js when get can the ID by using `[Symbol.toPrimitive]()` we do
  2267. // to this so that we do not cause potentally leaks when using `setTimeout`
  2268. // since this can be periodic when using `.refresh`.
  2269. if (isNumber(handleOrId)) {
  2270. data.handleId = handleOrId;
  2271. }
  2272. else {
  2273. data.handle = handleOrId;
  2274. // On Node.js a timeout and interval can be restarted over and over again by using the `.refresh` method.
  2275. data.isRefreshable = isFunction(handleOrId.refresh);
  2276. }
  2277. return task;
  2278. }
  2279. function clearTask(task) {
  2280. const { handle, handleId } = task.data;
  2281. return clearNative.call(window, handle ?? handleId);
  2282. }
  2283. setNative = patchMethod(window, setName, (delegate) => function (self, args) {
  2284. if (isFunction(args[0])) {
  2285. const options = {
  2286. isRefreshable: false,
  2287. isPeriodic: nameSuffix === 'Interval',
  2288. delay: nameSuffix === 'Timeout' || nameSuffix === 'Interval' ? args[1] || 0 : undefined,
  2289. args: args,
  2290. };
  2291. const callback = args[0];
  2292. args[0] = function timer() {
  2293. try {
  2294. return callback.apply(this, arguments);
  2295. }
  2296. finally {
  2297. // issue-934, task will be cancelled
  2298. // even it is a periodic task such as
  2299. // setInterval
  2300. // https://github.com/angular/angular/issues/40387
  2301. // Cleanup tasksByHandleId should be handled before scheduleTask
  2302. // Since some zoneSpec may intercept and doesn't trigger
  2303. // scheduleFn(scheduleTask) provided here.
  2304. const { handle, handleId, isPeriodic, isRefreshable } = options;
  2305. if (!isPeriodic && !isRefreshable) {
  2306. if (handleId) {
  2307. // in non-nodejs env, we remove timerId
  2308. // from local cache
  2309. delete tasksByHandleId[handleId];
  2310. }
  2311. else if (handle) {
  2312. // Node returns complex objects as handleIds
  2313. // we remove task reference from timer object
  2314. handle[taskSymbol] = null;
  2315. }
  2316. }
  2317. }
  2318. };
  2319. const task = scheduleMacroTaskWithCurrentZone(setName, args[0], options, scheduleTask, clearTask);
  2320. if (!task) {
  2321. return task;
  2322. }
  2323. // Node.js must additionally support the ref and unref functions.
  2324. const { handleId, handle, isRefreshable, isPeriodic } = task.data;
  2325. if (handleId) {
  2326. // for non nodejs env, we save handleId: task
  2327. // mapping in local cache for clearTimeout
  2328. tasksByHandleId[handleId] = task;
  2329. }
  2330. else if (handle) {
  2331. // for nodejs env, we save task
  2332. // reference in timerId Object for clearTimeout
  2333. handle[taskSymbol] = task;
  2334. if (isRefreshable && !isPeriodic) {
  2335. const originalRefresh = handle.refresh;
  2336. handle.refresh = function () {
  2337. const { zone, state } = task;
  2338. if (state === 'notScheduled') {
  2339. task._state = 'scheduled';
  2340. zone._updateTaskCount(task, 1);
  2341. }
  2342. else if (state === 'running') {
  2343. task._state = 'scheduling';
  2344. }
  2345. return originalRefresh.call(this);
  2346. };
  2347. }
  2348. }
  2349. return handle ?? handleId ?? task;
  2350. }
  2351. else {
  2352. // cause an error by calling it directly.
  2353. return delegate.apply(window, args);
  2354. }
  2355. });
  2356. clearNative = patchMethod(window, cancelName, (delegate) => function (self, args) {
  2357. const id = args[0];
  2358. let task;
  2359. if (isNumber(id)) {
  2360. // non nodejs env.
  2361. task = tasksByHandleId[id];
  2362. delete tasksByHandleId[id];
  2363. }
  2364. else {
  2365. // nodejs env ?? other environments.
  2366. task = id?.[taskSymbol];
  2367. if (task) {
  2368. id[taskSymbol] = null;
  2369. }
  2370. else {
  2371. task = id;
  2372. }
  2373. }
  2374. if (task?.type) {
  2375. if (task.cancelFn) {
  2376. // Do not cancel already canceled functions
  2377. task.zone.cancelTask(task);
  2378. }
  2379. }
  2380. else {
  2381. // cause an error by calling it directly.
  2382. delegate.apply(window, args);
  2383. }
  2384. });
  2385. }
  2386. function patchEvents(Zone) {
  2387. Zone.__load_patch('EventEmitter', (global, Zone, api) => {
  2388. // For EventEmitter
  2389. const EE_ADD_LISTENER = 'addListener';
  2390. const EE_PREPEND_LISTENER = 'prependListener';
  2391. const EE_REMOVE_LISTENER = 'removeListener';
  2392. const EE_REMOVE_ALL_LISTENER = 'removeAllListeners';
  2393. const EE_LISTENERS = 'listeners';
  2394. const EE_ON = 'on';
  2395. const EE_OFF = 'off';
  2396. const compareTaskCallbackVsDelegate = function (task, delegate) {
  2397. // same callback, same capture, same event name, just return
  2398. return task.callback === delegate || task.callback.listener === delegate;
  2399. };
  2400. const eventNameToString = function (eventName) {
  2401. if (typeof eventName === 'string') {
  2402. return eventName;
  2403. }
  2404. if (!eventName) {
  2405. return '';
  2406. }
  2407. return eventName.toString().replace('(', '_').replace(')', '_');
  2408. };
  2409. function patchEventEmitterMethods(obj) {
  2410. const result = patchEventTarget(global, api, [obj], {
  2411. useG: false,
  2412. add: EE_ADD_LISTENER,
  2413. rm: EE_REMOVE_LISTENER,
  2414. prepend: EE_PREPEND_LISTENER,
  2415. rmAll: EE_REMOVE_ALL_LISTENER,
  2416. listeners: EE_LISTENERS,
  2417. chkDup: false,
  2418. rt: true,
  2419. diff: compareTaskCallbackVsDelegate,
  2420. eventNameToString: eventNameToString,
  2421. });
  2422. if (result && result[0]) {
  2423. obj[EE_ON] = obj[EE_ADD_LISTENER];
  2424. obj[EE_OFF] = obj[EE_REMOVE_LISTENER];
  2425. }
  2426. }
  2427. // EventEmitter
  2428. let events;
  2429. try {
  2430. events = require('events');
  2431. }
  2432. catch (err) { }
  2433. if (events && events.EventEmitter) {
  2434. patchEventEmitterMethods(events.EventEmitter.prototype);
  2435. }
  2436. });
  2437. }
  2438. function patchFs(Zone) {
  2439. Zone.__load_patch('fs', (global, Zone, api) => {
  2440. let fs;
  2441. try {
  2442. fs = require('fs');
  2443. }
  2444. catch (err) { }
  2445. if (!fs)
  2446. return;
  2447. // watch, watchFile, unwatchFile has been patched
  2448. // because EventEmitter has been patched
  2449. const TO_PATCH_MACROTASK_METHODS = [
  2450. 'access',
  2451. 'appendFile',
  2452. 'chmod',
  2453. 'chown',
  2454. 'close',
  2455. 'exists',
  2456. 'fchmod',
  2457. 'fchown',
  2458. 'fdatasync',
  2459. 'fstat',
  2460. 'fsync',
  2461. 'ftruncate',
  2462. 'futimes',
  2463. 'lchmod',
  2464. 'lchown',
  2465. 'lutimes',
  2466. 'link',
  2467. 'lstat',
  2468. 'mkdir',
  2469. 'mkdtemp',
  2470. 'open',
  2471. 'opendir',
  2472. 'read',
  2473. 'readdir',
  2474. 'readFile',
  2475. 'readlink',
  2476. 'realpath',
  2477. 'rename',
  2478. 'rmdir',
  2479. 'stat',
  2480. 'symlink',
  2481. 'truncate',
  2482. 'unlink',
  2483. 'utimes',
  2484. 'write',
  2485. 'writeFile',
  2486. 'writev',
  2487. ];
  2488. TO_PATCH_MACROTASK_METHODS.filter((name) => !!fs[name] && typeof fs[name] === 'function').forEach((name) => {
  2489. patchMacroTask(fs, name, (self, args) => {
  2490. return {
  2491. name: 'fs.' + name,
  2492. args: args,
  2493. cbIdx: args.length > 0 ? args.length - 1 : -1,
  2494. target: self,
  2495. };
  2496. });
  2497. });
  2498. const realpathOriginalDelegate = fs.realpath?.[api.symbol('OriginalDelegate')];
  2499. // This is the only specific method that should be additionally patched because the previous
  2500. // `patchMacroTask` has overridden the `realpath` function and its `native` property.
  2501. if (realpathOriginalDelegate?.native) {
  2502. fs.realpath.native = realpathOriginalDelegate.native;
  2503. patchMacroTask(fs.realpath, 'native', (self, args) => ({
  2504. args,
  2505. target: self,
  2506. cbIdx: args.length > 0 ? args.length - 1 : -1,
  2507. name: 'fs.realpath.native',
  2508. }));
  2509. }
  2510. });
  2511. }
  2512. function patchNodeUtil(Zone) {
  2513. Zone.__load_patch('node_util', (global, Zone, api) => {
  2514. api.patchOnProperties = patchOnProperties;
  2515. api.patchMethod = patchMethod;
  2516. api.bindArguments = bindArguments;
  2517. api.patchMacroTask = patchMacroTask;
  2518. setShouldCopySymbolProperties(true);
  2519. });
  2520. }
  2521. const set = 'set';
  2522. const clear = 'clear';
  2523. function patchNode(Zone) {
  2524. patchNodeUtil(Zone);
  2525. patchEvents(Zone);
  2526. patchFs(Zone);
  2527. Zone.__load_patch('node_timers', (global, Zone) => {
  2528. // Timers
  2529. let globalUseTimeoutFromTimer = false;
  2530. try {
  2531. const timers = require('timers');
  2532. let globalEqualTimersTimeout = global.setTimeout === timers.setTimeout;
  2533. if (!globalEqualTimersTimeout && !isMix) {
  2534. // 1. if isMix, then we are in mix environment such as Electron
  2535. // we should only patch timers.setTimeout because global.setTimeout
  2536. // have been patched
  2537. // 2. if global.setTimeout not equal timers.setTimeout, check
  2538. // whether global.setTimeout use timers.setTimeout or not
  2539. const originSetTimeout = timers.setTimeout;
  2540. timers.setTimeout = function () {
  2541. globalUseTimeoutFromTimer = true;
  2542. return originSetTimeout.apply(this, arguments);
  2543. };
  2544. const detectTimeout = global.setTimeout(() => { }, 100);
  2545. clearTimeout(detectTimeout);
  2546. timers.setTimeout = originSetTimeout;
  2547. }
  2548. patchTimer(timers, set, clear, 'Timeout');
  2549. patchTimer(timers, set, clear, 'Interval');
  2550. patchTimer(timers, set, clear, 'Immediate');
  2551. }
  2552. catch (error) {
  2553. // timers module not exists, for example, when we using nativeScript
  2554. // timers is not available
  2555. }
  2556. if (isMix) {
  2557. // if we are in mix environment, such as Electron,
  2558. // the global.setTimeout has already been patched,
  2559. // so we just patch timers.setTimeout
  2560. return;
  2561. }
  2562. if (!globalUseTimeoutFromTimer) {
  2563. // 1. global setTimeout equals timers setTimeout
  2564. // 2. or global don't use timers setTimeout(maybe some other library patch setTimeout)
  2565. // 3. or load timers module error happens, we should patch global setTimeout
  2566. patchTimer(global, set, clear, 'Timeout');
  2567. patchTimer(global, set, clear, 'Interval');
  2568. patchTimer(global, set, clear, 'Immediate');
  2569. }
  2570. else {
  2571. // global use timers setTimeout, but not equals
  2572. // this happens when use nodejs v0.10.x, global setTimeout will
  2573. // use a lazy load version of timers setTimeout
  2574. // we should not double patch timer's setTimeout
  2575. // so we only store the __symbol__ for consistency
  2576. global[Zone.__symbol__('setTimeout')] = global.setTimeout;
  2577. global[Zone.__symbol__('setInterval')] = global.setInterval;
  2578. global[Zone.__symbol__('setImmediate')] = global.setImmediate;
  2579. }
  2580. });
  2581. // patch process related methods
  2582. Zone.__load_patch('nextTick', () => {
  2583. // patch nextTick as microTask
  2584. patchMicroTask(process, 'nextTick', (self, args) => {
  2585. return {
  2586. name: 'process.nextTick',
  2587. args: args,
  2588. cbIdx: args.length > 0 && typeof args[0] === 'function' ? 0 : -1,
  2589. target: process,
  2590. };
  2591. });
  2592. });
  2593. Zone.__load_patch('handleUnhandledPromiseRejection', (global, Zone, api) => {
  2594. Zone[api.symbol('unhandledPromiseRejectionHandler')] =
  2595. findProcessPromiseRejectionHandler('unhandledRejection');
  2596. Zone[api.symbol('rejectionHandledHandler')] =
  2597. findProcessPromiseRejectionHandler('rejectionHandled');
  2598. // handle unhandled promise rejection
  2599. function findProcessPromiseRejectionHandler(evtName) {
  2600. return function (e) {
  2601. const eventTasks = findEventTasks(process, evtName);
  2602. eventTasks.forEach((eventTask) => {
  2603. // process has added unhandledrejection event listener
  2604. // trigger the event listener
  2605. if (evtName === 'unhandledRejection') {
  2606. eventTask.invoke(e.rejection, e.promise);
  2607. }
  2608. else if (evtName === 'rejectionHandled') {
  2609. eventTask.invoke(e.promise);
  2610. }
  2611. });
  2612. };
  2613. }
  2614. });
  2615. // Crypto
  2616. Zone.__load_patch('crypto', () => {
  2617. let crypto;
  2618. try {
  2619. crypto = require('crypto');
  2620. }
  2621. catch (err) { }
  2622. // use the generic patchMacroTask to patch crypto
  2623. if (crypto) {
  2624. const methodNames = ['randomBytes', 'pbkdf2'];
  2625. methodNames.forEach((name) => {
  2626. patchMacroTask(crypto, name, (self, args) => {
  2627. return {
  2628. name: 'crypto.' + name,
  2629. args: args,
  2630. cbIdx: args.length > 0 && typeof args[args.length - 1] === 'function' ? args.length - 1 : -1,
  2631. target: crypto,
  2632. };
  2633. });
  2634. });
  2635. }
  2636. });
  2637. Zone.__load_patch('console', (global, Zone) => {
  2638. const consoleMethods = [
  2639. 'dir',
  2640. 'log',
  2641. 'info',
  2642. 'error',
  2643. 'warn',
  2644. 'assert',
  2645. 'debug',
  2646. 'timeEnd',
  2647. 'trace',
  2648. ];
  2649. consoleMethods.forEach((m) => {
  2650. const originalMethod = (console[Zone.__symbol__(m)] = console[m]);
  2651. if (originalMethod) {
  2652. console[m] = function () {
  2653. const args = ArraySlice.call(arguments);
  2654. if (Zone.current === Zone.root) {
  2655. return originalMethod.apply(this, args);
  2656. }
  2657. else {
  2658. return Zone.root.run(originalMethod, this, args);
  2659. }
  2660. };
  2661. }
  2662. });
  2663. });
  2664. Zone.__load_patch('queueMicrotask', (global, Zone, api) => {
  2665. patchQueueMicrotask(global, api);
  2666. });
  2667. }
  2668. function rollupMain() {
  2669. const Zone = loadZone();
  2670. patchNode(Zone); // Node needs to come first.
  2671. patchPromise(Zone);
  2672. patchToString(Zone);
  2673. return Zone;
  2674. }
  2675. rollupMain();