zone-testing-node-bundle.js 204 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255
  1. 'use strict';
  2. var __assign = (this && this.__assign) || function () {
  3. __assign = Object.assign || function(t) {
  4. for (var s, i = 1, n = arguments.length; i < n; i++) {
  5. s = arguments[i];
  6. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  7. t[p] = s[p];
  8. }
  9. return t;
  10. };
  11. return __assign.apply(this, arguments);
  12. };
  13. var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
  14. if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
  15. if (ar || !(i in from)) {
  16. if (!ar) ar = Array.prototype.slice.call(from, 0, i);
  17. ar[i] = from[i];
  18. }
  19. }
  20. return to.concat(ar || Array.prototype.slice.call(from));
  21. };
  22. /**
  23. * @license Angular v<unknown>
  24. * (c) 2010-2022 Google LLC. https://angular.io/
  25. * License: MIT
  26. */
  27. (function (factory) {
  28. typeof define === 'function' && define.amd ? define(factory) :
  29. factory();
  30. })((function () {
  31. 'use strict';
  32. ((function (global) {
  33. var performance = global['performance'];
  34. function mark(name) {
  35. performance && performance['mark'] && performance['mark'](name);
  36. }
  37. function performanceMeasure(name, label) {
  38. performance && performance['measure'] && performance['measure'](name, label);
  39. }
  40. mark('Zone');
  41. // Initialize before it's accessed below.
  42. // __Zone_symbol_prefix global can be used to override the default zone
  43. // symbol prefix with a custom one if needed.
  44. var symbolPrefix = global['__Zone_symbol_prefix'] || '__zone_symbol__';
  45. function __symbol__(name) {
  46. return symbolPrefix + name;
  47. }
  48. var checkDuplicate = global[__symbol__('forceDuplicateZoneCheck')] === true;
  49. if (global['Zone']) {
  50. // if global['Zone'] already exists (maybe zone.js was already loaded or
  51. // some other lib also registered a global object named Zone), we may need
  52. // to throw an error, but sometimes user may not want this error.
  53. // For example,
  54. // we have two web pages, page1 includes zone.js, page2 doesn't.
  55. // and the 1st time user load page1 and page2, everything work fine,
  56. // but when user load page2 again, error occurs because global['Zone'] already exists.
  57. // so we add a flag to let user choose whether to throw this error or not.
  58. // By default, if existing Zone is from zone.js, we will not throw the error.
  59. if (checkDuplicate || typeof global['Zone'].__symbol__ !== 'function') {
  60. throw new Error('Zone already loaded.');
  61. }
  62. else {
  63. return global['Zone'];
  64. }
  65. }
  66. var Zone = /** @class */ (function () {
  67. function Zone(parent, zoneSpec) {
  68. this._parent = parent;
  69. this._name = zoneSpec ? zoneSpec.name || 'unnamed' : '<root>';
  70. this._properties = zoneSpec && zoneSpec.properties || {};
  71. this._zoneDelegate =
  72. new _ZoneDelegate(this, this._parent && this._parent._zoneDelegate, zoneSpec);
  73. }
  74. Zone.assertZonePatched = function () {
  75. if (global['Promise'] !== patches['ZoneAwarePromise']) {
  76. throw new Error('Zone.js has detected that ZoneAwarePromise `(window|global).Promise` ' +
  77. 'has been overwritten.\n' +
  78. 'Most likely cause is that a Promise polyfill has been loaded ' +
  79. 'after Zone.js (Polyfilling Promise api is not necessary when zone.js is loaded. ' +
  80. 'If you must load one, do so before loading zone.js.)');
  81. }
  82. };
  83. Object.defineProperty(Zone, "root", {
  84. get: function () {
  85. var zone = Zone.current;
  86. while (zone.parent) {
  87. zone = zone.parent;
  88. }
  89. return zone;
  90. },
  91. enumerable: false,
  92. configurable: true
  93. });
  94. Object.defineProperty(Zone, "current", {
  95. get: function () {
  96. return _currentZoneFrame.zone;
  97. },
  98. enumerable: false,
  99. configurable: true
  100. });
  101. Object.defineProperty(Zone, "currentTask", {
  102. get: function () {
  103. return _currentTask;
  104. },
  105. enumerable: false,
  106. configurable: true
  107. });
  108. // tslint:disable-next-line:require-internal-with-underscore
  109. Zone.__load_patch = function (name, fn, ignoreDuplicate) {
  110. if (ignoreDuplicate === void 0) { ignoreDuplicate = false; }
  111. if (patches.hasOwnProperty(name)) {
  112. // `checkDuplicate` option is defined from global variable
  113. // so it works for all modules.
  114. // `ignoreDuplicate` can work for the specified module
  115. if (!ignoreDuplicate && checkDuplicate) {
  116. throw Error('Already loaded patch: ' + name);
  117. }
  118. }
  119. else if (!global['__Zone_disable_' + name]) {
  120. var perfName = 'Zone:' + name;
  121. mark(perfName);
  122. patches[name] = fn(global, Zone, _api);
  123. performanceMeasure(perfName, perfName);
  124. }
  125. };
  126. Object.defineProperty(Zone.prototype, "parent", {
  127. get: function () {
  128. return this._parent;
  129. },
  130. enumerable: false,
  131. configurable: true
  132. });
  133. Object.defineProperty(Zone.prototype, "name", {
  134. get: function () {
  135. return this._name;
  136. },
  137. enumerable: false,
  138. configurable: true
  139. });
  140. Zone.prototype.get = function (key) {
  141. var zone = this.getZoneWith(key);
  142. if (zone)
  143. return zone._properties[key];
  144. };
  145. Zone.prototype.getZoneWith = function (key) {
  146. var current = this;
  147. while (current) {
  148. if (current._properties.hasOwnProperty(key)) {
  149. return current;
  150. }
  151. current = current._parent;
  152. }
  153. return null;
  154. };
  155. Zone.prototype.fork = function (zoneSpec) {
  156. if (!zoneSpec)
  157. throw new Error('ZoneSpec required!');
  158. return this._zoneDelegate.fork(this, zoneSpec);
  159. };
  160. Zone.prototype.wrap = function (callback, source) {
  161. if (typeof callback !== 'function') {
  162. throw new Error('Expecting function got: ' + callback);
  163. }
  164. var _callback = this._zoneDelegate.intercept(this, callback, source);
  165. var zone = this;
  166. return function () {
  167. return zone.runGuarded(_callback, this, arguments, source);
  168. };
  169. };
  170. Zone.prototype.run = function (callback, applyThis, applyArgs, source) {
  171. _currentZoneFrame = { parent: _currentZoneFrame, zone: this };
  172. try {
  173. return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
  174. }
  175. finally {
  176. _currentZoneFrame = _currentZoneFrame.parent;
  177. }
  178. };
  179. Zone.prototype.runGuarded = function (callback, applyThis, applyArgs, source) {
  180. if (applyThis === void 0) { applyThis = null; }
  181. _currentZoneFrame = { parent: _currentZoneFrame, zone: this };
  182. try {
  183. try {
  184. return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
  185. }
  186. catch (error) {
  187. if (this._zoneDelegate.handleError(this, error)) {
  188. throw error;
  189. }
  190. }
  191. }
  192. finally {
  193. _currentZoneFrame = _currentZoneFrame.parent;
  194. }
  195. };
  196. Zone.prototype.runTask = function (task, applyThis, applyArgs) {
  197. if (task.zone != this) {
  198. throw new Error('A task can only be run in the zone of creation! (Creation: ' +
  199. (task.zone || NO_ZONE).name + '; Execution: ' + this.name + ')');
  200. }
  201. // https://github.com/angular/zone.js/issues/778, sometimes eventTask
  202. // will run in notScheduled(canceled) state, we should not try to
  203. // run such kind of task but just return
  204. if (task.state === notScheduled && (task.type === eventTask || task.type === macroTask)) {
  205. return;
  206. }
  207. var reEntryGuard = task.state != running;
  208. reEntryGuard && task._transitionTo(running, scheduled);
  209. task.runCount++;
  210. var previousTask = _currentTask;
  211. _currentTask = task;
  212. _currentZoneFrame = { parent: _currentZoneFrame, zone: this };
  213. try {
  214. if (task.type == macroTask && task.data && !task.data.isPeriodic) {
  215. task.cancelFn = undefined;
  216. }
  217. try {
  218. return this._zoneDelegate.invokeTask(this, task, applyThis, applyArgs);
  219. }
  220. catch (error) {
  221. if (this._zoneDelegate.handleError(this, error)) {
  222. throw error;
  223. }
  224. }
  225. }
  226. finally {
  227. // if the task's state is notScheduled or unknown, then it has already been cancelled
  228. // we should not reset the state to scheduled
  229. if (task.state !== notScheduled && task.state !== unknown) {
  230. if (task.type == eventTask || (task.data && task.data.isPeriodic)) {
  231. reEntryGuard && task._transitionTo(scheduled, running);
  232. }
  233. else {
  234. task.runCount = 0;
  235. this._updateTaskCount(task, -1);
  236. reEntryGuard &&
  237. task._transitionTo(notScheduled, running, notScheduled);
  238. }
  239. }
  240. _currentZoneFrame = _currentZoneFrame.parent;
  241. _currentTask = previousTask;
  242. }
  243. };
  244. Zone.prototype.scheduleTask = function (task) {
  245. if (task.zone && task.zone !== this) {
  246. // check if the task was rescheduled, the newZone
  247. // should not be the children of the original zone
  248. var newZone = this;
  249. while (newZone) {
  250. if (newZone === task.zone) {
  251. throw Error("can not reschedule task to ".concat(this.name, " which is descendants of the original zone ").concat(task.zone.name));
  252. }
  253. newZone = newZone.parent;
  254. }
  255. }
  256. task._transitionTo(scheduling, notScheduled);
  257. var zoneDelegates = [];
  258. task._zoneDelegates = zoneDelegates;
  259. task._zone = this;
  260. try {
  261. task = this._zoneDelegate.scheduleTask(this, task);
  262. }
  263. catch (err) {
  264. // should set task's state to unknown when scheduleTask throw error
  265. // because the err may from reschedule, so the fromState maybe notScheduled
  266. task._transitionTo(unknown, scheduling, notScheduled);
  267. // TODO: @JiaLiPassion, should we check the result from handleError?
  268. this._zoneDelegate.handleError(this, err);
  269. throw err;
  270. }
  271. if (task._zoneDelegates === zoneDelegates) {
  272. // we have to check because internally the delegate can reschedule the task.
  273. this._updateTaskCount(task, 1);
  274. }
  275. if (task.state == scheduling) {
  276. task._transitionTo(scheduled, scheduling);
  277. }
  278. return task;
  279. };
  280. Zone.prototype.scheduleMicroTask = function (source, callback, data, customSchedule) {
  281. return this.scheduleTask(new ZoneTask(microTask, source, callback, data, customSchedule, undefined));
  282. };
  283. Zone.prototype.scheduleMacroTask = function (source, callback, data, customSchedule, customCancel) {
  284. return this.scheduleTask(new ZoneTask(macroTask, source, callback, data, customSchedule, customCancel));
  285. };
  286. Zone.prototype.scheduleEventTask = function (source, callback, data, customSchedule, customCancel) {
  287. return this.scheduleTask(new ZoneTask(eventTask, source, callback, data, customSchedule, customCancel));
  288. };
  289. Zone.prototype.cancelTask = function (task) {
  290. if (task.zone != this)
  291. throw new Error('A task can only be cancelled in the zone of creation! (Creation: ' +
  292. (task.zone || NO_ZONE).name + '; Execution: ' + this.name + ')');
  293. if (task.state !== scheduled && task.state !== running) {
  294. return;
  295. }
  296. task._transitionTo(canceling, scheduled, running);
  297. try {
  298. this._zoneDelegate.cancelTask(this, task);
  299. }
  300. catch (err) {
  301. // if error occurs when cancelTask, transit the state to unknown
  302. task._transitionTo(unknown, canceling);
  303. this._zoneDelegate.handleError(this, err);
  304. throw err;
  305. }
  306. this._updateTaskCount(task, -1);
  307. task._transitionTo(notScheduled, canceling);
  308. task.runCount = 0;
  309. return task;
  310. };
  311. Zone.prototype._updateTaskCount = function (task, count) {
  312. var zoneDelegates = task._zoneDelegates;
  313. if (count == -1) {
  314. task._zoneDelegates = null;
  315. }
  316. for (var i = 0; i < zoneDelegates.length; i++) {
  317. zoneDelegates[i]._updateTaskCount(task.type, count);
  318. }
  319. };
  320. return Zone;
  321. }());
  322. // tslint:disable-next-line:require-internal-with-underscore
  323. Zone.__symbol__ = __symbol__;
  324. var DELEGATE_ZS = {
  325. name: '',
  326. onHasTask: function (delegate, _, target, hasTaskState) { return delegate.hasTask(target, hasTaskState); },
  327. onScheduleTask: function (delegate, _, target, task) { return delegate.scheduleTask(target, task); },
  328. onInvokeTask: function (delegate, _, target, task, applyThis, applyArgs) { return delegate.invokeTask(target, task, applyThis, applyArgs); },
  329. onCancelTask: function (delegate, _, target, task) { return delegate.cancelTask(target, task); }
  330. };
  331. var _ZoneDelegate = /** @class */ (function () {
  332. function _ZoneDelegate(zone, parentDelegate, zoneSpec) {
  333. this._taskCounts = { 'microTask': 0, 'macroTask': 0, 'eventTask': 0 };
  334. this.zone = zone;
  335. this._parentDelegate = parentDelegate;
  336. this._forkZS = zoneSpec && (zoneSpec && zoneSpec.onFork ? zoneSpec : parentDelegate._forkZS);
  337. this._forkDlgt = zoneSpec && (zoneSpec.onFork ? parentDelegate : parentDelegate._forkDlgt);
  338. this._forkCurrZone =
  339. zoneSpec && (zoneSpec.onFork ? this.zone : parentDelegate._forkCurrZone);
  340. this._interceptZS =
  341. zoneSpec && (zoneSpec.onIntercept ? zoneSpec : parentDelegate._interceptZS);
  342. this._interceptDlgt =
  343. zoneSpec && (zoneSpec.onIntercept ? parentDelegate : parentDelegate._interceptDlgt);
  344. this._interceptCurrZone =
  345. zoneSpec && (zoneSpec.onIntercept ? this.zone : parentDelegate._interceptCurrZone);
  346. this._invokeZS = zoneSpec && (zoneSpec.onInvoke ? zoneSpec : parentDelegate._invokeZS);
  347. this._invokeDlgt =
  348. zoneSpec && (zoneSpec.onInvoke ? parentDelegate : parentDelegate._invokeDlgt);
  349. this._invokeCurrZone =
  350. zoneSpec && (zoneSpec.onInvoke ? this.zone : parentDelegate._invokeCurrZone);
  351. this._handleErrorZS =
  352. zoneSpec && (zoneSpec.onHandleError ? zoneSpec : parentDelegate._handleErrorZS);
  353. this._handleErrorDlgt =
  354. zoneSpec && (zoneSpec.onHandleError ? parentDelegate : parentDelegate._handleErrorDlgt);
  355. this._handleErrorCurrZone =
  356. zoneSpec && (zoneSpec.onHandleError ? this.zone : parentDelegate._handleErrorCurrZone);
  357. this._scheduleTaskZS =
  358. zoneSpec && (zoneSpec.onScheduleTask ? zoneSpec : parentDelegate._scheduleTaskZS);
  359. this._scheduleTaskDlgt = zoneSpec &&
  360. (zoneSpec.onScheduleTask ? parentDelegate : parentDelegate._scheduleTaskDlgt);
  361. this._scheduleTaskCurrZone =
  362. zoneSpec && (zoneSpec.onScheduleTask ? this.zone : parentDelegate._scheduleTaskCurrZone);
  363. this._invokeTaskZS =
  364. zoneSpec && (zoneSpec.onInvokeTask ? zoneSpec : parentDelegate._invokeTaskZS);
  365. this._invokeTaskDlgt =
  366. zoneSpec && (zoneSpec.onInvokeTask ? parentDelegate : parentDelegate._invokeTaskDlgt);
  367. this._invokeTaskCurrZone =
  368. zoneSpec && (zoneSpec.onInvokeTask ? this.zone : parentDelegate._invokeTaskCurrZone);
  369. this._cancelTaskZS =
  370. zoneSpec && (zoneSpec.onCancelTask ? zoneSpec : parentDelegate._cancelTaskZS);
  371. this._cancelTaskDlgt =
  372. zoneSpec && (zoneSpec.onCancelTask ? parentDelegate : parentDelegate._cancelTaskDlgt);
  373. this._cancelTaskCurrZone =
  374. zoneSpec && (zoneSpec.onCancelTask ? this.zone : parentDelegate._cancelTaskCurrZone);
  375. this._hasTaskZS = null;
  376. this._hasTaskDlgt = null;
  377. this._hasTaskDlgtOwner = null;
  378. this._hasTaskCurrZone = null;
  379. var zoneSpecHasTask = zoneSpec && zoneSpec.onHasTask;
  380. var parentHasTask = parentDelegate && parentDelegate._hasTaskZS;
  381. if (zoneSpecHasTask || parentHasTask) {
  382. // If we need to report hasTask, than this ZS needs to do ref counting on tasks. In such
  383. // a case all task related interceptors must go through this ZD. We can't short circuit it.
  384. this._hasTaskZS = zoneSpecHasTask ? zoneSpec : DELEGATE_ZS;
  385. this._hasTaskDlgt = parentDelegate;
  386. this._hasTaskDlgtOwner = this;
  387. this._hasTaskCurrZone = zone;
  388. if (!zoneSpec.onScheduleTask) {
  389. this._scheduleTaskZS = DELEGATE_ZS;
  390. this._scheduleTaskDlgt = parentDelegate;
  391. this._scheduleTaskCurrZone = this.zone;
  392. }
  393. if (!zoneSpec.onInvokeTask) {
  394. this._invokeTaskZS = DELEGATE_ZS;
  395. this._invokeTaskDlgt = parentDelegate;
  396. this._invokeTaskCurrZone = this.zone;
  397. }
  398. if (!zoneSpec.onCancelTask) {
  399. this._cancelTaskZS = DELEGATE_ZS;
  400. this._cancelTaskDlgt = parentDelegate;
  401. this._cancelTaskCurrZone = this.zone;
  402. }
  403. }
  404. }
  405. _ZoneDelegate.prototype.fork = function (targetZone, zoneSpec) {
  406. return this._forkZS ? this._forkZS.onFork(this._forkDlgt, this.zone, targetZone, zoneSpec) :
  407. new Zone(targetZone, zoneSpec);
  408. };
  409. _ZoneDelegate.prototype.intercept = function (targetZone, callback, source) {
  410. return this._interceptZS ?
  411. this._interceptZS.onIntercept(this._interceptDlgt, this._interceptCurrZone, targetZone, callback, source) :
  412. callback;
  413. };
  414. _ZoneDelegate.prototype.invoke = function (targetZone, callback, applyThis, applyArgs, source) {
  415. return this._invokeZS ? this._invokeZS.onInvoke(this._invokeDlgt, this._invokeCurrZone, targetZone, callback, applyThis, applyArgs, source) :
  416. callback.apply(applyThis, applyArgs);
  417. };
  418. _ZoneDelegate.prototype.handleError = function (targetZone, error) {
  419. return this._handleErrorZS ?
  420. this._handleErrorZS.onHandleError(this._handleErrorDlgt, this._handleErrorCurrZone, targetZone, error) :
  421. true;
  422. };
  423. _ZoneDelegate.prototype.scheduleTask = function (targetZone, task) {
  424. var returnTask = task;
  425. if (this._scheduleTaskZS) {
  426. if (this._hasTaskZS) {
  427. returnTask._zoneDelegates.push(this._hasTaskDlgtOwner);
  428. }
  429. // clang-format off
  430. returnTask = this._scheduleTaskZS.onScheduleTask(this._scheduleTaskDlgt, this._scheduleTaskCurrZone, targetZone, task);
  431. // clang-format on
  432. if (!returnTask)
  433. returnTask = task;
  434. }
  435. else {
  436. if (task.scheduleFn) {
  437. task.scheduleFn(task);
  438. }
  439. else if (task.type == microTask) {
  440. scheduleMicroTask(task);
  441. }
  442. else {
  443. throw new Error('Task is missing scheduleFn.');
  444. }
  445. }
  446. return returnTask;
  447. };
  448. _ZoneDelegate.prototype.invokeTask = function (targetZone, task, applyThis, applyArgs) {
  449. return this._invokeTaskZS ? this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt, this._invokeTaskCurrZone, targetZone, task, applyThis, applyArgs) :
  450. task.callback.apply(applyThis, applyArgs);
  451. };
  452. _ZoneDelegate.prototype.cancelTask = function (targetZone, task) {
  453. var value;
  454. if (this._cancelTaskZS) {
  455. value = this._cancelTaskZS.onCancelTask(this._cancelTaskDlgt, this._cancelTaskCurrZone, targetZone, task);
  456. }
  457. else {
  458. if (!task.cancelFn) {
  459. throw Error('Task is not cancelable');
  460. }
  461. value = task.cancelFn(task);
  462. }
  463. return value;
  464. };
  465. _ZoneDelegate.prototype.hasTask = function (targetZone, isEmpty) {
  466. // hasTask should not throw error so other ZoneDelegate
  467. // can still trigger hasTask callback
  468. try {
  469. this._hasTaskZS &&
  470. this._hasTaskZS.onHasTask(this._hasTaskDlgt, this._hasTaskCurrZone, targetZone, isEmpty);
  471. }
  472. catch (err) {
  473. this.handleError(targetZone, err);
  474. }
  475. };
  476. // tslint:disable-next-line:require-internal-with-underscore
  477. _ZoneDelegate.prototype._updateTaskCount = function (type, count) {
  478. var counts = this._taskCounts;
  479. var prev = counts[type];
  480. var next = counts[type] = prev + count;
  481. if (next < 0) {
  482. throw new Error('More tasks executed then were scheduled.');
  483. }
  484. if (prev == 0 || next == 0) {
  485. var isEmpty = {
  486. microTask: counts['microTask'] > 0,
  487. macroTask: counts['macroTask'] > 0,
  488. eventTask: counts['eventTask'] > 0,
  489. change: type
  490. };
  491. this.hasTask(this.zone, isEmpty);
  492. }
  493. };
  494. return _ZoneDelegate;
  495. }());
  496. var ZoneTask = /** @class */ (function () {
  497. function ZoneTask(type, source, callback, options, scheduleFn, cancelFn) {
  498. // tslint:disable-next-line:require-internal-with-underscore
  499. this._zone = null;
  500. this.runCount = 0;
  501. // tslint:disable-next-line:require-internal-with-underscore
  502. this._zoneDelegates = null;
  503. // tslint:disable-next-line:require-internal-with-underscore
  504. this._state = 'notScheduled';
  505. this.type = type;
  506. this.source = source;
  507. this.data = options;
  508. this.scheduleFn = scheduleFn;
  509. this.cancelFn = cancelFn;
  510. if (!callback) {
  511. throw new Error('callback is not defined');
  512. }
  513. this.callback = callback;
  514. var self = this;
  515. // TODO: @JiaLiPassion options should have interface
  516. if (type === eventTask && options && options.useG) {
  517. this.invoke = ZoneTask.invokeTask;
  518. }
  519. else {
  520. this.invoke = function () {
  521. return ZoneTask.invokeTask.call(global, self, this, arguments);
  522. };
  523. }
  524. }
  525. ZoneTask.invokeTask = function (task, target, args) {
  526. if (!task) {
  527. task = this;
  528. }
  529. _numberOfNestedTaskFrames++;
  530. try {
  531. task.runCount++;
  532. return task.zone.runTask(task, target, args);
  533. }
  534. finally {
  535. if (_numberOfNestedTaskFrames == 1) {
  536. drainMicroTaskQueue();
  537. }
  538. _numberOfNestedTaskFrames--;
  539. }
  540. };
  541. Object.defineProperty(ZoneTask.prototype, "zone", {
  542. get: function () {
  543. return this._zone;
  544. },
  545. enumerable: false,
  546. configurable: true
  547. });
  548. Object.defineProperty(ZoneTask.prototype, "state", {
  549. get: function () {
  550. return this._state;
  551. },
  552. enumerable: false,
  553. configurable: true
  554. });
  555. ZoneTask.prototype.cancelScheduleRequest = function () {
  556. this._transitionTo(notScheduled, scheduling);
  557. };
  558. // tslint:disable-next-line:require-internal-with-underscore
  559. ZoneTask.prototype._transitionTo = function (toState, fromState1, fromState2) {
  560. if (this._state === fromState1 || this._state === fromState2) {
  561. this._state = toState;
  562. if (toState == notScheduled) {
  563. this._zoneDelegates = null;
  564. }
  565. }
  566. else {
  567. throw new Error("".concat(this.type, " '").concat(this.source, "': can not transition to '").concat(toState, "', expecting state '").concat(fromState1, "'").concat(fromState2 ? ' or \'' + fromState2 + '\'' : '', ", was '").concat(this._state, "'."));
  568. }
  569. };
  570. ZoneTask.prototype.toString = function () {
  571. if (this.data && typeof this.data.handleId !== 'undefined') {
  572. return this.data.handleId.toString();
  573. }
  574. else {
  575. return Object.prototype.toString.call(this);
  576. }
  577. };
  578. // add toJSON method to prevent cyclic error when
  579. // call JSON.stringify(zoneTask)
  580. ZoneTask.prototype.toJSON = function () {
  581. return {
  582. type: this.type,
  583. state: this.state,
  584. source: this.source,
  585. zone: this.zone.name,
  586. runCount: this.runCount
  587. };
  588. };
  589. return ZoneTask;
  590. }());
  591. //////////////////////////////////////////////////////
  592. //////////////////////////////////////////////////////
  593. /// MICROTASK QUEUE
  594. //////////////////////////////////////////////////////
  595. //////////////////////////////////////////////////////
  596. var symbolSetTimeout = __symbol__('setTimeout');
  597. var symbolPromise = __symbol__('Promise');
  598. var symbolThen = __symbol__('then');
  599. var _microTaskQueue = [];
  600. var _isDrainingMicrotaskQueue = false;
  601. var nativeMicroTaskQueuePromise;
  602. function nativeScheduleMicroTask(func) {
  603. if (!nativeMicroTaskQueuePromise) {
  604. if (global[symbolPromise]) {
  605. nativeMicroTaskQueuePromise = global[symbolPromise].resolve(0);
  606. }
  607. }
  608. if (nativeMicroTaskQueuePromise) {
  609. var nativeThen = nativeMicroTaskQueuePromise[symbolThen];
  610. if (!nativeThen) {
  611. // native Promise is not patchable, we need to use `then` directly
  612. // issue 1078
  613. nativeThen = nativeMicroTaskQueuePromise['then'];
  614. }
  615. nativeThen.call(nativeMicroTaskQueuePromise, func);
  616. }
  617. else {
  618. global[symbolSetTimeout](func, 0);
  619. }
  620. }
  621. function scheduleMicroTask(task) {
  622. // if we are not running in any task, and there has not been anything scheduled
  623. // we must bootstrap the initial task creation by manually scheduling the drain
  624. if (_numberOfNestedTaskFrames === 0 && _microTaskQueue.length === 0) {
  625. // We are not running in Task, so we need to kickstart the microtask queue.
  626. nativeScheduleMicroTask(drainMicroTaskQueue);
  627. }
  628. task && _microTaskQueue.push(task);
  629. }
  630. function drainMicroTaskQueue() {
  631. if (!_isDrainingMicrotaskQueue) {
  632. _isDrainingMicrotaskQueue = true;
  633. while (_microTaskQueue.length) {
  634. var queue = _microTaskQueue;
  635. _microTaskQueue = [];
  636. for (var i = 0; i < queue.length; i++) {
  637. var task = queue[i];
  638. try {
  639. task.zone.runTask(task, null, null);
  640. }
  641. catch (error) {
  642. _api.onUnhandledError(error);
  643. }
  644. }
  645. }
  646. _api.microtaskDrainDone();
  647. _isDrainingMicrotaskQueue = false;
  648. }
  649. }
  650. //////////////////////////////////////////////////////
  651. //////////////////////////////////////////////////////
  652. /// BOOTSTRAP
  653. //////////////////////////////////////////////////////
  654. //////////////////////////////////////////////////////
  655. var NO_ZONE = { name: 'NO ZONE' };
  656. var notScheduled = 'notScheduled', scheduling = 'scheduling', scheduled = 'scheduled', running = 'running', canceling = 'canceling', unknown = 'unknown';
  657. var microTask = 'microTask', macroTask = 'macroTask', eventTask = 'eventTask';
  658. var patches = {};
  659. var _api = {
  660. symbol: __symbol__,
  661. currentZoneFrame: function () { return _currentZoneFrame; },
  662. onUnhandledError: noop,
  663. microtaskDrainDone: noop,
  664. scheduleMicroTask: scheduleMicroTask,
  665. showUncaughtError: function () { return !Zone[__symbol__('ignoreConsoleErrorUncaughtError')]; },
  666. patchEventTarget: function () { return []; },
  667. patchOnProperties: noop,
  668. patchMethod: function () { return noop; },
  669. bindArguments: function () { return []; },
  670. patchThen: function () { return noop; },
  671. patchMacroTask: function () { return noop; },
  672. patchEventPrototype: function () { return noop; },
  673. isIEOrEdge: function () { return false; },
  674. getGlobalObjects: function () { return undefined; },
  675. ObjectDefineProperty: function () { return noop; },
  676. ObjectGetOwnPropertyDescriptor: function () { return undefined; },
  677. ObjectCreate: function () { return undefined; },
  678. ArraySlice: function () { return []; },
  679. patchClass: function () { return noop; },
  680. wrapWithCurrentZone: function () { return noop; },
  681. filterProperties: function () { return []; },
  682. attachOriginToPatched: function () { return noop; },
  683. _redefineProperty: function () { return noop; },
  684. patchCallbacks: function () { return noop; },
  685. nativeScheduleMicroTask: nativeScheduleMicroTask
  686. };
  687. var _currentZoneFrame = { parent: null, zone: new Zone(null, null) };
  688. var _currentTask = null;
  689. var _numberOfNestedTaskFrames = 0;
  690. function noop() { }
  691. performanceMeasure('Zone', 'Zone');
  692. return global['Zone'] = Zone;
  693. }))(typeof window !== 'undefined' && window || typeof self !== 'undefined' && self || global);
  694. /**
  695. * A different implementation for monkey patching Promise.
  696. * Currently Zone.js patches Promise itself with ZoneAwarePromise and also Promise.prototype.then
  697. * The reason is:
  698. *
  699. * 1. Promise.prototype.then should trigger ZoneSpec.scheduleTask and acts as a microTask
  700. * 2. Promise should be able to controlled by fakeAsync(), so Promise.prototype.then can work as
  701. * sync operation in fakeAsync()
  702. * 3. Promise unhandledRejection can be handled by ZoneSpec.onHandleError hook
  703. *
  704. * And this implementation also has it's disadvantage.
  705. *
  706. * 1. We need to implement a full Promise spec by ourselves.
  707. * 2. We need to implement the new APIs for Promise such as (all, allSettled, any...) when the new
  708. * APIs are available.
  709. * 3. Promise behavior is different with the native one, such as the timing of then callback.
  710. * 4. Can not handle the some vm operation requires native Promise such as async/await or
  711. * SafePromise.
  712. *
  713. * And this new implementation try to address most of these disadvantages.
  714. * 1. We don't monkey patch Promise itself any longer.
  715. * 2. We only monkey patches Promise.prototype.then and schedule microTask from there.
  716. * 3. The Promise APIs are all using native ones.
  717. * 4. SafePromise issues are gone, and the timing will be the same with the native one.
  718. *
  719. * Also this new implementation introduces breaking changes.
  720. *
  721. * 1. Promise can not be easily handled by fakeAsync(), and since we will deprecate fakeAsync() in
  722. * the future, this is the first step.
  723. * 2. Promise unhandled rejection happened inside new Promise(callback) will not be handled by
  724. * ZoneSpec.onHandleError(thenCallback error will not be be impacted).
  725. *
  726. * So now we only introduces this change to `zone-node` bundle, since the breaking change will be
  727. * minor for NodeJS environment,
  728. * @TODO: JiaLiPassion, we will introduce this change to browser later.
  729. */
  730. Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
  731. var __symbol__ = api.symbol;
  732. var symbolThen = __symbol__('then');
  733. api.onUnhandledError = function (e) {
  734. if (api.showUncaughtError()) {
  735. var rejection = e && e.rejection;
  736. if (rejection) {
  737. console.error('Unhandled Promise rejection:', rejection instanceof Error ? rejection === null || rejection === void 0 ? void 0 : rejection.message : rejection, '; Zone:', e.zone.name, '; Task:', e.task && e.task.source, '; Value:', rejection, rejection instanceof Error ? rejection.stack : undefined);
  738. }
  739. else {
  740. console.error(e);
  741. }
  742. }
  743. };
  744. api.microtaskDrainDone = function () { };
  745. var symbolThenPatched = __symbol__('thenPatched');
  746. function patchThen(Ctor) {
  747. var proto = Ctor.prototype;
  748. if (Ctor[symbolThenPatched] === true) {
  749. return;
  750. }
  751. var prop = Object.getOwnPropertyDescriptor(proto, 'then');
  752. if (prop && (prop.writable === false || !prop.configurable)) {
  753. // check Ctor.prototype.then propertyDescriptor is writable or not
  754. // in meteor env, writable is false, we should ignore such case
  755. return;
  756. }
  757. var originalThen = proto.then;
  758. // Keep a reference to the original method.
  759. proto[symbolThen] = originalThen;
  760. var makeResolver = function (resolveFunc, zone, source, isReject) {
  761. if (!resolveFunc) {
  762. return resolveFunc;
  763. }
  764. return function (val) {
  765. var task = zone.scheduleMicroTask(source, function () {
  766. return typeof resolveFunc === 'function' ? resolveFunc(val) :
  767. (isReject ? Promise.reject(val) : val);
  768. }, undefined, function () { });
  769. return zone.runGuarded(function () {
  770. return task.invoke();
  771. }, undefined, []);
  772. };
  773. };
  774. Ctor.prototype.then = function (onResolve, onReject) {
  775. var zone = Zone.current;
  776. return originalThen.call(this, makeResolver(onResolve, zone, 'Promise.prototype.then', false), makeResolver(onReject, zone, 'Promise.prototype.reject', true));
  777. };
  778. Ctor[symbolThenPatched] = true;
  779. }
  780. api.patchThen = patchThen;
  781. if (Promise) {
  782. patchThen(Promise);
  783. }
  784. global[api.symbol('Promise')] = Promise;
  785. return Promise;
  786. });
  787. /**
  788. * Suppress closure compiler errors about unknown 'Zone' variable
  789. * @fileoverview
  790. * @suppress {undefinedVars,globalThis,missingRequire}
  791. */
  792. /// <reference types="node"/>
  793. // issue #989, to reduce bundle size, use short name
  794. /** Object.getOwnPropertyDescriptor */
  795. var ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  796. /** Object.defineProperty */
  797. var ObjectDefineProperty = Object.defineProperty;
  798. /** Object.getPrototypeOf */
  799. var ObjectGetPrototypeOf = Object.getPrototypeOf;
  800. /** Array.prototype.slice */
  801. var ArraySlice = Array.prototype.slice;
  802. /** addEventListener string const */
  803. var ADD_EVENT_LISTENER_STR = 'addEventListener';
  804. /** removeEventListener string const */
  805. var REMOVE_EVENT_LISTENER_STR = 'removeEventListener';
  806. /** zoneSymbol addEventListener */
  807. Zone.__symbol__(ADD_EVENT_LISTENER_STR);
  808. /** zoneSymbol removeEventListener */
  809. Zone.__symbol__(REMOVE_EVENT_LISTENER_STR);
  810. /** true string const */
  811. var TRUE_STR = 'true';
  812. /** false string const */
  813. var FALSE_STR = 'false';
  814. /** Zone symbol prefix string const. */
  815. var ZONE_SYMBOL_PREFIX = Zone.__symbol__('');
  816. function wrapWithCurrentZone(callback, source) {
  817. return Zone.current.wrap(callback, source);
  818. }
  819. function scheduleMacroTaskWithCurrentZone(source, callback, data, customSchedule, customCancel) {
  820. return Zone.current.scheduleMacroTask(source, callback, data, customSchedule, customCancel);
  821. }
  822. var zoneSymbol = Zone.__symbol__;
  823. var isWindowExists = typeof window !== 'undefined';
  824. var internalWindow = isWindowExists ? window : undefined;
  825. var _global = isWindowExists && internalWindow || typeof self === 'object' && self || global;
  826. var REMOVE_ATTRIBUTE = 'removeAttribute';
  827. function bindArguments(args, source) {
  828. for (var i = args.length - 1; i >= 0; i--) {
  829. if (typeof args[i] === 'function') {
  830. args[i] = wrapWithCurrentZone(args[i], source + '_' + i);
  831. }
  832. }
  833. return args;
  834. }
  835. function isPropertyWritable(propertyDesc) {
  836. if (!propertyDesc) {
  837. return true;
  838. }
  839. if (propertyDesc.writable === false) {
  840. return false;
  841. }
  842. return !(typeof propertyDesc.get === 'function' && typeof propertyDesc.set === 'undefined');
  843. }
  844. var isWebWorker = (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope);
  845. // Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
  846. // this code.
  847. var isNode = (!('nw' in _global) && typeof _global.process !== 'undefined' &&
  848. {}.toString.call(_global.process) === '[object process]');
  849. var isBrowser = !isNode && !isWebWorker && !!(isWindowExists && internalWindow['HTMLElement']);
  850. // we are in electron of nw, so we are both browser and nodejs
  851. // Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
  852. // this code.
  853. var isMix = typeof _global.process !== 'undefined' &&
  854. {}.toString.call(_global.process) === '[object process]' && !isWebWorker &&
  855. !!(isWindowExists && internalWindow['HTMLElement']);
  856. var zoneSymbolEventNames$1 = {};
  857. var wrapFn = function (event) {
  858. // https://github.com/angular/zone.js/issues/911, in IE, sometimes
  859. // event will be undefined, so we need to use window.event
  860. event = event || _global.event;
  861. if (!event) {
  862. return;
  863. }
  864. var eventNameSymbol = zoneSymbolEventNames$1[event.type];
  865. if (!eventNameSymbol) {
  866. eventNameSymbol = zoneSymbolEventNames$1[event.type] = zoneSymbol('ON_PROPERTY' + event.type);
  867. }
  868. var target = this || event.target || _global;
  869. var listener = target[eventNameSymbol];
  870. var result;
  871. if (isBrowser && target === internalWindow && event.type === 'error') {
  872. // window.onerror have different signature
  873. // https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror#window.onerror
  874. // and onerror callback will prevent default when callback return true
  875. var errorEvent = event;
  876. result = listener &&
  877. listener.call(this, errorEvent.message, errorEvent.filename, errorEvent.lineno, errorEvent.colno, errorEvent.error);
  878. if (result === true) {
  879. event.preventDefault();
  880. }
  881. }
  882. else {
  883. result = listener && listener.apply(this, arguments);
  884. if (result != undefined && !result) {
  885. event.preventDefault();
  886. }
  887. }
  888. return result;
  889. };
  890. function patchProperty(obj, prop, prototype) {
  891. var desc = ObjectGetOwnPropertyDescriptor(obj, prop);
  892. if (!desc && prototype) {
  893. // when patch window object, use prototype to check prop exist or not
  894. var prototypeDesc = ObjectGetOwnPropertyDescriptor(prototype, prop);
  895. if (prototypeDesc) {
  896. desc = { enumerable: true, configurable: true };
  897. }
  898. }
  899. // if the descriptor not exists or is not configurable
  900. // just return
  901. if (!desc || !desc.configurable) {
  902. return;
  903. }
  904. var onPropPatchedSymbol = zoneSymbol('on' + prop + 'patched');
  905. if (obj.hasOwnProperty(onPropPatchedSymbol) && obj[onPropPatchedSymbol]) {
  906. return;
  907. }
  908. // A property descriptor cannot have getter/setter and be writable
  909. // deleting the writable and value properties avoids this error:
  910. //
  911. // TypeError: property descriptors must not specify a value or be writable when a
  912. // getter or setter has been specified
  913. delete desc.writable;
  914. delete desc.value;
  915. var originalDescGet = desc.get;
  916. var originalDescSet = desc.set;
  917. // slice(2) cuz 'onclick' -> 'click', etc
  918. var eventName = prop.slice(2);
  919. var eventNameSymbol = zoneSymbolEventNames$1[eventName];
  920. if (!eventNameSymbol) {
  921. eventNameSymbol = zoneSymbolEventNames$1[eventName] = zoneSymbol('ON_PROPERTY' + eventName);
  922. }
  923. desc.set = function (newValue) {
  924. // in some of windows's onproperty callback, this is undefined
  925. // so we need to check it
  926. var target = this;
  927. if (!target && obj === _global) {
  928. target = _global;
  929. }
  930. if (!target) {
  931. return;
  932. }
  933. var previousValue = target[eventNameSymbol];
  934. if (typeof previousValue === 'function') {
  935. target.removeEventListener(eventName, wrapFn);
  936. }
  937. // issue #978, when onload handler was added before loading zone.js
  938. // we should remove it with originalDescSet
  939. originalDescSet && originalDescSet.call(target, null);
  940. target[eventNameSymbol] = newValue;
  941. if (typeof newValue === 'function') {
  942. target.addEventListener(eventName, wrapFn, false);
  943. }
  944. };
  945. // The getter would return undefined for unassigned properties but the default value of an
  946. // unassigned property is null
  947. desc.get = function () {
  948. // in some of windows's onproperty callback, this is undefined
  949. // so we need to check it
  950. var target = this;
  951. if (!target && obj === _global) {
  952. target = _global;
  953. }
  954. if (!target) {
  955. return null;
  956. }
  957. var listener = target[eventNameSymbol];
  958. if (listener) {
  959. return listener;
  960. }
  961. else if (originalDescGet) {
  962. // result will be null when use inline event attribute,
  963. // such as <button onclick="func();">OK</button>
  964. // because the onclick function is internal raw uncompiled handler
  965. // the onclick will be evaluated when first time event was triggered or
  966. // the property is accessed, https://github.com/angular/zone.js/issues/525
  967. // so we should use original native get to retrieve the handler
  968. var value = originalDescGet.call(this);
  969. if (value) {
  970. desc.set.call(this, value);
  971. if (typeof target[REMOVE_ATTRIBUTE] === 'function') {
  972. target.removeAttribute(prop);
  973. }
  974. return value;
  975. }
  976. }
  977. return null;
  978. };
  979. ObjectDefineProperty(obj, prop, desc);
  980. obj[onPropPatchedSymbol] = true;
  981. }
  982. function patchOnProperties(obj, properties, prototype) {
  983. if (properties) {
  984. for (var i = 0; i < properties.length; i++) {
  985. patchProperty(obj, 'on' + properties[i], prototype);
  986. }
  987. }
  988. else {
  989. var onProperties = [];
  990. for (var prop in obj) {
  991. if (prop.slice(0, 2) == 'on') {
  992. onProperties.push(prop);
  993. }
  994. }
  995. for (var j = 0; j < onProperties.length; j++) {
  996. patchProperty(obj, onProperties[j], prototype);
  997. }
  998. }
  999. }
  1000. zoneSymbol('originalInstance');
  1001. function copySymbolProperties(src, dest) {
  1002. if (typeof Object.getOwnPropertySymbols !== 'function') {
  1003. return;
  1004. }
  1005. var symbols = Object.getOwnPropertySymbols(src);
  1006. symbols.forEach(function (symbol) {
  1007. var desc = Object.getOwnPropertyDescriptor(src, symbol);
  1008. Object.defineProperty(dest, symbol, {
  1009. get: function () {
  1010. return src[symbol];
  1011. },
  1012. set: function (value) {
  1013. if (desc && (!desc.writable || typeof desc.set !== 'function')) {
  1014. // if src[symbol] is not writable or not have a setter, just return
  1015. return;
  1016. }
  1017. src[symbol] = value;
  1018. },
  1019. enumerable: desc ? desc.enumerable : true,
  1020. configurable: desc ? desc.configurable : true
  1021. });
  1022. });
  1023. }
  1024. var shouldCopySymbolProperties = false;
  1025. function setShouldCopySymbolProperties(flag) {
  1026. shouldCopySymbolProperties = flag;
  1027. }
  1028. function patchMethod(target, name, patchFn) {
  1029. var proto = target;
  1030. while (proto && !proto.hasOwnProperty(name)) {
  1031. proto = ObjectGetPrototypeOf(proto);
  1032. }
  1033. if (!proto && target[name]) {
  1034. // somehow we did not find it, but we can see it. This happens on IE for Window properties.
  1035. proto = target;
  1036. }
  1037. var delegateName = zoneSymbol(name);
  1038. var delegate = null;
  1039. if (proto && (!(delegate = proto[delegateName]) || !proto.hasOwnProperty(delegateName))) {
  1040. delegate = proto[delegateName] = proto[name];
  1041. // check whether proto[name] is writable
  1042. // some property is readonly in safari, such as HtmlCanvasElement.prototype.toBlob
  1043. var desc = proto && ObjectGetOwnPropertyDescriptor(proto, name);
  1044. if (isPropertyWritable(desc)) {
  1045. var patchDelegate_1 = patchFn(delegate, delegateName, name);
  1046. proto[name] = function () {
  1047. return patchDelegate_1(this, arguments);
  1048. };
  1049. attachOriginToPatched(proto[name], delegate);
  1050. if (shouldCopySymbolProperties) {
  1051. copySymbolProperties(delegate, proto[name]);
  1052. }
  1053. }
  1054. }
  1055. return delegate;
  1056. }
  1057. // TODO: @JiaLiPassion, support cancel task later if necessary
  1058. function patchMacroTask(obj, funcName, metaCreator) {
  1059. var setNative = null;
  1060. function scheduleTask(task) {
  1061. var data = task.data;
  1062. data.args[data.cbIdx] = function () {
  1063. task.invoke.apply(this, arguments);
  1064. };
  1065. setNative.apply(data.target, data.args);
  1066. return task;
  1067. }
  1068. setNative = patchMethod(obj, funcName, function (delegate) { return function (self, args) {
  1069. var meta = metaCreator(self, args);
  1070. if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
  1071. return scheduleMacroTaskWithCurrentZone(meta.name, args[meta.cbIdx], meta, scheduleTask);
  1072. }
  1073. else {
  1074. // cause an error by calling it directly.
  1075. return delegate.apply(self, args);
  1076. }
  1077. }; });
  1078. }
  1079. function patchMicroTask(obj, funcName, metaCreator) {
  1080. var setNative = null;
  1081. function scheduleTask(task) {
  1082. var data = task.data;
  1083. data.args[data.cbIdx] = function () {
  1084. task.invoke.apply(this, arguments);
  1085. };
  1086. setNative.apply(data.target, data.args);
  1087. return task;
  1088. }
  1089. setNative = patchMethod(obj, funcName, function (delegate) { return function (self, args) {
  1090. var meta = metaCreator(self, args);
  1091. if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
  1092. return Zone.current.scheduleMicroTask(meta.name, args[meta.cbIdx], meta, scheduleTask);
  1093. }
  1094. else {
  1095. // cause an error by calling it directly.
  1096. return delegate.apply(self, args);
  1097. }
  1098. }; });
  1099. }
  1100. function attachOriginToPatched(patched, original) {
  1101. patched[zoneSymbol('OriginalDelegate')] = original;
  1102. }
  1103. // override Function.prototype.toString to make zone.js patched function
  1104. // look like native function
  1105. Zone.__load_patch('toString', function (global) {
  1106. // patch Func.prototype.toString to let them look like native
  1107. var originalFunctionToString = Function.prototype.toString;
  1108. var ORIGINAL_DELEGATE_SYMBOL = zoneSymbol('OriginalDelegate');
  1109. var PROMISE_SYMBOL = zoneSymbol('Promise');
  1110. var ERROR_SYMBOL = zoneSymbol('Error');
  1111. var newFunctionToString = function toString() {
  1112. if (typeof this === 'function') {
  1113. var originalDelegate = this[ORIGINAL_DELEGATE_SYMBOL];
  1114. if (originalDelegate) {
  1115. if (typeof originalDelegate === 'function') {
  1116. return originalFunctionToString.call(originalDelegate);
  1117. }
  1118. else {
  1119. return Object.prototype.toString.call(originalDelegate);
  1120. }
  1121. }
  1122. if (this === Promise) {
  1123. var nativePromise = global[PROMISE_SYMBOL];
  1124. if (nativePromise) {
  1125. return originalFunctionToString.call(nativePromise);
  1126. }
  1127. }
  1128. if (this === Error) {
  1129. var nativeError = global[ERROR_SYMBOL];
  1130. if (nativeError) {
  1131. return originalFunctionToString.call(nativeError);
  1132. }
  1133. }
  1134. }
  1135. return originalFunctionToString.call(this);
  1136. };
  1137. newFunctionToString[ORIGINAL_DELEGATE_SYMBOL] = originalFunctionToString;
  1138. Function.prototype.toString = newFunctionToString;
  1139. // patch Object.prototype.toString to let them look like native
  1140. var originalObjectToString = Object.prototype.toString;
  1141. var PROMISE_OBJECT_TO_STRING = '[object Promise]';
  1142. Object.prototype.toString = function () {
  1143. if (typeof Promise === 'function' && this instanceof Promise) {
  1144. return PROMISE_OBJECT_TO_STRING;
  1145. }
  1146. return originalObjectToString.call(this);
  1147. };
  1148. });
  1149. Zone.__load_patch('node_util', function (global, Zone, api) {
  1150. api.patchOnProperties = patchOnProperties;
  1151. api.patchMethod = patchMethod;
  1152. api.bindArguments = bindArguments;
  1153. api.patchMacroTask = patchMacroTask;
  1154. setShouldCopySymbolProperties(true);
  1155. });
  1156. /**
  1157. * @fileoverview
  1158. * @suppress {missingRequire}
  1159. */
  1160. var passiveSupported = false;
  1161. if (typeof window !== 'undefined') {
  1162. try {
  1163. var options = Object.defineProperty({}, 'passive', {
  1164. get: function () {
  1165. passiveSupported = true;
  1166. }
  1167. });
  1168. // Note: We pass the `options` object as the event handler too. This is not compatible with the
  1169. // signature of `addEventListener` or `removeEventListener` but enables us to remove the handler
  1170. // without an actual handler.
  1171. window.addEventListener('test', options, options);
  1172. window.removeEventListener('test', options, options);
  1173. }
  1174. catch (err) {
  1175. passiveSupported = false;
  1176. }
  1177. }
  1178. // an identifier to tell ZoneTask do not create a new invoke closure
  1179. var OPTIMIZED_ZONE_EVENT_TASK_DATA = {
  1180. useG: true
  1181. };
  1182. var zoneSymbolEventNames = {};
  1183. var globalSources = {};
  1184. var EVENT_NAME_SYMBOL_REGX = new RegExp('^' + ZONE_SYMBOL_PREFIX + '(\\w+)(true|false)$');
  1185. var IMMEDIATE_PROPAGATION_SYMBOL = zoneSymbol('propagationStopped');
  1186. function prepareEventNames(eventName, eventNameToString) {
  1187. var falseEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + FALSE_STR;
  1188. var trueEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + TRUE_STR;
  1189. var symbol = ZONE_SYMBOL_PREFIX + falseEventName;
  1190. var symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
  1191. zoneSymbolEventNames[eventName] = {};
  1192. zoneSymbolEventNames[eventName][FALSE_STR] = symbol;
  1193. zoneSymbolEventNames[eventName][TRUE_STR] = symbolCapture;
  1194. }
  1195. function patchEventTarget(_global, api, apis, patchOptions) {
  1196. var ADD_EVENT_LISTENER = (patchOptions && patchOptions.add) || ADD_EVENT_LISTENER_STR;
  1197. var REMOVE_EVENT_LISTENER = (patchOptions && patchOptions.rm) || REMOVE_EVENT_LISTENER_STR;
  1198. var LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.listeners) || 'eventListeners';
  1199. var REMOVE_ALL_LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.rmAll) || 'removeAllListeners';
  1200. var zoneSymbolAddEventListener = zoneSymbol(ADD_EVENT_LISTENER);
  1201. var ADD_EVENT_LISTENER_SOURCE = '.' + ADD_EVENT_LISTENER + ':';
  1202. var PREPEND_EVENT_LISTENER = 'prependListener';
  1203. var PREPEND_EVENT_LISTENER_SOURCE = '.' + PREPEND_EVENT_LISTENER + ':';
  1204. var invokeTask = function (task, target, event) {
  1205. // for better performance, check isRemoved which is set
  1206. // by removeEventListener
  1207. if (task.isRemoved) {
  1208. return;
  1209. }
  1210. var delegate = task.callback;
  1211. if (typeof delegate === 'object' && delegate.handleEvent) {
  1212. // create the bind version of handleEvent when invoke
  1213. task.callback = function (event) { return delegate.handleEvent(event); };
  1214. task.originalDelegate = delegate;
  1215. }
  1216. // invoke static task.invoke
  1217. // need to try/catch error here, otherwise, the error in one event listener
  1218. // will break the executions of the other event listeners. Also error will
  1219. // not remove the event listener when `once` options is true.
  1220. var error;
  1221. try {
  1222. task.invoke(task, target, [event]);
  1223. }
  1224. catch (err) {
  1225. error = err;
  1226. }
  1227. var options = task.options;
  1228. if (options && typeof options === 'object' && options.once) {
  1229. // if options.once is true, after invoke once remove listener here
  1230. // only browser need to do this, nodejs eventEmitter will cal removeListener
  1231. // inside EventEmitter.once
  1232. var delegate_1 = task.originalDelegate ? task.originalDelegate : task.callback;
  1233. target[REMOVE_EVENT_LISTENER].call(target, event.type, delegate_1, options);
  1234. }
  1235. return error;
  1236. };
  1237. function globalCallback(context, event, isCapture) {
  1238. // https://github.com/angular/zone.js/issues/911, in IE, sometimes
  1239. // event will be undefined, so we need to use window.event
  1240. event = event || _global.event;
  1241. if (!event) {
  1242. return;
  1243. }
  1244. // event.target is needed for Samsung TV and SourceBuffer
  1245. // || global is needed https://github.com/angular/zone.js/issues/190
  1246. var target = context || event.target || _global;
  1247. var tasks = target[zoneSymbolEventNames[event.type][isCapture ? TRUE_STR : FALSE_STR]];
  1248. if (tasks) {
  1249. var errors = [];
  1250. // invoke all tasks which attached to current target with given event.type and capture = false
  1251. // for performance concern, if task.length === 1, just invoke
  1252. if (tasks.length === 1) {
  1253. var err = invokeTask(tasks[0], target, event);
  1254. err && errors.push(err);
  1255. }
  1256. else {
  1257. // https://github.com/angular/zone.js/issues/836
  1258. // copy the tasks array before invoke, to avoid
  1259. // the callback will remove itself or other listener
  1260. var copyTasks = tasks.slice();
  1261. for (var i = 0; i < copyTasks.length; i++) {
  1262. if (event && event[IMMEDIATE_PROPAGATION_SYMBOL] === true) {
  1263. break;
  1264. }
  1265. var err = invokeTask(copyTasks[i], target, event);
  1266. err && errors.push(err);
  1267. }
  1268. }
  1269. // Since there is only one error, we don't need to schedule microTask
  1270. // to throw the error.
  1271. if (errors.length === 1) {
  1272. throw errors[0];
  1273. }
  1274. else {
  1275. var _loop_1 = function (i) {
  1276. var err = errors[i];
  1277. api.nativeScheduleMicroTask(function () {
  1278. throw err;
  1279. });
  1280. };
  1281. for (var i = 0; i < errors.length; i++) {
  1282. _loop_1(i);
  1283. }
  1284. }
  1285. }
  1286. }
  1287. // global shared zoneAwareCallback to handle all event callback with capture = false
  1288. var globalZoneAwareCallback = function (event) {
  1289. return globalCallback(this, event, false);
  1290. };
  1291. // global shared zoneAwareCallback to handle all event callback with capture = true
  1292. var globalZoneAwareCaptureCallback = function (event) {
  1293. return globalCallback(this, event, true);
  1294. };
  1295. function patchEventTargetMethods(obj, patchOptions) {
  1296. if (!obj) {
  1297. return false;
  1298. }
  1299. var useGlobalCallback = true;
  1300. if (patchOptions && patchOptions.useG !== undefined) {
  1301. useGlobalCallback = patchOptions.useG;
  1302. }
  1303. var validateHandler = patchOptions && patchOptions.vh;
  1304. var checkDuplicate = true;
  1305. if (patchOptions && patchOptions.chkDup !== undefined) {
  1306. checkDuplicate = patchOptions.chkDup;
  1307. }
  1308. var returnTarget = false;
  1309. if (patchOptions && patchOptions.rt !== undefined) {
  1310. returnTarget = patchOptions.rt;
  1311. }
  1312. var proto = obj;
  1313. while (proto && !proto.hasOwnProperty(ADD_EVENT_LISTENER)) {
  1314. proto = ObjectGetPrototypeOf(proto);
  1315. }
  1316. if (!proto && obj[ADD_EVENT_LISTENER]) {
  1317. // somehow we did not find it, but we can see it. This happens on IE for Window properties.
  1318. proto = obj;
  1319. }
  1320. if (!proto) {
  1321. return false;
  1322. }
  1323. if (proto[zoneSymbolAddEventListener]) {
  1324. return false;
  1325. }
  1326. var eventNameToString = patchOptions && patchOptions.eventNameToString;
  1327. // a shared global taskData to pass data for scheduleEventTask
  1328. // so we do not need to create a new object just for pass some data
  1329. var taskData = {};
  1330. var nativeAddEventListener = proto[zoneSymbolAddEventListener] = proto[ADD_EVENT_LISTENER];
  1331. var nativeRemoveEventListener = proto[zoneSymbol(REMOVE_EVENT_LISTENER)] =
  1332. proto[REMOVE_EVENT_LISTENER];
  1333. var nativeListeners = proto[zoneSymbol(LISTENERS_EVENT_LISTENER)] =
  1334. proto[LISTENERS_EVENT_LISTENER];
  1335. var nativeRemoveAllListeners = proto[zoneSymbol(REMOVE_ALL_LISTENERS_EVENT_LISTENER)] =
  1336. proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER];
  1337. var nativePrependEventListener;
  1338. if (patchOptions && patchOptions.prepend) {
  1339. nativePrependEventListener = proto[zoneSymbol(patchOptions.prepend)] =
  1340. proto[patchOptions.prepend];
  1341. }
  1342. /**
  1343. * This util function will build an option object with passive option
  1344. * to handle all possible input from the user.
  1345. */
  1346. function buildEventListenerOptions(options, passive) {
  1347. if (!passiveSupported && typeof options === 'object' && options) {
  1348. // doesn't support passive but user want to pass an object as options.
  1349. // this will not work on some old browser, so we just pass a boolean
  1350. // as useCapture parameter
  1351. return !!options.capture;
  1352. }
  1353. if (!passiveSupported || !passive) {
  1354. return options;
  1355. }
  1356. if (typeof options === 'boolean') {
  1357. return { capture: options, passive: true };
  1358. }
  1359. if (!options) {
  1360. return { passive: true };
  1361. }
  1362. if (typeof options === 'object' && options.passive !== false) {
  1363. return __assign(__assign({}, options), { passive: true });
  1364. }
  1365. return options;
  1366. }
  1367. var customScheduleGlobal = function (task) {
  1368. // if there is already a task for the eventName + capture,
  1369. // just return, because we use the shared globalZoneAwareCallback here.
  1370. if (taskData.isExisting) {
  1371. return;
  1372. }
  1373. return nativeAddEventListener.call(taskData.target, taskData.eventName, taskData.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, taskData.options);
  1374. };
  1375. var customCancelGlobal = function (task) {
  1376. // if task is not marked as isRemoved, this call is directly
  1377. // from Zone.prototype.cancelTask, we should remove the task
  1378. // from tasksList of target first
  1379. if (!task.isRemoved) {
  1380. var symbolEventNames = zoneSymbolEventNames[task.eventName];
  1381. var symbolEventName = void 0;
  1382. if (symbolEventNames) {
  1383. symbolEventName = symbolEventNames[task.capture ? TRUE_STR : FALSE_STR];
  1384. }
  1385. var existingTasks = symbolEventName && task.target[symbolEventName];
  1386. if (existingTasks) {
  1387. for (var i = 0; i < existingTasks.length; i++) {
  1388. var existingTask = existingTasks[i];
  1389. if (existingTask === task) {
  1390. existingTasks.splice(i, 1);
  1391. // set isRemoved to data for faster invokeTask check
  1392. task.isRemoved = true;
  1393. if (existingTasks.length === 0) {
  1394. // all tasks for the eventName + capture have gone,
  1395. // remove globalZoneAwareCallback and remove the task cache from target
  1396. task.allRemoved = true;
  1397. task.target[symbolEventName] = null;
  1398. }
  1399. break;
  1400. }
  1401. }
  1402. }
  1403. }
  1404. // if all tasks for the eventName + capture have gone,
  1405. // we will really remove the global event callback,
  1406. // if not, return
  1407. if (!task.allRemoved) {
  1408. return;
  1409. }
  1410. return nativeRemoveEventListener.call(task.target, task.eventName, task.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, task.options);
  1411. };
  1412. var customScheduleNonGlobal = function (task) {
  1413. return nativeAddEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
  1414. };
  1415. var customSchedulePrepend = function (task) {
  1416. return nativePrependEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
  1417. };
  1418. var customCancelNonGlobal = function (task) {
  1419. return nativeRemoveEventListener.call(task.target, task.eventName, task.invoke, task.options);
  1420. };
  1421. var customSchedule = useGlobalCallback ? customScheduleGlobal : customScheduleNonGlobal;
  1422. var customCancel = useGlobalCallback ? customCancelGlobal : customCancelNonGlobal;
  1423. var compareTaskCallbackVsDelegate = function (task, delegate) {
  1424. var typeOfDelegate = typeof delegate;
  1425. return (typeOfDelegate === 'function' && task.callback === delegate) ||
  1426. (typeOfDelegate === 'object' && task.originalDelegate === delegate);
  1427. };
  1428. var compare = (patchOptions && patchOptions.diff) ? patchOptions.diff : compareTaskCallbackVsDelegate;
  1429. var unpatchedEvents = Zone[zoneSymbol('UNPATCHED_EVENTS')];
  1430. var passiveEvents = _global[zoneSymbol('PASSIVE_EVENTS')];
  1431. var makeAddListener = function (nativeListener, addSource, customScheduleFn, customCancelFn, returnTarget, prepend) {
  1432. if (returnTarget === void 0) { returnTarget = false; }
  1433. if (prepend === void 0) { prepend = false; }
  1434. return function () {
  1435. var target = this || _global;
  1436. var eventName = arguments[0];
  1437. if (patchOptions && patchOptions.transferEventName) {
  1438. eventName = patchOptions.transferEventName(eventName);
  1439. }
  1440. var delegate = arguments[1];
  1441. if (!delegate) {
  1442. return nativeListener.apply(this, arguments);
  1443. }
  1444. if (isNode && eventName === 'uncaughtException') {
  1445. // don't patch uncaughtException of nodejs to prevent endless loop
  1446. return nativeListener.apply(this, arguments);
  1447. }
  1448. // don't create the bind delegate function for handleEvent
  1449. // case here to improve addEventListener performance
  1450. // we will create the bind delegate when invoke
  1451. var isHandleEvent = false;
  1452. if (typeof delegate !== 'function') {
  1453. if (!delegate.handleEvent) {
  1454. return nativeListener.apply(this, arguments);
  1455. }
  1456. isHandleEvent = true;
  1457. }
  1458. if (validateHandler && !validateHandler(nativeListener, delegate, target, arguments)) {
  1459. return;
  1460. }
  1461. var passive = passiveSupported && !!passiveEvents && passiveEvents.indexOf(eventName) !== -1;
  1462. var options = buildEventListenerOptions(arguments[2], passive);
  1463. if (unpatchedEvents) {
  1464. // check unpatched list
  1465. for (var i = 0; i < unpatchedEvents.length; i++) {
  1466. if (eventName === unpatchedEvents[i]) {
  1467. if (passive) {
  1468. return nativeListener.call(target, eventName, delegate, options);
  1469. }
  1470. else {
  1471. return nativeListener.apply(this, arguments);
  1472. }
  1473. }
  1474. }
  1475. }
  1476. var capture = !options ? false : typeof options === 'boolean' ? true : options.capture;
  1477. var once = options && typeof options === 'object' ? options.once : false;
  1478. var zone = Zone.current;
  1479. var symbolEventNames = zoneSymbolEventNames[eventName];
  1480. if (!symbolEventNames) {
  1481. prepareEventNames(eventName, eventNameToString);
  1482. symbolEventNames = zoneSymbolEventNames[eventName];
  1483. }
  1484. var symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
  1485. var existingTasks = target[symbolEventName];
  1486. var isExisting = false;
  1487. if (existingTasks) {
  1488. // already have task registered
  1489. isExisting = true;
  1490. if (checkDuplicate) {
  1491. for (var i = 0; i < existingTasks.length; i++) {
  1492. if (compare(existingTasks[i], delegate)) {
  1493. // same callback, same capture, same event name, just return
  1494. return;
  1495. }
  1496. }
  1497. }
  1498. }
  1499. else {
  1500. existingTasks = target[symbolEventName] = [];
  1501. }
  1502. var source;
  1503. var constructorName = target.constructor['name'];
  1504. var targetSource = globalSources[constructorName];
  1505. if (targetSource) {
  1506. source = targetSource[eventName];
  1507. }
  1508. if (!source) {
  1509. source = constructorName + addSource +
  1510. (eventNameToString ? eventNameToString(eventName) : eventName);
  1511. }
  1512. // do not create a new object as task.data to pass those things
  1513. // just use the global shared one
  1514. taskData.options = options;
  1515. if (once) {
  1516. // if addEventListener with once options, we don't pass it to
  1517. // native addEventListener, instead we keep the once setting
  1518. // and handle ourselves.
  1519. taskData.options.once = false;
  1520. }
  1521. taskData.target = target;
  1522. taskData.capture = capture;
  1523. taskData.eventName = eventName;
  1524. taskData.isExisting = isExisting;
  1525. var data = useGlobalCallback ? OPTIMIZED_ZONE_EVENT_TASK_DATA : undefined;
  1526. // keep taskData into data to allow onScheduleEventTask to access the task information
  1527. if (data) {
  1528. data.taskData = taskData;
  1529. }
  1530. var task = zone.scheduleEventTask(source, delegate, data, customScheduleFn, customCancelFn);
  1531. // should clear taskData.target to avoid memory leak
  1532. // issue, https://github.com/angular/angular/issues/20442
  1533. taskData.target = null;
  1534. // need to clear up taskData because it is a global object
  1535. if (data) {
  1536. data.taskData = null;
  1537. }
  1538. // have to save those information to task in case
  1539. // application may call task.zone.cancelTask() directly
  1540. if (once) {
  1541. options.once = true;
  1542. }
  1543. if (!(!passiveSupported && typeof task.options === 'boolean')) {
  1544. // if not support passive, and we pass an option object
  1545. // to addEventListener, we should save the options to task
  1546. task.options = options;
  1547. }
  1548. task.target = target;
  1549. task.capture = capture;
  1550. task.eventName = eventName;
  1551. if (isHandleEvent) {
  1552. // save original delegate for compare to check duplicate
  1553. task.originalDelegate = delegate;
  1554. }
  1555. if (!prepend) {
  1556. existingTasks.push(task);
  1557. }
  1558. else {
  1559. existingTasks.unshift(task);
  1560. }
  1561. if (returnTarget) {
  1562. return target;
  1563. }
  1564. };
  1565. };
  1566. proto[ADD_EVENT_LISTENER] = makeAddListener(nativeAddEventListener, ADD_EVENT_LISTENER_SOURCE, customSchedule, customCancel, returnTarget);
  1567. if (nativePrependEventListener) {
  1568. proto[PREPEND_EVENT_LISTENER] = makeAddListener(nativePrependEventListener, PREPEND_EVENT_LISTENER_SOURCE, customSchedulePrepend, customCancel, returnTarget, true);
  1569. }
  1570. proto[REMOVE_EVENT_LISTENER] = function () {
  1571. var target = this || _global;
  1572. var eventName = arguments[0];
  1573. if (patchOptions && patchOptions.transferEventName) {
  1574. eventName = patchOptions.transferEventName(eventName);
  1575. }
  1576. var options = arguments[2];
  1577. var capture = !options ? false : typeof options === 'boolean' ? true : options.capture;
  1578. var delegate = arguments[1];
  1579. if (!delegate) {
  1580. return nativeRemoveEventListener.apply(this, arguments);
  1581. }
  1582. if (validateHandler &&
  1583. !validateHandler(nativeRemoveEventListener, delegate, target, arguments)) {
  1584. return;
  1585. }
  1586. var symbolEventNames = zoneSymbolEventNames[eventName];
  1587. var symbolEventName;
  1588. if (symbolEventNames) {
  1589. symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
  1590. }
  1591. var existingTasks = symbolEventName && target[symbolEventName];
  1592. if (existingTasks) {
  1593. for (var i = 0; i < existingTasks.length; i++) {
  1594. var existingTask = existingTasks[i];
  1595. if (compare(existingTask, delegate)) {
  1596. existingTasks.splice(i, 1);
  1597. // set isRemoved to data for faster invokeTask check
  1598. existingTask.isRemoved = true;
  1599. if (existingTasks.length === 0) {
  1600. // all tasks for the eventName + capture have gone,
  1601. // remove globalZoneAwareCallback and remove the task cache from target
  1602. existingTask.allRemoved = true;
  1603. target[symbolEventName] = null;
  1604. // in the target, we have an event listener which is added by on_property
  1605. // such as target.onclick = function() {}, so we need to clear this internal
  1606. // property too if all delegates all removed
  1607. if (typeof eventName === 'string') {
  1608. var onPropertySymbol = ZONE_SYMBOL_PREFIX + 'ON_PROPERTY' + eventName;
  1609. target[onPropertySymbol] = null;
  1610. }
  1611. }
  1612. existingTask.zone.cancelTask(existingTask);
  1613. if (returnTarget) {
  1614. return target;
  1615. }
  1616. return;
  1617. }
  1618. }
  1619. }
  1620. // issue 930, didn't find the event name or callback
  1621. // from zone kept existingTasks, the callback maybe
  1622. // added outside of zone, we need to call native removeEventListener
  1623. // to try to remove it.
  1624. return nativeRemoveEventListener.apply(this, arguments);
  1625. };
  1626. proto[LISTENERS_EVENT_LISTENER] = function () {
  1627. var target = this || _global;
  1628. var eventName = arguments[0];
  1629. if (patchOptions && patchOptions.transferEventName) {
  1630. eventName = patchOptions.transferEventName(eventName);
  1631. }
  1632. var listeners = [];
  1633. var tasks = findEventTasks(target, eventNameToString ? eventNameToString(eventName) : eventName);
  1634. for (var i = 0; i < tasks.length; i++) {
  1635. var task = tasks[i];
  1636. var delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  1637. listeners.push(delegate);
  1638. }
  1639. return listeners;
  1640. };
  1641. proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER] = function () {
  1642. var target = this || _global;
  1643. var eventName = arguments[0];
  1644. if (!eventName) {
  1645. var keys = Object.keys(target);
  1646. for (var i = 0; i < keys.length; i++) {
  1647. var prop = keys[i];
  1648. var match = EVENT_NAME_SYMBOL_REGX.exec(prop);
  1649. var evtName = match && match[1];
  1650. // in nodejs EventEmitter, removeListener event is
  1651. // used for monitoring the removeListener call,
  1652. // so just keep removeListener eventListener until
  1653. // all other eventListeners are removed
  1654. if (evtName && evtName !== 'removeListener') {
  1655. this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, evtName);
  1656. }
  1657. }
  1658. // remove removeListener listener finally
  1659. this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, 'removeListener');
  1660. }
  1661. else {
  1662. if (patchOptions && patchOptions.transferEventName) {
  1663. eventName = patchOptions.transferEventName(eventName);
  1664. }
  1665. var symbolEventNames = zoneSymbolEventNames[eventName];
  1666. if (symbolEventNames) {
  1667. var symbolEventName = symbolEventNames[FALSE_STR];
  1668. var symbolCaptureEventName = symbolEventNames[TRUE_STR];
  1669. var tasks = target[symbolEventName];
  1670. var captureTasks = target[symbolCaptureEventName];
  1671. if (tasks) {
  1672. var removeTasks = tasks.slice();
  1673. for (var i = 0; i < removeTasks.length; i++) {
  1674. var task = removeTasks[i];
  1675. var delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  1676. this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
  1677. }
  1678. }
  1679. if (captureTasks) {
  1680. var removeTasks = captureTasks.slice();
  1681. for (var i = 0; i < removeTasks.length; i++) {
  1682. var task = removeTasks[i];
  1683. var delegate = task.originalDelegate ? task.originalDelegate : task.callback;
  1684. this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
  1685. }
  1686. }
  1687. }
  1688. }
  1689. if (returnTarget) {
  1690. return this;
  1691. }
  1692. };
  1693. // for native toString patch
  1694. attachOriginToPatched(proto[ADD_EVENT_LISTENER], nativeAddEventListener);
  1695. attachOriginToPatched(proto[REMOVE_EVENT_LISTENER], nativeRemoveEventListener);
  1696. if (nativeRemoveAllListeners) {
  1697. attachOriginToPatched(proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER], nativeRemoveAllListeners);
  1698. }
  1699. if (nativeListeners) {
  1700. attachOriginToPatched(proto[LISTENERS_EVENT_LISTENER], nativeListeners);
  1701. }
  1702. return true;
  1703. }
  1704. var results = [];
  1705. for (var i = 0; i < apis.length; i++) {
  1706. results[i] = patchEventTargetMethods(apis[i], patchOptions);
  1707. }
  1708. return results;
  1709. }
  1710. function findEventTasks(target, eventName) {
  1711. if (!eventName) {
  1712. var foundTasks = [];
  1713. for (var prop in target) {
  1714. var match = EVENT_NAME_SYMBOL_REGX.exec(prop);
  1715. var evtName = match && match[1];
  1716. if (evtName && (!eventName || evtName === eventName)) {
  1717. var tasks = target[prop];
  1718. if (tasks) {
  1719. for (var i = 0; i < tasks.length; i++) {
  1720. foundTasks.push(tasks[i]);
  1721. }
  1722. }
  1723. }
  1724. }
  1725. return foundTasks;
  1726. }
  1727. var symbolEventName = zoneSymbolEventNames[eventName];
  1728. if (!symbolEventName) {
  1729. prepareEventNames(eventName);
  1730. symbolEventName = zoneSymbolEventNames[eventName];
  1731. }
  1732. var captureFalseTasks = target[symbolEventName[FALSE_STR]];
  1733. var captureTrueTasks = target[symbolEventName[TRUE_STR]];
  1734. if (!captureFalseTasks) {
  1735. return captureTrueTasks ? captureTrueTasks.slice() : [];
  1736. }
  1737. else {
  1738. return captureTrueTasks ? captureFalseTasks.concat(captureTrueTasks) :
  1739. captureFalseTasks.slice();
  1740. }
  1741. }
  1742. Zone.__load_patch('EventEmitter', function (global, Zone, api) {
  1743. // For EventEmitter
  1744. var EE_ADD_LISTENER = 'addListener';
  1745. var EE_PREPEND_LISTENER = 'prependListener';
  1746. var EE_REMOVE_LISTENER = 'removeListener';
  1747. var EE_REMOVE_ALL_LISTENER = 'removeAllListeners';
  1748. var EE_LISTENERS = 'listeners';
  1749. var EE_ON = 'on';
  1750. var EE_OFF = 'off';
  1751. var compareTaskCallbackVsDelegate = function (task, delegate) {
  1752. // same callback, same capture, same event name, just return
  1753. return task.callback === delegate || task.callback.listener === delegate;
  1754. };
  1755. var eventNameToString = function (eventName) {
  1756. if (typeof eventName === 'string') {
  1757. return eventName;
  1758. }
  1759. if (!eventName) {
  1760. return '';
  1761. }
  1762. return eventName.toString().replace('(', '_').replace(')', '_');
  1763. };
  1764. function patchEventEmitterMethods(obj) {
  1765. var result = patchEventTarget(global, api, [obj], {
  1766. useG: false,
  1767. add: EE_ADD_LISTENER,
  1768. rm: EE_REMOVE_LISTENER,
  1769. prepend: EE_PREPEND_LISTENER,
  1770. rmAll: EE_REMOVE_ALL_LISTENER,
  1771. listeners: EE_LISTENERS,
  1772. chkDup: false,
  1773. rt: true,
  1774. diff: compareTaskCallbackVsDelegate,
  1775. eventNameToString: eventNameToString
  1776. });
  1777. if (result && result[0]) {
  1778. obj[EE_ON] = obj[EE_ADD_LISTENER];
  1779. obj[EE_OFF] = obj[EE_REMOVE_LISTENER];
  1780. }
  1781. }
  1782. // EventEmitter
  1783. var events;
  1784. try {
  1785. events = require('events');
  1786. }
  1787. catch (err) {
  1788. }
  1789. if (events && events.EventEmitter) {
  1790. patchEventEmitterMethods(events.EventEmitter.prototype);
  1791. }
  1792. });
  1793. Zone.__load_patch('fs', function () {
  1794. var fs;
  1795. try {
  1796. fs = require('fs');
  1797. }
  1798. catch (err) {
  1799. }
  1800. // watch, watchFile, unwatchFile has been patched
  1801. // because EventEmitter has been patched
  1802. var TO_PATCH_MACROTASK_METHODS = [
  1803. 'access', 'appendFile', 'chmod', 'chown', 'close', 'exists', 'fchmod',
  1804. 'fchown', 'fdatasync', 'fstat', 'fsync', 'ftruncate', 'futimes', 'lchmod',
  1805. 'lchown', 'link', 'lstat', 'mkdir', 'mkdtemp', 'open', 'read',
  1806. 'readdir', 'readFile', 'readlink', 'realpath', 'rename', 'rmdir', 'stat',
  1807. 'symlink', 'truncate', 'unlink', 'utimes', 'write', 'writeFile',
  1808. ];
  1809. if (fs) {
  1810. TO_PATCH_MACROTASK_METHODS.filter(function (name) { return !!fs[name] && typeof fs[name] === 'function'; })
  1811. .forEach(function (name) {
  1812. patchMacroTask(fs, name, function (self, args) {
  1813. return {
  1814. name: 'fs.' + name,
  1815. args: args,
  1816. cbIdx: args.length > 0 ? args.length - 1 : -1,
  1817. target: self
  1818. };
  1819. });
  1820. });
  1821. }
  1822. });
  1823. /**
  1824. * @fileoverview
  1825. * @suppress {missingRequire}
  1826. */
  1827. var taskSymbol = zoneSymbol('zoneTask');
  1828. function patchTimer(window, setName, cancelName, nameSuffix) {
  1829. var setNative = null;
  1830. var clearNative = null;
  1831. setName += nameSuffix;
  1832. cancelName += nameSuffix;
  1833. var tasksByHandleId = {};
  1834. function scheduleTask(task) {
  1835. var data = task.data;
  1836. data.args[0] = function () {
  1837. return task.invoke.apply(this, arguments);
  1838. };
  1839. data.handleId = setNative.apply(window, data.args);
  1840. return task;
  1841. }
  1842. function clearTask(task) {
  1843. return clearNative.call(window, task.data.handleId);
  1844. }
  1845. setNative =
  1846. patchMethod(window, setName, function (delegate) { return function (self, args) {
  1847. if (typeof args[0] === 'function') {
  1848. var options_1 = {
  1849. isPeriodic: nameSuffix === 'Interval',
  1850. delay: (nameSuffix === 'Timeout' || nameSuffix === 'Interval') ? args[1] || 0 :
  1851. undefined,
  1852. args: args
  1853. };
  1854. var callback_1 = args[0];
  1855. args[0] = function timer() {
  1856. try {
  1857. return callback_1.apply(this, arguments);
  1858. }
  1859. finally {
  1860. // issue-934, task will be cancelled
  1861. // even it is a periodic task such as
  1862. // setInterval
  1863. // https://github.com/angular/angular/issues/40387
  1864. // Cleanup tasksByHandleId should be handled before scheduleTask
  1865. // Since some zoneSpec may intercept and doesn't trigger
  1866. // scheduleFn(scheduleTask) provided here.
  1867. if (!(options_1.isPeriodic)) {
  1868. if (typeof options_1.handleId === 'number') {
  1869. // in non-nodejs env, we remove timerId
  1870. // from local cache
  1871. delete tasksByHandleId[options_1.handleId];
  1872. }
  1873. else if (options_1.handleId) {
  1874. // Node returns complex objects as handleIds
  1875. // we remove task reference from timer object
  1876. options_1.handleId[taskSymbol] = null;
  1877. }
  1878. }
  1879. }
  1880. };
  1881. var task = scheduleMacroTaskWithCurrentZone(setName, args[0], options_1, scheduleTask, clearTask);
  1882. if (!task) {
  1883. return task;
  1884. }
  1885. // Node.js must additionally support the ref and unref functions.
  1886. var handle = task.data.handleId;
  1887. if (typeof handle === 'number') {
  1888. // for non nodejs env, we save handleId: task
  1889. // mapping in local cache for clearTimeout
  1890. tasksByHandleId[handle] = task;
  1891. }
  1892. else if (handle) {
  1893. // for nodejs env, we save task
  1894. // reference in timerId Object for clearTimeout
  1895. handle[taskSymbol] = task;
  1896. }
  1897. // check whether handle is null, because some polyfill or browser
  1898. // may return undefined from setTimeout/setInterval/setImmediate/requestAnimationFrame
  1899. if (handle && handle.ref && handle.unref && typeof handle.ref === 'function' &&
  1900. typeof handle.unref === 'function') {
  1901. task.ref = handle.ref.bind(handle);
  1902. task.unref = handle.unref.bind(handle);
  1903. }
  1904. if (typeof handle === 'number' || handle) {
  1905. return handle;
  1906. }
  1907. return task;
  1908. }
  1909. else {
  1910. // cause an error by calling it directly.
  1911. return delegate.apply(window, args);
  1912. }
  1913. }; });
  1914. clearNative =
  1915. patchMethod(window, cancelName, function (delegate) { return function (self, args) {
  1916. var id = args[0];
  1917. var task;
  1918. if (typeof id === 'number') {
  1919. // non nodejs env.
  1920. task = tasksByHandleId[id];
  1921. }
  1922. else {
  1923. // nodejs env.
  1924. task = id && id[taskSymbol];
  1925. // other environments.
  1926. if (!task) {
  1927. task = id;
  1928. }
  1929. }
  1930. if (task && typeof task.type === 'string') {
  1931. if (task.state !== 'notScheduled' &&
  1932. (task.cancelFn && task.data.isPeriodic || task.runCount === 0)) {
  1933. if (typeof id === 'number') {
  1934. delete tasksByHandleId[id];
  1935. }
  1936. else if (id) {
  1937. id[taskSymbol] = null;
  1938. }
  1939. // Do not cancel already canceled functions
  1940. task.zone.cancelTask(task);
  1941. }
  1942. }
  1943. else {
  1944. // cause an error by calling it directly.
  1945. delegate.apply(window, args);
  1946. }
  1947. }; });
  1948. }
  1949. var set = 'set';
  1950. var clear = 'clear';
  1951. Zone.__load_patch('node_timers', function (global, Zone) {
  1952. // Timers
  1953. var globalUseTimeoutFromTimer = false;
  1954. try {
  1955. var timers = require('timers');
  1956. var globalEqualTimersTimeout = global.setTimeout === timers.setTimeout;
  1957. if (!globalEqualTimersTimeout && !isMix) {
  1958. // 1. if isMix, then we are in mix environment such as Electron
  1959. // we should only patch timers.setTimeout because global.setTimeout
  1960. // have been patched
  1961. // 2. if global.setTimeout not equal timers.setTimeout, check
  1962. // whether global.setTimeout use timers.setTimeout or not
  1963. var originSetTimeout_1 = timers.setTimeout;
  1964. timers.setTimeout = function () {
  1965. globalUseTimeoutFromTimer = true;
  1966. return originSetTimeout_1.apply(this, arguments);
  1967. };
  1968. var detectTimeout = global.setTimeout(function () { }, 100);
  1969. clearTimeout(detectTimeout);
  1970. timers.setTimeout = originSetTimeout_1;
  1971. }
  1972. patchTimer(timers, set, clear, 'Timeout');
  1973. patchTimer(timers, set, clear, 'Interval');
  1974. patchTimer(timers, set, clear, 'Immediate');
  1975. }
  1976. catch (error) {
  1977. // timers module not exists, for example, when we using nativeScript
  1978. // timers is not available
  1979. }
  1980. if (isMix) {
  1981. // if we are in mix environment, such as Electron,
  1982. // the global.setTimeout has already been patched,
  1983. // so we just patch timers.setTimeout
  1984. return;
  1985. }
  1986. if (!globalUseTimeoutFromTimer) {
  1987. // 1. global setTimeout equals timers setTimeout
  1988. // 2. or global don't use timers setTimeout(maybe some other library patch setTimeout)
  1989. // 3. or load timers module error happens, we should patch global setTimeout
  1990. patchTimer(global, set, clear, 'Timeout');
  1991. patchTimer(global, set, clear, 'Interval');
  1992. patchTimer(global, set, clear, 'Immediate');
  1993. }
  1994. else {
  1995. // global use timers setTimeout, but not equals
  1996. // this happens when use nodejs v0.10.x, global setTimeout will
  1997. // use a lazy load version of timers setTimeout
  1998. // we should not double patch timer's setTimeout
  1999. // so we only store the __symbol__ for consistency
  2000. global[Zone.__symbol__('setTimeout')] = global.setTimeout;
  2001. global[Zone.__symbol__('setInterval')] = global.setInterval;
  2002. global[Zone.__symbol__('setImmediate')] = global.setImmediate;
  2003. }
  2004. });
  2005. // patch process related methods
  2006. Zone.__load_patch('nextTick', function () {
  2007. // patch nextTick as microTask
  2008. patchMicroTask(process, 'nextTick', function (self, args) {
  2009. return {
  2010. name: 'process.nextTick',
  2011. args: args,
  2012. cbIdx: (args.length > 0 && typeof args[0] === 'function') ? 0 : -1,
  2013. target: process
  2014. };
  2015. });
  2016. });
  2017. Zone.__load_patch('handleUnhandledPromiseRejection', function (global, Zone, api) {
  2018. Zone[api.symbol('unhandledPromiseRejectionHandler')] =
  2019. findProcessPromiseRejectionHandler('unhandledRejection');
  2020. Zone[api.symbol('rejectionHandledHandler')] =
  2021. findProcessPromiseRejectionHandler('rejectionHandled');
  2022. // handle unhandled promise rejection
  2023. function findProcessPromiseRejectionHandler(evtName) {
  2024. return function (e) {
  2025. var eventTasks = findEventTasks(process, evtName);
  2026. eventTasks.forEach(function (eventTask) {
  2027. // process has added unhandledrejection event listener
  2028. // trigger the event listener
  2029. if (evtName === 'unhandledRejection') {
  2030. eventTask.invoke(e.rejection, e.promise);
  2031. }
  2032. else if (evtName === 'rejectionHandled') {
  2033. eventTask.invoke(e.promise);
  2034. }
  2035. });
  2036. };
  2037. }
  2038. });
  2039. // Crypto
  2040. Zone.__load_patch('crypto', function () {
  2041. var crypto;
  2042. try {
  2043. crypto = require('crypto');
  2044. }
  2045. catch (err) {
  2046. }
  2047. // use the generic patchMacroTask to patch crypto
  2048. if (crypto) {
  2049. var methodNames = ['randomBytes', 'pbkdf2'];
  2050. methodNames.forEach(function (name) {
  2051. patchMacroTask(crypto, name, function (self, args) {
  2052. return {
  2053. name: 'crypto.' + name,
  2054. args: args,
  2055. cbIdx: (args.length > 0 && typeof args[args.length - 1] === 'function') ?
  2056. args.length - 1 :
  2057. -1,
  2058. target: crypto
  2059. };
  2060. });
  2061. });
  2062. }
  2063. });
  2064. Zone.__load_patch('console', function (global, Zone) {
  2065. var consoleMethods = ['dir', 'log', 'info', 'error', 'warn', 'assert', 'debug', 'timeEnd', 'trace'];
  2066. consoleMethods.forEach(function (m) {
  2067. var originalMethod = console[Zone.__symbol__(m)] = console[m];
  2068. if (originalMethod) {
  2069. console[m] = function () {
  2070. var args = ArraySlice.call(arguments);
  2071. if (Zone.current === Zone.root) {
  2072. return originalMethod.apply(this, args);
  2073. }
  2074. else {
  2075. return Zone.root.run(originalMethod, this, args);
  2076. }
  2077. };
  2078. }
  2079. });
  2080. });
  2081. /**
  2082. * @fileoverview
  2083. * @suppress {globalThis}
  2084. */
  2085. var NEWLINE = '\n';
  2086. var IGNORE_FRAMES = {};
  2087. var creationTrace = '__creationTrace__';
  2088. var ERROR_TAG = 'STACKTRACE TRACKING';
  2089. var SEP_TAG = '__SEP_TAG__';
  2090. var sepTemplate = SEP_TAG + '@[native]';
  2091. var LongStackTrace = /** @class */ (function () {
  2092. function LongStackTrace() {
  2093. this.error = getStacktrace();
  2094. this.timestamp = new Date();
  2095. }
  2096. return LongStackTrace;
  2097. }());
  2098. function getStacktraceWithUncaughtError() {
  2099. return new Error(ERROR_TAG);
  2100. }
  2101. function getStacktraceWithCaughtError() {
  2102. try {
  2103. throw getStacktraceWithUncaughtError();
  2104. }
  2105. catch (err) {
  2106. return err;
  2107. }
  2108. }
  2109. // Some implementations of exception handling don't create a stack trace if the exception
  2110. // isn't thrown, however it's faster not to actually throw the exception.
  2111. var error = getStacktraceWithUncaughtError();
  2112. var caughtError = getStacktraceWithCaughtError();
  2113. var getStacktrace = error.stack ?
  2114. getStacktraceWithUncaughtError :
  2115. (caughtError.stack ? getStacktraceWithCaughtError : getStacktraceWithUncaughtError);
  2116. function getFrames(error) {
  2117. return error.stack ? error.stack.split(NEWLINE) : [];
  2118. }
  2119. function addErrorStack(lines, error) {
  2120. var trace = getFrames(error);
  2121. for (var i = 0; i < trace.length; i++) {
  2122. var frame = trace[i];
  2123. // Filter out the Frames which are part of stack capturing.
  2124. if (!IGNORE_FRAMES.hasOwnProperty(frame)) {
  2125. lines.push(trace[i]);
  2126. }
  2127. }
  2128. }
  2129. function renderLongStackTrace(frames, stack) {
  2130. var longTrace = [stack ? stack.trim() : ''];
  2131. if (frames) {
  2132. var timestamp = new Date().getTime();
  2133. for (var i = 0; i < frames.length; i++) {
  2134. var traceFrames = frames[i];
  2135. var lastTime = traceFrames.timestamp;
  2136. var separator = "____________________Elapsed ".concat(timestamp - lastTime.getTime(), " ms; At: ").concat(lastTime);
  2137. separator = separator.replace(/[^\w\d]/g, '_');
  2138. longTrace.push(sepTemplate.replace(SEP_TAG, separator));
  2139. addErrorStack(longTrace, traceFrames.error);
  2140. timestamp = lastTime.getTime();
  2141. }
  2142. }
  2143. return longTrace.join(NEWLINE);
  2144. }
  2145. // if Error.stackTraceLimit is 0, means stack trace
  2146. // is disabled, so we don't need to generate long stack trace
  2147. // this will improve performance in some test(some test will
  2148. // set stackTraceLimit to 0, https://github.com/angular/zone.js/issues/698
  2149. function stackTracesEnabled() {
  2150. // Cast through any since this property only exists on Error in the nodejs
  2151. // typings.
  2152. return Error.stackTraceLimit > 0;
  2153. }
  2154. Zone['longStackTraceZoneSpec'] = {
  2155. name: 'long-stack-trace',
  2156. longStackTraceLimit: 10,
  2157. // add a getLongStackTrace method in spec to
  2158. // handle handled reject promise error.
  2159. getLongStackTrace: function (error) {
  2160. if (!error) {
  2161. return undefined;
  2162. }
  2163. var trace = error[Zone.__symbol__('currentTaskTrace')];
  2164. if (!trace) {
  2165. return error.stack;
  2166. }
  2167. return renderLongStackTrace(trace, error.stack);
  2168. },
  2169. onScheduleTask: function (parentZoneDelegate, currentZone, targetZone, task) {
  2170. if (stackTracesEnabled()) {
  2171. var currentTask = Zone.currentTask;
  2172. var trace = currentTask && currentTask.data && currentTask.data[creationTrace] || [];
  2173. trace = [new LongStackTrace()].concat(trace);
  2174. if (trace.length > this.longStackTraceLimit) {
  2175. trace.length = this.longStackTraceLimit;
  2176. }
  2177. if (!task.data)
  2178. task.data = {};
  2179. if (task.type === 'eventTask') {
  2180. // Fix issue https://github.com/angular/zone.js/issues/1195,
  2181. // For event task of browser, by default, all task will share a
  2182. // singleton instance of data object, we should create a new one here
  2183. // The cast to `any` is required to workaround a closure bug which wrongly applies
  2184. // URL sanitization rules to .data access.
  2185. task.data = __assign({}, task.data);
  2186. }
  2187. task.data[creationTrace] = trace;
  2188. }
  2189. return parentZoneDelegate.scheduleTask(targetZone, task);
  2190. },
  2191. onHandleError: function (parentZoneDelegate, currentZone, targetZone, error) {
  2192. if (stackTracesEnabled()) {
  2193. var parentTask = Zone.currentTask || error.task;
  2194. if (error instanceof Error && parentTask) {
  2195. var longStack = renderLongStackTrace(parentTask.data && parentTask.data[creationTrace], error.stack);
  2196. try {
  2197. error.stack = error.longStack = longStack;
  2198. }
  2199. catch (err) {
  2200. }
  2201. }
  2202. }
  2203. return parentZoneDelegate.handleError(targetZone, error);
  2204. }
  2205. };
  2206. function captureStackTraces(stackTraces, count) {
  2207. if (count > 0) {
  2208. stackTraces.push(getFrames((new LongStackTrace()).error));
  2209. captureStackTraces(stackTraces, count - 1);
  2210. }
  2211. }
  2212. function computeIgnoreFrames() {
  2213. if (!stackTracesEnabled()) {
  2214. return;
  2215. }
  2216. var frames = [];
  2217. captureStackTraces(frames, 2);
  2218. var frames1 = frames[0];
  2219. var frames2 = frames[1];
  2220. for (var i = 0; i < frames1.length; i++) {
  2221. var frame1 = frames1[i];
  2222. if (frame1.indexOf(ERROR_TAG) == -1) {
  2223. var match = frame1.match(/^\s*at\s+/);
  2224. if (match) {
  2225. sepTemplate = match[0] + SEP_TAG + ' (http://localhost)';
  2226. break;
  2227. }
  2228. }
  2229. }
  2230. for (var i = 0; i < frames1.length; i++) {
  2231. var frame1 = frames1[i];
  2232. var frame2 = frames2[i];
  2233. if (frame1 === frame2) {
  2234. IGNORE_FRAMES[frame1] = true;
  2235. }
  2236. else {
  2237. break;
  2238. }
  2239. }
  2240. }
  2241. computeIgnoreFrames();
  2242. var ProxyZoneSpec = /** @class */ (function () {
  2243. function ProxyZoneSpec(defaultSpecDelegate) {
  2244. if (defaultSpecDelegate === void 0) { defaultSpecDelegate = null; }
  2245. this.defaultSpecDelegate = defaultSpecDelegate;
  2246. this.name = 'ProxyZone';
  2247. this._delegateSpec = null;
  2248. this.properties = { 'ProxyZoneSpec': this };
  2249. this.propertyKeys = null;
  2250. this.lastTaskState = null;
  2251. this.isNeedToTriggerHasTask = false;
  2252. this.tasks = [];
  2253. this.setDelegate(defaultSpecDelegate);
  2254. }
  2255. ProxyZoneSpec.get = function () {
  2256. return Zone.current.get('ProxyZoneSpec');
  2257. };
  2258. ProxyZoneSpec.isLoaded = function () {
  2259. return ProxyZoneSpec.get() instanceof ProxyZoneSpec;
  2260. };
  2261. ProxyZoneSpec.assertPresent = function () {
  2262. if (!ProxyZoneSpec.isLoaded()) {
  2263. throw new Error("Expected to be running in 'ProxyZone', but it was not found.");
  2264. }
  2265. return ProxyZoneSpec.get();
  2266. };
  2267. ProxyZoneSpec.prototype.setDelegate = function (delegateSpec) {
  2268. var _this = this;
  2269. var isNewDelegate = this._delegateSpec !== delegateSpec;
  2270. this._delegateSpec = delegateSpec;
  2271. this.propertyKeys && this.propertyKeys.forEach(function (key) { return delete _this.properties[key]; });
  2272. this.propertyKeys = null;
  2273. if (delegateSpec && delegateSpec.properties) {
  2274. this.propertyKeys = Object.keys(delegateSpec.properties);
  2275. this.propertyKeys.forEach(function (k) { return _this.properties[k] = delegateSpec.properties[k]; });
  2276. }
  2277. // if a new delegateSpec was set, check if we need to trigger hasTask
  2278. if (isNewDelegate && this.lastTaskState &&
  2279. (this.lastTaskState.macroTask || this.lastTaskState.microTask)) {
  2280. this.isNeedToTriggerHasTask = true;
  2281. }
  2282. };
  2283. ProxyZoneSpec.prototype.getDelegate = function () {
  2284. return this._delegateSpec;
  2285. };
  2286. ProxyZoneSpec.prototype.resetDelegate = function () {
  2287. this.getDelegate();
  2288. this.setDelegate(this.defaultSpecDelegate);
  2289. };
  2290. ProxyZoneSpec.prototype.tryTriggerHasTask = function (parentZoneDelegate, currentZone, targetZone) {
  2291. if (this.isNeedToTriggerHasTask && this.lastTaskState) {
  2292. // last delegateSpec has microTask or macroTask
  2293. // should call onHasTask in current delegateSpec
  2294. this.isNeedToTriggerHasTask = false;
  2295. this.onHasTask(parentZoneDelegate, currentZone, targetZone, this.lastTaskState);
  2296. }
  2297. };
  2298. ProxyZoneSpec.prototype.removeFromTasks = function (task) {
  2299. if (!this.tasks) {
  2300. return;
  2301. }
  2302. for (var i = 0; i < this.tasks.length; i++) {
  2303. if (this.tasks[i] === task) {
  2304. this.tasks.splice(i, 1);
  2305. return;
  2306. }
  2307. }
  2308. };
  2309. ProxyZoneSpec.prototype.getAndClearPendingTasksInfo = function () {
  2310. if (this.tasks.length === 0) {
  2311. return '';
  2312. }
  2313. var taskInfo = this.tasks.map(function (task) {
  2314. var dataInfo = task.data &&
  2315. Object.keys(task.data)
  2316. .map(function (key) {
  2317. return key + ':' + task.data[key];
  2318. })
  2319. .join(',');
  2320. return "type: ".concat(task.type, ", source: ").concat(task.source, ", args: {").concat(dataInfo, "}");
  2321. });
  2322. var pendingTasksInfo = '--Pending async tasks are: [' + taskInfo + ']';
  2323. // clear tasks
  2324. this.tasks = [];
  2325. return pendingTasksInfo;
  2326. };
  2327. ProxyZoneSpec.prototype.onFork = function (parentZoneDelegate, currentZone, targetZone, zoneSpec) {
  2328. if (this._delegateSpec && this._delegateSpec.onFork) {
  2329. return this._delegateSpec.onFork(parentZoneDelegate, currentZone, targetZone, zoneSpec);
  2330. }
  2331. else {
  2332. return parentZoneDelegate.fork(targetZone, zoneSpec);
  2333. }
  2334. };
  2335. ProxyZoneSpec.prototype.onIntercept = function (parentZoneDelegate, currentZone, targetZone, delegate, source) {
  2336. if (this._delegateSpec && this._delegateSpec.onIntercept) {
  2337. return this._delegateSpec.onIntercept(parentZoneDelegate, currentZone, targetZone, delegate, source);
  2338. }
  2339. else {
  2340. return parentZoneDelegate.intercept(targetZone, delegate, source);
  2341. }
  2342. };
  2343. ProxyZoneSpec.prototype.onInvoke = function (parentZoneDelegate, currentZone, targetZone, delegate, applyThis, applyArgs, source) {
  2344. this.tryTriggerHasTask(parentZoneDelegate, currentZone, targetZone);
  2345. if (this._delegateSpec && this._delegateSpec.onInvoke) {
  2346. return this._delegateSpec.onInvoke(parentZoneDelegate, currentZone, targetZone, delegate, applyThis, applyArgs, source);
  2347. }
  2348. else {
  2349. return parentZoneDelegate.invoke(targetZone, delegate, applyThis, applyArgs, source);
  2350. }
  2351. };
  2352. ProxyZoneSpec.prototype.onHandleError = function (parentZoneDelegate, currentZone, targetZone, error) {
  2353. if (this._delegateSpec && this._delegateSpec.onHandleError) {
  2354. return this._delegateSpec.onHandleError(parentZoneDelegate, currentZone, targetZone, error);
  2355. }
  2356. else {
  2357. return parentZoneDelegate.handleError(targetZone, error);
  2358. }
  2359. };
  2360. ProxyZoneSpec.prototype.onScheduleTask = function (parentZoneDelegate, currentZone, targetZone, task) {
  2361. if (task.type !== 'eventTask') {
  2362. this.tasks.push(task);
  2363. }
  2364. if (this._delegateSpec && this._delegateSpec.onScheduleTask) {
  2365. return this._delegateSpec.onScheduleTask(parentZoneDelegate, currentZone, targetZone, task);
  2366. }
  2367. else {
  2368. return parentZoneDelegate.scheduleTask(targetZone, task);
  2369. }
  2370. };
  2371. ProxyZoneSpec.prototype.onInvokeTask = function (parentZoneDelegate, currentZone, targetZone, task, applyThis, applyArgs) {
  2372. if (task.type !== 'eventTask') {
  2373. this.removeFromTasks(task);
  2374. }
  2375. this.tryTriggerHasTask(parentZoneDelegate, currentZone, targetZone);
  2376. if (this._delegateSpec && this._delegateSpec.onInvokeTask) {
  2377. return this._delegateSpec.onInvokeTask(parentZoneDelegate, currentZone, targetZone, task, applyThis, applyArgs);
  2378. }
  2379. else {
  2380. return parentZoneDelegate.invokeTask(targetZone, task, applyThis, applyArgs);
  2381. }
  2382. };
  2383. ProxyZoneSpec.prototype.onCancelTask = function (parentZoneDelegate, currentZone, targetZone, task) {
  2384. if (task.type !== 'eventTask') {
  2385. this.removeFromTasks(task);
  2386. }
  2387. this.tryTriggerHasTask(parentZoneDelegate, currentZone, targetZone);
  2388. if (this._delegateSpec && this._delegateSpec.onCancelTask) {
  2389. return this._delegateSpec.onCancelTask(parentZoneDelegate, currentZone, targetZone, task);
  2390. }
  2391. else {
  2392. return parentZoneDelegate.cancelTask(targetZone, task);
  2393. }
  2394. };
  2395. ProxyZoneSpec.prototype.onHasTask = function (delegate, current, target, hasTaskState) {
  2396. this.lastTaskState = hasTaskState;
  2397. if (this._delegateSpec && this._delegateSpec.onHasTask) {
  2398. this._delegateSpec.onHasTask(delegate, current, target, hasTaskState);
  2399. }
  2400. else {
  2401. delegate.hasTask(target, hasTaskState);
  2402. }
  2403. };
  2404. return ProxyZoneSpec;
  2405. }());
  2406. // Export the class so that new instances can be created with proper
  2407. // constructor params.
  2408. Zone['ProxyZoneSpec'] = ProxyZoneSpec;
  2409. var SyncTestZoneSpec = /** @class */ (function () {
  2410. function SyncTestZoneSpec(namePrefix) {
  2411. this.runZone = Zone.current;
  2412. this.name = 'syncTestZone for ' + namePrefix;
  2413. }
  2414. SyncTestZoneSpec.prototype.onScheduleTask = function (delegate, current, target, task) {
  2415. switch (task.type) {
  2416. case 'microTask':
  2417. case 'macroTask':
  2418. throw new Error("Cannot call ".concat(task.source, " from within a sync test (").concat(this.name, ")."));
  2419. case 'eventTask':
  2420. task = delegate.scheduleTask(target, task);
  2421. break;
  2422. }
  2423. return task;
  2424. };
  2425. return SyncTestZoneSpec;
  2426. }());
  2427. // Export the class so that new instances can be created with proper
  2428. // constructor params.
  2429. Zone['SyncTestZoneSpec'] = SyncTestZoneSpec;
  2430. /// <reference types="jasmine"/>
  2431. Zone.__load_patch('jasmine', function (global, Zone, api) {
  2432. var __extends = function (d, b) {
  2433. for (var p in b)
  2434. if (b.hasOwnProperty(p))
  2435. d[p] = b[p];
  2436. function __() {
  2437. this.constructor = d;
  2438. }
  2439. d.prototype = b === null ? Object.create(b) : ((__.prototype = b.prototype), new __());
  2440. };
  2441. // Patch jasmine's describe/it/beforeEach/afterEach functions so test code always runs
  2442. // in a testZone (ProxyZone). (See: angular/zone.js#91 & angular/angular#10503)
  2443. if (!Zone)
  2444. throw new Error('Missing: zone.js');
  2445. if (typeof jest !== 'undefined') {
  2446. // return if jasmine is a light implementation inside jest
  2447. // in this case, we are running inside jest not jasmine
  2448. return;
  2449. }
  2450. if (typeof jasmine == 'undefined' || jasmine['__zone_patch__']) {
  2451. return;
  2452. }
  2453. jasmine['__zone_patch__'] = true;
  2454. var SyncTestZoneSpec = Zone['SyncTestZoneSpec'];
  2455. var ProxyZoneSpec = Zone['ProxyZoneSpec'];
  2456. if (!SyncTestZoneSpec)
  2457. throw new Error('Missing: SyncTestZoneSpec');
  2458. if (!ProxyZoneSpec)
  2459. throw new Error('Missing: ProxyZoneSpec');
  2460. var ambientZone = Zone.current;
  2461. var symbol = Zone.__symbol__;
  2462. // whether patch jasmine clock when in fakeAsync
  2463. var disablePatchingJasmineClock = global[symbol('fakeAsyncDisablePatchingClock')] === true;
  2464. // the original variable name fakeAsyncPatchLock is not accurate, so the name will be
  2465. // fakeAsyncAutoFakeAsyncWhenClockPatched and if this enablePatchingJasmineClock is false, we also
  2466. // automatically disable the auto jump into fakeAsync feature
  2467. var enableAutoFakeAsyncWhenClockPatched = !disablePatchingJasmineClock &&
  2468. ((global[symbol('fakeAsyncPatchLock')] === true) ||
  2469. (global[symbol('fakeAsyncAutoFakeAsyncWhenClockPatched')] === true));
  2470. var ignoreUnhandledRejection = global[symbol('ignoreUnhandledRejection')] === true;
  2471. if (!ignoreUnhandledRejection) {
  2472. var globalErrors_1 = jasmine.GlobalErrors;
  2473. if (globalErrors_1 && !jasmine[symbol('GlobalErrors')]) {
  2474. jasmine[symbol('GlobalErrors')] = globalErrors_1;
  2475. jasmine.GlobalErrors = function () {
  2476. var instance = new globalErrors_1();
  2477. var originalInstall = instance.install;
  2478. if (originalInstall && !instance[symbol('install')]) {
  2479. instance[symbol('install')] = originalInstall;
  2480. instance.install = function () {
  2481. var isNode = typeof process !== 'undefined' && !!process.on;
  2482. // Note: Jasmine checks internally if `process` and `process.on` is defined. Otherwise,
  2483. // it installs the browser rejection handler through the `global.addEventListener`.
  2484. // This code may be run in the browser environment where `process` is not defined, and
  2485. // this will lead to a runtime exception since Webpack 5 removed automatic Node.js
  2486. // polyfills. Note, that events are named differently, it's `unhandledRejection` in
  2487. // Node.js and `unhandledrejection` in the browser.
  2488. var originalHandlers = isNode ? process.listeners('unhandledRejection') :
  2489. global.eventListeners('unhandledrejection');
  2490. var result = originalInstall.apply(this, arguments);
  2491. isNode ? process.removeAllListeners('unhandledRejection') :
  2492. global.removeAllListeners('unhandledrejection');
  2493. if (originalHandlers) {
  2494. originalHandlers.forEach(function (handler) {
  2495. if (isNode) {
  2496. process.on('unhandledRejection', handler);
  2497. }
  2498. else {
  2499. global.addEventListener('unhandledrejection', handler);
  2500. }
  2501. });
  2502. }
  2503. return result;
  2504. };
  2505. }
  2506. return instance;
  2507. };
  2508. }
  2509. }
  2510. // Monkey patch all of the jasmine DSL so that each function runs in appropriate zone.
  2511. var jasmineEnv = jasmine.getEnv();
  2512. ['describe', 'xdescribe', 'fdescribe'].forEach(function (methodName) {
  2513. var originalJasmineFn = jasmineEnv[methodName];
  2514. jasmineEnv[methodName] = function (description, specDefinitions) {
  2515. return originalJasmineFn.call(this, description, wrapDescribeInZone(description, specDefinitions));
  2516. };
  2517. });
  2518. ['it', 'xit', 'fit'].forEach(function (methodName) {
  2519. var originalJasmineFn = jasmineEnv[methodName];
  2520. jasmineEnv[symbol(methodName)] = originalJasmineFn;
  2521. jasmineEnv[methodName] = function (description, specDefinitions, timeout) {
  2522. arguments[1] = wrapTestInZone(specDefinitions);
  2523. return originalJasmineFn.apply(this, arguments);
  2524. };
  2525. });
  2526. ['beforeEach', 'afterEach', 'beforeAll', 'afterAll'].forEach(function (methodName) {
  2527. var originalJasmineFn = jasmineEnv[methodName];
  2528. jasmineEnv[symbol(methodName)] = originalJasmineFn;
  2529. jasmineEnv[methodName] = function (specDefinitions, timeout) {
  2530. arguments[0] = wrapTestInZone(specDefinitions);
  2531. return originalJasmineFn.apply(this, arguments);
  2532. };
  2533. });
  2534. if (!disablePatchingJasmineClock) {
  2535. // need to patch jasmine.clock().mockDate and jasmine.clock().tick() so
  2536. // they can work properly in FakeAsyncTest
  2537. var originalClockFn_1 = (jasmine[symbol('clock')] = jasmine['clock']);
  2538. jasmine['clock'] = function () {
  2539. var clock = originalClockFn_1.apply(this, arguments);
  2540. if (!clock[symbol('patched')]) {
  2541. clock[symbol('patched')] = symbol('patched');
  2542. var originalTick_1 = (clock[symbol('tick')] = clock.tick);
  2543. clock.tick = function () {
  2544. var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  2545. if (fakeAsyncZoneSpec) {
  2546. return fakeAsyncZoneSpec.tick.apply(fakeAsyncZoneSpec, arguments);
  2547. }
  2548. return originalTick_1.apply(this, arguments);
  2549. };
  2550. var originalMockDate_1 = (clock[symbol('mockDate')] = clock.mockDate);
  2551. clock.mockDate = function () {
  2552. var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  2553. if (fakeAsyncZoneSpec) {
  2554. var dateTime = arguments.length > 0 ? arguments[0] : new Date();
  2555. return fakeAsyncZoneSpec.setFakeBaseSystemTime.apply(fakeAsyncZoneSpec, dateTime && typeof dateTime.getTime === 'function' ? [dateTime.getTime()] :
  2556. arguments);
  2557. }
  2558. return originalMockDate_1.apply(this, arguments);
  2559. };
  2560. // for auto go into fakeAsync feature, we need the flag to enable it
  2561. if (enableAutoFakeAsyncWhenClockPatched) {
  2562. ['install', 'uninstall'].forEach(function (methodName) {
  2563. var originalClockFn = (clock[symbol(methodName)] = clock[methodName]);
  2564. clock[methodName] = function () {
  2565. var FakeAsyncTestZoneSpec = Zone['FakeAsyncTestZoneSpec'];
  2566. if (FakeAsyncTestZoneSpec) {
  2567. jasmine[symbol('clockInstalled')] = 'install' === methodName;
  2568. return;
  2569. }
  2570. return originalClockFn.apply(this, arguments);
  2571. };
  2572. });
  2573. }
  2574. }
  2575. return clock;
  2576. };
  2577. }
  2578. // monkey patch createSpyObj to make properties enumerable to true
  2579. if (!jasmine[Zone.__symbol__('createSpyObj')]) {
  2580. var originalCreateSpyObj_1 = jasmine.createSpyObj;
  2581. jasmine[Zone.__symbol__('createSpyObj')] = originalCreateSpyObj_1;
  2582. jasmine.createSpyObj = function () {
  2583. var args = Array.prototype.slice.call(arguments);
  2584. var propertyNames = args.length >= 3 ? args[2] : null;
  2585. var spyObj;
  2586. if (propertyNames) {
  2587. var defineProperty_1 = Object.defineProperty;
  2588. Object.defineProperty = function (obj, p, attributes) {
  2589. return defineProperty_1.call(this, obj, p, __assign(__assign({}, attributes), { configurable: true, enumerable: true }));
  2590. };
  2591. try {
  2592. spyObj = originalCreateSpyObj_1.apply(this, args);
  2593. }
  2594. finally {
  2595. Object.defineProperty = defineProperty_1;
  2596. }
  2597. }
  2598. else {
  2599. spyObj = originalCreateSpyObj_1.apply(this, args);
  2600. }
  2601. return spyObj;
  2602. };
  2603. }
  2604. /**
  2605. * Gets a function wrapping the body of a Jasmine `describe` block to execute in a
  2606. * synchronous-only zone.
  2607. */
  2608. function wrapDescribeInZone(description, describeBody) {
  2609. return function () {
  2610. // Create a synchronous-only zone in which to run `describe` blocks in order to raise an
  2611. // error if any asynchronous operations are attempted inside of a `describe`.
  2612. var syncZone = ambientZone.fork(new SyncTestZoneSpec("jasmine.describe#".concat(description)));
  2613. return syncZone.run(describeBody, this, arguments);
  2614. };
  2615. }
  2616. function runInTestZone(testBody, applyThis, queueRunner, done) {
  2617. var isClockInstalled = !!jasmine[symbol('clockInstalled')];
  2618. queueRunner.testProxyZoneSpec;
  2619. var testProxyZone = queueRunner.testProxyZone;
  2620. if (isClockInstalled && enableAutoFakeAsyncWhenClockPatched) {
  2621. // auto run a fakeAsync
  2622. var fakeAsyncModule = Zone[Zone.__symbol__('fakeAsyncTest')];
  2623. if (fakeAsyncModule && typeof fakeAsyncModule.fakeAsync === 'function') {
  2624. testBody = fakeAsyncModule.fakeAsync(testBody);
  2625. }
  2626. }
  2627. if (done) {
  2628. return testProxyZone.run(testBody, applyThis, [done]);
  2629. }
  2630. else {
  2631. return testProxyZone.run(testBody, applyThis);
  2632. }
  2633. }
  2634. /**
  2635. * Gets a function wrapping the body of a Jasmine `it/beforeEach/afterEach` block to
  2636. * execute in a ProxyZone zone.
  2637. * This will run in `testProxyZone`. The `testProxyZone` will be reset by the `ZoneQueueRunner`
  2638. */
  2639. function wrapTestInZone(testBody) {
  2640. // The `done` callback is only passed through if the function expects at least one argument.
  2641. // Note we have to make a function with correct number of arguments, otherwise jasmine will
  2642. // think that all functions are sync or async.
  2643. return (testBody && (testBody.length ? function (done) {
  2644. return runInTestZone(testBody, this, this.queueRunner, done);
  2645. } : function () {
  2646. return runInTestZone(testBody, this, this.queueRunner);
  2647. }));
  2648. }
  2649. var QueueRunner = jasmine.QueueRunner;
  2650. jasmine.QueueRunner = (function (_super) {
  2651. __extends(ZoneQueueRunner, _super);
  2652. function ZoneQueueRunner(attrs) {
  2653. var _this = this;
  2654. if (attrs.onComplete) {
  2655. attrs.onComplete = (function (fn) { return function () {
  2656. // All functions are done, clear the test zone.
  2657. _this.testProxyZone = null;
  2658. _this.testProxyZoneSpec = null;
  2659. ambientZone.scheduleMicroTask('jasmine.onComplete', fn);
  2660. }; })(attrs.onComplete);
  2661. }
  2662. var nativeSetTimeout = global[Zone.__symbol__('setTimeout')];
  2663. var nativeClearTimeout = global[Zone.__symbol__('clearTimeout')];
  2664. if (nativeSetTimeout) {
  2665. // should run setTimeout inside jasmine outside of zone
  2666. attrs.timeout = {
  2667. setTimeout: nativeSetTimeout ? nativeSetTimeout : global.setTimeout,
  2668. clearTimeout: nativeClearTimeout ? nativeClearTimeout : global.clearTimeout
  2669. };
  2670. }
  2671. // create a userContext to hold the queueRunner itself
  2672. // so we can access the testProxy in it/xit/beforeEach ...
  2673. if (jasmine.UserContext) {
  2674. if (!attrs.userContext) {
  2675. attrs.userContext = new jasmine.UserContext();
  2676. }
  2677. attrs.userContext.queueRunner = this;
  2678. }
  2679. else {
  2680. if (!attrs.userContext) {
  2681. attrs.userContext = {};
  2682. }
  2683. attrs.userContext.queueRunner = this;
  2684. }
  2685. // patch attrs.onException
  2686. var onException = attrs.onException;
  2687. attrs.onException = function (error) {
  2688. if (error &&
  2689. error.message ===
  2690. 'Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.') {
  2691. // jasmine timeout, we can make the error message more
  2692. // reasonable to tell what tasks are pending
  2693. var proxyZoneSpec = this && this.testProxyZoneSpec;
  2694. if (proxyZoneSpec) {
  2695. var pendingTasksInfo = proxyZoneSpec.getAndClearPendingTasksInfo();
  2696. try {
  2697. // try catch here in case error.message is not writable
  2698. error.message += pendingTasksInfo;
  2699. }
  2700. catch (err) {
  2701. }
  2702. }
  2703. }
  2704. if (onException) {
  2705. onException.call(this, error);
  2706. }
  2707. };
  2708. _super.call(this, attrs);
  2709. }
  2710. ZoneQueueRunner.prototype.execute = function () {
  2711. var _this = this;
  2712. var zone = Zone.current;
  2713. var isChildOfAmbientZone = false;
  2714. while (zone) {
  2715. if (zone === ambientZone) {
  2716. isChildOfAmbientZone = true;
  2717. break;
  2718. }
  2719. zone = zone.parent;
  2720. }
  2721. if (!isChildOfAmbientZone)
  2722. throw new Error('Unexpected Zone: ' + Zone.current.name);
  2723. // This is the zone which will be used for running individual tests.
  2724. // It will be a proxy zone, so that the tests function can retroactively install
  2725. // different zones.
  2726. // Example:
  2727. // - In beforeEach() do childZone = Zone.current.fork(...);
  2728. // - In it() try to do fakeAsync(). The issue is that because the beforeEach forked the
  2729. // zone outside of fakeAsync it will be able to escape the fakeAsync rules.
  2730. // - Because ProxyZone is parent fo `childZone` fakeAsync can retroactively add
  2731. // fakeAsync behavior to the childZone.
  2732. this.testProxyZoneSpec = new ProxyZoneSpec();
  2733. this.testProxyZone = ambientZone.fork(this.testProxyZoneSpec);
  2734. if (!Zone.currentTask) {
  2735. // if we are not running in a task then if someone would register a
  2736. // element.addEventListener and then calling element.click() the
  2737. // addEventListener callback would think that it is the top most task and would
  2738. // drain the microtask queue on element.click() which would be incorrect.
  2739. // For this reason we always force a task when running jasmine tests.
  2740. Zone.current.scheduleMicroTask('jasmine.execute().forceTask', function () { return QueueRunner.prototype.execute.call(_this); });
  2741. }
  2742. else {
  2743. _super.prototype.execute.call(this);
  2744. }
  2745. };
  2746. return ZoneQueueRunner;
  2747. })(QueueRunner);
  2748. });
  2749. Zone.__load_patch('jest', function (context, Zone, api) {
  2750. if (typeof jest === 'undefined' || jest['__zone_patch__']) {
  2751. return;
  2752. }
  2753. jest['__zone_patch__'] = true;
  2754. var ProxyZoneSpec = Zone['ProxyZoneSpec'];
  2755. var SyncTestZoneSpec = Zone['SyncTestZoneSpec'];
  2756. if (!ProxyZoneSpec) {
  2757. throw new Error('Missing ProxyZoneSpec');
  2758. }
  2759. var rootZone = Zone.current;
  2760. var syncZone = rootZone.fork(new SyncTestZoneSpec('jest.describe'));
  2761. var proxyZoneSpec = new ProxyZoneSpec();
  2762. var proxyZone = rootZone.fork(proxyZoneSpec);
  2763. function wrapDescribeFactoryInZone(originalJestFn) {
  2764. return function () {
  2765. var tableArgs = [];
  2766. for (var _i = 0; _i < arguments.length; _i++) {
  2767. tableArgs[_i] = arguments[_i];
  2768. }
  2769. var originalDescribeFn = originalJestFn.apply(this, tableArgs);
  2770. return function () {
  2771. var args = [];
  2772. for (var _i = 0; _i < arguments.length; _i++) {
  2773. args[_i] = arguments[_i];
  2774. }
  2775. args[1] = wrapDescribeInZone(args[1]);
  2776. return originalDescribeFn.apply(this, args);
  2777. };
  2778. };
  2779. }
  2780. function wrapTestFactoryInZone(originalJestFn) {
  2781. return function () {
  2782. var tableArgs = [];
  2783. for (var _i = 0; _i < arguments.length; _i++) {
  2784. tableArgs[_i] = arguments[_i];
  2785. }
  2786. return function () {
  2787. var args = [];
  2788. for (var _i = 0; _i < arguments.length; _i++) {
  2789. args[_i] = arguments[_i];
  2790. }
  2791. args[1] = wrapTestInZone(args[1]);
  2792. return originalJestFn.apply(this, tableArgs).apply(this, args);
  2793. };
  2794. };
  2795. }
  2796. /**
  2797. * Gets a function wrapping the body of a jest `describe` block to execute in a
  2798. * synchronous-only zone.
  2799. */
  2800. function wrapDescribeInZone(describeBody) {
  2801. return function () {
  2802. var args = [];
  2803. for (var _i = 0; _i < arguments.length; _i++) {
  2804. args[_i] = arguments[_i];
  2805. }
  2806. return syncZone.run(describeBody, this, args);
  2807. };
  2808. }
  2809. /**
  2810. * Gets a function wrapping the body of a jest `it/beforeEach/afterEach` block to
  2811. * execute in a ProxyZone zone.
  2812. * This will run in the `proxyZone`.
  2813. */
  2814. function wrapTestInZone(testBody, isTestFunc) {
  2815. if (isTestFunc === void 0) { isTestFunc = false; }
  2816. if (typeof testBody !== 'function') {
  2817. return testBody;
  2818. }
  2819. var wrappedFunc = function () {
  2820. if (Zone[api.symbol('useFakeTimersCalled')] === true && testBody &&
  2821. !testBody.isFakeAsync) {
  2822. // jest.useFakeTimers is called, run into fakeAsyncTest automatically.
  2823. var fakeAsyncModule = Zone[Zone.__symbol__('fakeAsyncTest')];
  2824. if (fakeAsyncModule && typeof fakeAsyncModule.fakeAsync === 'function') {
  2825. testBody = fakeAsyncModule.fakeAsync(testBody);
  2826. }
  2827. }
  2828. proxyZoneSpec.isTestFunc = isTestFunc;
  2829. return proxyZone.run(testBody, null, arguments);
  2830. };
  2831. // Update the length of wrappedFunc to be the same as the length of the testBody
  2832. // So jest core can handle whether the test function has `done()` or not correctly
  2833. Object.defineProperty(wrappedFunc, 'length', { configurable: true, writable: true, enumerable: false });
  2834. wrappedFunc.length = testBody.length;
  2835. return wrappedFunc;
  2836. }
  2837. ['describe', 'xdescribe', 'fdescribe'].forEach(function (methodName) {
  2838. var originalJestFn = context[methodName];
  2839. if (context[Zone.__symbol__(methodName)]) {
  2840. return;
  2841. }
  2842. context[Zone.__symbol__(methodName)] = originalJestFn;
  2843. context[methodName] = function () {
  2844. var args = [];
  2845. for (var _i = 0; _i < arguments.length; _i++) {
  2846. args[_i] = arguments[_i];
  2847. }
  2848. args[1] = wrapDescribeInZone(args[1]);
  2849. return originalJestFn.apply(this, args);
  2850. };
  2851. context[methodName].each = wrapDescribeFactoryInZone(originalJestFn.each);
  2852. });
  2853. context.describe.only = context.fdescribe;
  2854. context.describe.skip = context.xdescribe;
  2855. ['it', 'xit', 'fit', 'test', 'xtest'].forEach(function (methodName) {
  2856. var originalJestFn = context[methodName];
  2857. if (context[Zone.__symbol__(methodName)]) {
  2858. return;
  2859. }
  2860. context[Zone.__symbol__(methodName)] = originalJestFn;
  2861. context[methodName] = function () {
  2862. var args = [];
  2863. for (var _i = 0; _i < arguments.length; _i++) {
  2864. args[_i] = arguments[_i];
  2865. }
  2866. args[1] = wrapTestInZone(args[1], true);
  2867. return originalJestFn.apply(this, args);
  2868. };
  2869. context[methodName].each = wrapTestFactoryInZone(originalJestFn.each);
  2870. context[methodName].todo = originalJestFn.todo;
  2871. });
  2872. context.it.only = context.fit;
  2873. context.it.skip = context.xit;
  2874. context.test.only = context.fit;
  2875. context.test.skip = context.xit;
  2876. ['beforeEach', 'afterEach', 'beforeAll', 'afterAll'].forEach(function (methodName) {
  2877. var originalJestFn = context[methodName];
  2878. if (context[Zone.__symbol__(methodName)]) {
  2879. return;
  2880. }
  2881. context[Zone.__symbol__(methodName)] = originalJestFn;
  2882. context[methodName] = function () {
  2883. var args = [];
  2884. for (var _i = 0; _i < arguments.length; _i++) {
  2885. args[_i] = arguments[_i];
  2886. }
  2887. args[0] = wrapTestInZone(args[0]);
  2888. return originalJestFn.apply(this, args);
  2889. };
  2890. });
  2891. Zone.patchJestObject = function patchJestObject(Timer, isModern) {
  2892. if (isModern === void 0) { isModern = false; }
  2893. // check whether currently the test is inside fakeAsync()
  2894. function isPatchingFakeTimer() {
  2895. var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  2896. return !!fakeAsyncZoneSpec;
  2897. }
  2898. // check whether the current function is inside `test/it` or other methods
  2899. // such as `describe/beforeEach`
  2900. function isInTestFunc() {
  2901. var proxyZoneSpec = Zone.current.get('ProxyZoneSpec');
  2902. return proxyZoneSpec && proxyZoneSpec.isTestFunc;
  2903. }
  2904. if (Timer[api.symbol('fakeTimers')]) {
  2905. return;
  2906. }
  2907. Timer[api.symbol('fakeTimers')] = true;
  2908. // patch jest fakeTimer internal method to make sure no console.warn print out
  2909. api.patchMethod(Timer, '_checkFakeTimers', function (delegate) {
  2910. return function (self, args) {
  2911. if (isPatchingFakeTimer()) {
  2912. return true;
  2913. }
  2914. else {
  2915. return delegate.apply(self, args);
  2916. }
  2917. };
  2918. });
  2919. // patch useFakeTimers(), set useFakeTimersCalled flag, and make test auto run into fakeAsync
  2920. api.patchMethod(Timer, 'useFakeTimers', function (delegate) {
  2921. return function (self, args) {
  2922. Zone[api.symbol('useFakeTimersCalled')] = true;
  2923. if (isModern || isInTestFunc()) {
  2924. return delegate.apply(self, args);
  2925. }
  2926. return self;
  2927. };
  2928. });
  2929. // patch useRealTimers(), unset useFakeTimers flag
  2930. api.patchMethod(Timer, 'useRealTimers', function (delegate) {
  2931. return function (self, args) {
  2932. Zone[api.symbol('useFakeTimersCalled')] = false;
  2933. if (isModern || isInTestFunc()) {
  2934. return delegate.apply(self, args);
  2935. }
  2936. return self;
  2937. };
  2938. });
  2939. // patch setSystemTime(), call setCurrentRealTime() in the fakeAsyncTest
  2940. api.patchMethod(Timer, 'setSystemTime', function (delegate) {
  2941. return function (self, args) {
  2942. var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  2943. if (fakeAsyncZoneSpec && isPatchingFakeTimer()) {
  2944. fakeAsyncZoneSpec.setFakeBaseSystemTime(args[0]);
  2945. }
  2946. else {
  2947. return delegate.apply(self, args);
  2948. }
  2949. };
  2950. });
  2951. // patch getSystemTime(), call getCurrentRealTime() in the fakeAsyncTest
  2952. api.patchMethod(Timer, 'getRealSystemTime', function (delegate) {
  2953. return function (self, args) {
  2954. var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  2955. if (fakeAsyncZoneSpec && isPatchingFakeTimer()) {
  2956. return fakeAsyncZoneSpec.getRealSystemTime();
  2957. }
  2958. else {
  2959. return delegate.apply(self, args);
  2960. }
  2961. };
  2962. });
  2963. // patch runAllTicks(), run all microTasks inside fakeAsync
  2964. api.patchMethod(Timer, 'runAllTicks', function (delegate) {
  2965. return function (self, args) {
  2966. var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  2967. if (fakeAsyncZoneSpec) {
  2968. fakeAsyncZoneSpec.flushMicrotasks();
  2969. }
  2970. else {
  2971. return delegate.apply(self, args);
  2972. }
  2973. };
  2974. });
  2975. // patch runAllTimers(), run all macroTasks inside fakeAsync
  2976. api.patchMethod(Timer, 'runAllTimers', function (delegate) {
  2977. return function (self, args) {
  2978. var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  2979. if (fakeAsyncZoneSpec) {
  2980. fakeAsyncZoneSpec.flush(100, true);
  2981. }
  2982. else {
  2983. return delegate.apply(self, args);
  2984. }
  2985. };
  2986. });
  2987. // patch advanceTimersByTime(), call tick() in the fakeAsyncTest
  2988. api.patchMethod(Timer, 'advanceTimersByTime', function (delegate) {
  2989. return function (self, args) {
  2990. var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  2991. if (fakeAsyncZoneSpec) {
  2992. fakeAsyncZoneSpec.tick(args[0]);
  2993. }
  2994. else {
  2995. return delegate.apply(self, args);
  2996. }
  2997. };
  2998. });
  2999. // patch runOnlyPendingTimers(), call flushOnlyPendingTimers() in the fakeAsyncTest
  3000. api.patchMethod(Timer, 'runOnlyPendingTimers', function (delegate) {
  3001. return function (self, args) {
  3002. var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  3003. if (fakeAsyncZoneSpec) {
  3004. fakeAsyncZoneSpec.flushOnlyPendingTimers();
  3005. }
  3006. else {
  3007. return delegate.apply(self, args);
  3008. }
  3009. };
  3010. });
  3011. // patch advanceTimersToNextTimer(), call tickToNext() in the fakeAsyncTest
  3012. api.patchMethod(Timer, 'advanceTimersToNextTimer', function (delegate) {
  3013. return function (self, args) {
  3014. var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  3015. if (fakeAsyncZoneSpec) {
  3016. fakeAsyncZoneSpec.tickToNext(args[0]);
  3017. }
  3018. else {
  3019. return delegate.apply(self, args);
  3020. }
  3021. };
  3022. });
  3023. // patch clearAllTimers(), call removeAllTimers() in the fakeAsyncTest
  3024. api.patchMethod(Timer, 'clearAllTimers', function (delegate) {
  3025. return function (self, args) {
  3026. var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  3027. if (fakeAsyncZoneSpec) {
  3028. fakeAsyncZoneSpec.removeAllTimers();
  3029. }
  3030. else {
  3031. return delegate.apply(self, args);
  3032. }
  3033. };
  3034. });
  3035. // patch getTimerCount(), call getTimerCount() in the fakeAsyncTest
  3036. api.patchMethod(Timer, 'getTimerCount', function (delegate) {
  3037. return function (self, args) {
  3038. var fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  3039. if (fakeAsyncZoneSpec) {
  3040. return fakeAsyncZoneSpec.getTimerCount();
  3041. }
  3042. else {
  3043. return delegate.apply(self, args);
  3044. }
  3045. };
  3046. });
  3047. };
  3048. });
  3049. Zone.__load_patch('mocha', function (global, Zone) {
  3050. var Mocha = global.Mocha;
  3051. if (typeof Mocha === 'undefined') {
  3052. // return if Mocha is not available, because now zone-testing
  3053. // will load mocha patch with jasmine/jest patch
  3054. return;
  3055. }
  3056. if (typeof Zone === 'undefined') {
  3057. throw new Error('Missing Zone.js');
  3058. }
  3059. var ProxyZoneSpec = Zone['ProxyZoneSpec'];
  3060. var SyncTestZoneSpec = Zone['SyncTestZoneSpec'];
  3061. if (!ProxyZoneSpec) {
  3062. throw new Error('Missing ProxyZoneSpec');
  3063. }
  3064. if (Mocha['__zone_patch__']) {
  3065. throw new Error('"Mocha" has already been patched with "Zone".');
  3066. }
  3067. Mocha['__zone_patch__'] = true;
  3068. var rootZone = Zone.current;
  3069. var syncZone = rootZone.fork(new SyncTestZoneSpec('Mocha.describe'));
  3070. var testZone = null;
  3071. var suiteZone = rootZone.fork(new ProxyZoneSpec());
  3072. var mochaOriginal = {
  3073. after: global.after,
  3074. afterEach: global.afterEach,
  3075. before: global.before,
  3076. beforeEach: global.beforeEach,
  3077. describe: global.describe,
  3078. it: global.it
  3079. };
  3080. function modifyArguments(args, syncTest, asyncTest) {
  3081. var _loop_2 = function (i) {
  3082. var arg = args[i];
  3083. if (typeof arg === 'function') {
  3084. // The `done` callback is only passed through if the function expects at
  3085. // least one argument.
  3086. // Note we have to make a function with correct number of arguments,
  3087. // otherwise mocha will
  3088. // think that all functions are sync or async.
  3089. args[i] = (arg.length === 0) ? syncTest(arg) : asyncTest(arg);
  3090. // Mocha uses toString to view the test body in the result list, make sure we return the
  3091. // correct function body
  3092. args[i].toString = function () {
  3093. return arg.toString();
  3094. };
  3095. }
  3096. };
  3097. for (var i = 0; i < args.length; i++) {
  3098. _loop_2(i);
  3099. }
  3100. return args;
  3101. }
  3102. function wrapDescribeInZone(args) {
  3103. var syncTest = function (fn) {
  3104. return function () {
  3105. return syncZone.run(fn, this, arguments);
  3106. };
  3107. };
  3108. return modifyArguments(args, syncTest);
  3109. }
  3110. function wrapTestInZone(args) {
  3111. var asyncTest = function (fn) {
  3112. return function (done) {
  3113. return testZone.run(fn, this, [done]);
  3114. };
  3115. };
  3116. var syncTest = function (fn) {
  3117. return function () {
  3118. return testZone.run(fn, this);
  3119. };
  3120. };
  3121. return modifyArguments(args, syncTest, asyncTest);
  3122. }
  3123. function wrapSuiteInZone(args) {
  3124. var asyncTest = function (fn) {
  3125. return function (done) {
  3126. return suiteZone.run(fn, this, [done]);
  3127. };
  3128. };
  3129. var syncTest = function (fn) {
  3130. return function () {
  3131. return suiteZone.run(fn, this);
  3132. };
  3133. };
  3134. return modifyArguments(args, syncTest, asyncTest);
  3135. }
  3136. global.describe = global.suite = function () {
  3137. return mochaOriginal.describe.apply(this, wrapDescribeInZone(arguments));
  3138. };
  3139. global.xdescribe = global.suite.skip = function () {
  3140. return mochaOriginal.describe.skip.apply(this, wrapDescribeInZone(arguments));
  3141. };
  3142. global.describe.only = global.suite.only = function () {
  3143. return mochaOriginal.describe.only.apply(this, wrapDescribeInZone(arguments));
  3144. };
  3145. global.it = global.specify = global.test = function () {
  3146. return mochaOriginal.it.apply(this, wrapTestInZone(arguments));
  3147. };
  3148. global.xit = global.xspecify = function () {
  3149. return mochaOriginal.it.skip.apply(this, wrapTestInZone(arguments));
  3150. };
  3151. global.it.only = global.test.only = function () {
  3152. return mochaOriginal.it.only.apply(this, wrapTestInZone(arguments));
  3153. };
  3154. global.after = global.suiteTeardown = function () {
  3155. return mochaOriginal.after.apply(this, wrapSuiteInZone(arguments));
  3156. };
  3157. global.afterEach = global.teardown = function () {
  3158. return mochaOriginal.afterEach.apply(this, wrapTestInZone(arguments));
  3159. };
  3160. global.before = global.suiteSetup = function () {
  3161. return mochaOriginal.before.apply(this, wrapSuiteInZone(arguments));
  3162. };
  3163. global.beforeEach = global.setup = function () {
  3164. return mochaOriginal.beforeEach.apply(this, wrapTestInZone(arguments));
  3165. };
  3166. (function (originalRunTest, originalRun) {
  3167. Mocha.Runner.prototype.runTest = function (fn) {
  3168. var _this = this;
  3169. Zone.current.scheduleMicroTask('mocha.forceTask', function () {
  3170. originalRunTest.call(_this, fn);
  3171. });
  3172. };
  3173. Mocha.Runner.prototype.run = function (fn) {
  3174. this.on('test', function (e) {
  3175. testZone = rootZone.fork(new ProxyZoneSpec());
  3176. });
  3177. this.on('fail', function (test, err) {
  3178. var proxyZoneSpec = testZone && testZone.get('ProxyZoneSpec');
  3179. if (proxyZoneSpec && err) {
  3180. try {
  3181. // try catch here in case err.message is not writable
  3182. err.message += proxyZoneSpec.getAndClearPendingTasksInfo();
  3183. }
  3184. catch (error) {
  3185. }
  3186. }
  3187. });
  3188. return originalRun.call(this, fn);
  3189. };
  3190. })(Mocha.Runner.prototype.runTest, Mocha.Runner.prototype.run);
  3191. });
  3192. (function (_global) {
  3193. var AsyncTestZoneSpec = /** @class */ (function () {
  3194. function AsyncTestZoneSpec(finishCallback, failCallback, namePrefix) {
  3195. this.finishCallback = finishCallback;
  3196. this.failCallback = failCallback;
  3197. this._pendingMicroTasks = false;
  3198. this._pendingMacroTasks = false;
  3199. this._alreadyErrored = false;
  3200. this._isSync = false;
  3201. this._existingFinishTimer = null;
  3202. this.entryFunction = null;
  3203. this.runZone = Zone.current;
  3204. this.unresolvedChainedPromiseCount = 0;
  3205. this.supportWaitUnresolvedChainedPromise = false;
  3206. this.name = 'asyncTestZone for ' + namePrefix;
  3207. this.properties = { 'AsyncTestZoneSpec': this };
  3208. this.supportWaitUnresolvedChainedPromise =
  3209. _global[Zone.__symbol__('supportWaitUnResolvedChainedPromise')] === true;
  3210. }
  3211. AsyncTestZoneSpec.prototype.isUnresolvedChainedPromisePending = function () {
  3212. return this.unresolvedChainedPromiseCount > 0;
  3213. };
  3214. AsyncTestZoneSpec.prototype._finishCallbackIfDone = function () {
  3215. var _this = this;
  3216. // NOTE: Technically the `onHasTask` could fire together with the initial synchronous
  3217. // completion in `onInvoke`. `onHasTask` might call this method when it captured e.g.
  3218. // microtasks in the proxy zone that now complete as part of this async zone run.
  3219. // Consider the following scenario:
  3220. // 1. A test `beforeEach` schedules a microtask in the ProxyZone.
  3221. // 2. An actual empty `it` spec executes in the AsyncTestZone` (using e.g. `waitForAsync`).
  3222. // 3. The `onInvoke` invokes `_finishCallbackIfDone` because the spec runs synchronously.
  3223. // 4. We wait the scheduled timeout (see below) to account for unhandled promises.
  3224. // 5. The microtask from (1) finishes and `onHasTask` is invoked.
  3225. // --> We register a second `_finishCallbackIfDone` even though we have scheduled a timeout.
  3226. // If the finish timeout from below is already scheduled, terminate the existing scheduled
  3227. // finish invocation, avoiding calling `jasmine` `done` multiple times. *Note* that we would
  3228. // want to schedule a new finish callback in case the task state changes again.
  3229. if (this._existingFinishTimer !== null) {
  3230. clearTimeout(this._existingFinishTimer);
  3231. this._existingFinishTimer = null;
  3232. }
  3233. if (!(this._pendingMicroTasks || this._pendingMacroTasks ||
  3234. (this.supportWaitUnresolvedChainedPromise && this.isUnresolvedChainedPromisePending()))) {
  3235. // We wait until the next tick because we would like to catch unhandled promises which could
  3236. // cause test logic to be executed. In such cases we cannot finish with tasks pending then.
  3237. this.runZone.run(function () {
  3238. _this._existingFinishTimer = setTimeout(function () {
  3239. if (!_this._alreadyErrored && !(_this._pendingMicroTasks || _this._pendingMacroTasks)) {
  3240. _this.finishCallback();
  3241. }
  3242. }, 0);
  3243. });
  3244. }
  3245. };
  3246. AsyncTestZoneSpec.prototype.patchPromiseForTest = function () {
  3247. if (!this.supportWaitUnresolvedChainedPromise) {
  3248. return;
  3249. }
  3250. var patchPromiseForTest = Promise[Zone.__symbol__('patchPromiseForTest')];
  3251. if (patchPromiseForTest) {
  3252. patchPromiseForTest();
  3253. }
  3254. };
  3255. AsyncTestZoneSpec.prototype.unPatchPromiseForTest = function () {
  3256. if (!this.supportWaitUnresolvedChainedPromise) {
  3257. return;
  3258. }
  3259. var unPatchPromiseForTest = Promise[Zone.__symbol__('unPatchPromiseForTest')];
  3260. if (unPatchPromiseForTest) {
  3261. unPatchPromiseForTest();
  3262. }
  3263. };
  3264. AsyncTestZoneSpec.prototype.onScheduleTask = function (delegate, current, target, task) {
  3265. if (task.type !== 'eventTask') {
  3266. this._isSync = false;
  3267. }
  3268. if (task.type === 'microTask' && task.data && task.data instanceof Promise) {
  3269. // check whether the promise is a chained promise
  3270. if (task.data[AsyncTestZoneSpec.symbolParentUnresolved] === true) {
  3271. // chained promise is being scheduled
  3272. this.unresolvedChainedPromiseCount--;
  3273. }
  3274. }
  3275. return delegate.scheduleTask(target, task);
  3276. };
  3277. AsyncTestZoneSpec.prototype.onInvokeTask = function (delegate, current, target, task, applyThis, applyArgs) {
  3278. if (task.type !== 'eventTask') {
  3279. this._isSync = false;
  3280. }
  3281. return delegate.invokeTask(target, task, applyThis, applyArgs);
  3282. };
  3283. AsyncTestZoneSpec.prototype.onCancelTask = function (delegate, current, target, task) {
  3284. if (task.type !== 'eventTask') {
  3285. this._isSync = false;
  3286. }
  3287. return delegate.cancelTask(target, task);
  3288. };
  3289. // Note - we need to use onInvoke at the moment to call finish when a test is
  3290. // fully synchronous. TODO(juliemr): remove this when the logic for
  3291. // onHasTask changes and it calls whenever the task queues are dirty.
  3292. // updated by(JiaLiPassion), only call finish callback when no task
  3293. // was scheduled/invoked/canceled.
  3294. AsyncTestZoneSpec.prototype.onInvoke = function (parentZoneDelegate, currentZone, targetZone, delegate, applyThis, applyArgs, source) {
  3295. if (!this.entryFunction) {
  3296. this.entryFunction = delegate;
  3297. }
  3298. try {
  3299. this._isSync = true;
  3300. return parentZoneDelegate.invoke(targetZone, delegate, applyThis, applyArgs, source);
  3301. }
  3302. finally {
  3303. // We need to check the delegate is the same as entryFunction or not.
  3304. // Consider the following case.
  3305. //
  3306. // asyncTestZone.run(() => { // Here the delegate will be the entryFunction
  3307. // Zone.current.run(() => { // Here the delegate will not be the entryFunction
  3308. // });
  3309. // });
  3310. //
  3311. // We only want to check whether there are async tasks scheduled
  3312. // for the entry function.
  3313. if (this._isSync && this.entryFunction === delegate) {
  3314. this._finishCallbackIfDone();
  3315. }
  3316. }
  3317. };
  3318. AsyncTestZoneSpec.prototype.onHandleError = function (parentZoneDelegate, currentZone, targetZone, error) {
  3319. // Let the parent try to handle the error.
  3320. var result = parentZoneDelegate.handleError(targetZone, error);
  3321. if (result) {
  3322. this.failCallback(error);
  3323. this._alreadyErrored = true;
  3324. }
  3325. return false;
  3326. };
  3327. AsyncTestZoneSpec.prototype.onHasTask = function (delegate, current, target, hasTaskState) {
  3328. delegate.hasTask(target, hasTaskState);
  3329. // We should only trigger finishCallback when the target zone is the AsyncTestZone
  3330. // Consider the following cases.
  3331. //
  3332. // const childZone = asyncTestZone.fork({
  3333. // name: 'child',
  3334. // onHasTask: ...
  3335. // });
  3336. //
  3337. // So we have nested zones declared the onHasTask hook, in this case,
  3338. // the onHasTask will be triggered twice, and cause the finishCallbackIfDone()
  3339. // is also be invoked twice. So we need to only trigger the finishCallbackIfDone()
  3340. // when the current zone is the same as the target zone.
  3341. if (current !== target) {
  3342. return;
  3343. }
  3344. if (hasTaskState.change == 'microTask') {
  3345. this._pendingMicroTasks = hasTaskState.microTask;
  3346. this._finishCallbackIfDone();
  3347. }
  3348. else if (hasTaskState.change == 'macroTask') {
  3349. this._pendingMacroTasks = hasTaskState.macroTask;
  3350. this._finishCallbackIfDone();
  3351. }
  3352. };
  3353. return AsyncTestZoneSpec;
  3354. }());
  3355. AsyncTestZoneSpec.symbolParentUnresolved = Zone.__symbol__('parentUnresolved');
  3356. // Export the class so that new instances can be created with proper
  3357. // constructor params.
  3358. Zone['AsyncTestZoneSpec'] = AsyncTestZoneSpec;
  3359. })(typeof window !== 'undefined' && window || typeof self !== 'undefined' && self || global);
  3360. Zone.__load_patch('asynctest', function (global, Zone, api) {
  3361. /**
  3362. * Wraps a test function in an asynchronous test zone. The test will automatically
  3363. * complete when all asynchronous calls within this zone are done.
  3364. */
  3365. Zone[api.symbol('asyncTest')] = function asyncTest(fn) {
  3366. // If we're running using the Jasmine test framework, adapt to call the 'done'
  3367. // function when asynchronous activity is finished.
  3368. if (global.jasmine) {
  3369. // Not using an arrow function to preserve context passed from call site
  3370. return function (done) {
  3371. if (!done) {
  3372. // if we run beforeEach in @angular/core/testing/testing_internal then we get no done
  3373. // fake it here and assume sync.
  3374. done = function () { };
  3375. done.fail = function (e) {
  3376. throw e;
  3377. };
  3378. }
  3379. runInTestZone(fn, this, done, function (err) {
  3380. if (typeof err === 'string') {
  3381. return done.fail(new Error(err));
  3382. }
  3383. else {
  3384. done.fail(err);
  3385. }
  3386. });
  3387. };
  3388. }
  3389. // Otherwise, return a promise which will resolve when asynchronous activity
  3390. // is finished. This will be correctly consumed by the Mocha framework with
  3391. // it('...', async(myFn)); or can be used in a custom framework.
  3392. // Not using an arrow function to preserve context passed from call site
  3393. return function () {
  3394. var _this = this;
  3395. return new Promise(function (finishCallback, failCallback) {
  3396. runInTestZone(fn, _this, finishCallback, failCallback);
  3397. });
  3398. };
  3399. };
  3400. function runInTestZone(fn, context, finishCallback, failCallback) {
  3401. var currentZone = Zone.current;
  3402. var AsyncTestZoneSpec = Zone['AsyncTestZoneSpec'];
  3403. if (AsyncTestZoneSpec === undefined) {
  3404. throw new Error('AsyncTestZoneSpec is needed for the async() test helper but could not be found. ' +
  3405. 'Please make sure that your environment includes zone.js/plugins/async-test');
  3406. }
  3407. var ProxyZoneSpec = Zone['ProxyZoneSpec'];
  3408. if (!ProxyZoneSpec) {
  3409. throw new Error('ProxyZoneSpec is needed for the async() test helper but could not be found. ' +
  3410. 'Please make sure that your environment includes zone.js/plugins/proxy');
  3411. }
  3412. var proxyZoneSpec = ProxyZoneSpec.get();
  3413. ProxyZoneSpec.assertPresent();
  3414. // We need to create the AsyncTestZoneSpec outside the ProxyZone.
  3415. // If we do it in ProxyZone then we will get to infinite recursion.
  3416. var proxyZone = Zone.current.getZoneWith('ProxyZoneSpec');
  3417. var previousDelegate = proxyZoneSpec.getDelegate();
  3418. proxyZone.parent.run(function () {
  3419. var testZoneSpec = new AsyncTestZoneSpec(function () {
  3420. // Need to restore the original zone.
  3421. if (proxyZoneSpec.getDelegate() == testZoneSpec) {
  3422. // Only reset the zone spec if it's
  3423. // still this one. Otherwise, assume
  3424. // it's OK.
  3425. proxyZoneSpec.setDelegate(previousDelegate);
  3426. }
  3427. testZoneSpec.unPatchPromiseForTest();
  3428. currentZone.run(function () {
  3429. finishCallback();
  3430. });
  3431. }, function (error) {
  3432. // Need to restore the original zone.
  3433. if (proxyZoneSpec.getDelegate() == testZoneSpec) {
  3434. // Only reset the zone spec if it's sill this one. Otherwise, assume it's OK.
  3435. proxyZoneSpec.setDelegate(previousDelegate);
  3436. }
  3437. testZoneSpec.unPatchPromiseForTest();
  3438. currentZone.run(function () {
  3439. failCallback(error);
  3440. });
  3441. }, 'test');
  3442. proxyZoneSpec.setDelegate(testZoneSpec);
  3443. testZoneSpec.patchPromiseForTest();
  3444. });
  3445. return Zone.current.runGuarded(fn, context);
  3446. }
  3447. });
  3448. (function (global) {
  3449. var OriginalDate = global.Date;
  3450. // Since when we compile this file to `es2015`, and if we define
  3451. // this `FakeDate` as `class FakeDate`, and then set `FakeDate.prototype`
  3452. // there will be an error which is `Cannot assign to read only property 'prototype'`
  3453. // so we need to use function implementation here.
  3454. function FakeDate() {
  3455. if (arguments.length === 0) {
  3456. var d = new OriginalDate();
  3457. d.setTime(FakeDate.now());
  3458. return d;
  3459. }
  3460. else {
  3461. var args = Array.prototype.slice.call(arguments);
  3462. return new (OriginalDate.bind.apply(OriginalDate, __spreadArray([void 0], args, false)))();
  3463. }
  3464. }
  3465. FakeDate.now = function () {
  3466. var fakeAsyncTestZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  3467. if (fakeAsyncTestZoneSpec) {
  3468. return fakeAsyncTestZoneSpec.getFakeSystemTime();
  3469. }
  3470. return OriginalDate.now.apply(this, arguments);
  3471. };
  3472. FakeDate.UTC = OriginalDate.UTC;
  3473. FakeDate.parse = OriginalDate.parse;
  3474. // keep a reference for zone patched timer function
  3475. var timers = {
  3476. setTimeout: global.setTimeout,
  3477. setInterval: global.setInterval,
  3478. clearTimeout: global.clearTimeout,
  3479. clearInterval: global.clearInterval
  3480. };
  3481. var Scheduler = /** @class */ (function () {
  3482. function Scheduler() {
  3483. // Scheduler queue with the tuple of end time and callback function - sorted by end time.
  3484. this._schedulerQueue = [];
  3485. // Current simulated time in millis.
  3486. this._currentTickTime = 0;
  3487. // Current fake system base time in millis.
  3488. this._currentFakeBaseSystemTime = OriginalDate.now();
  3489. // track requeuePeriodicTimer
  3490. this._currentTickRequeuePeriodicEntries = [];
  3491. }
  3492. Scheduler.prototype.getCurrentTickTime = function () {
  3493. return this._currentTickTime;
  3494. };
  3495. Scheduler.prototype.getFakeSystemTime = function () {
  3496. return this._currentFakeBaseSystemTime + this._currentTickTime;
  3497. };
  3498. Scheduler.prototype.setFakeBaseSystemTime = function (fakeBaseSystemTime) {
  3499. this._currentFakeBaseSystemTime = fakeBaseSystemTime;
  3500. };
  3501. Scheduler.prototype.getRealSystemTime = function () {
  3502. return OriginalDate.now();
  3503. };
  3504. Scheduler.prototype.scheduleFunction = function (cb, delay, options) {
  3505. options = __assign({
  3506. args: [],
  3507. isPeriodic: false,
  3508. isRequestAnimationFrame: false,
  3509. id: -1,
  3510. isRequeuePeriodic: false
  3511. }, options);
  3512. var currentId = options.id < 0 ? Scheduler.nextId++ : options.id;
  3513. var endTime = this._currentTickTime + delay;
  3514. // Insert so that scheduler queue remains sorted by end time.
  3515. var newEntry = {
  3516. endTime: endTime,
  3517. id: currentId,
  3518. func: cb,
  3519. args: options.args,
  3520. delay: delay,
  3521. isPeriodic: options.isPeriodic,
  3522. isRequestAnimationFrame: options.isRequestAnimationFrame
  3523. };
  3524. if (options.isRequeuePeriodic) {
  3525. this._currentTickRequeuePeriodicEntries.push(newEntry);
  3526. }
  3527. var i = 0;
  3528. for (; i < this._schedulerQueue.length; i++) {
  3529. var currentEntry = this._schedulerQueue[i];
  3530. if (newEntry.endTime < currentEntry.endTime) {
  3531. break;
  3532. }
  3533. }
  3534. this._schedulerQueue.splice(i, 0, newEntry);
  3535. return currentId;
  3536. };
  3537. Scheduler.prototype.removeScheduledFunctionWithId = function (id) {
  3538. for (var i = 0; i < this._schedulerQueue.length; i++) {
  3539. if (this._schedulerQueue[i].id == id) {
  3540. this._schedulerQueue.splice(i, 1);
  3541. break;
  3542. }
  3543. }
  3544. };
  3545. Scheduler.prototype.removeAll = function () {
  3546. this._schedulerQueue = [];
  3547. };
  3548. Scheduler.prototype.getTimerCount = function () {
  3549. return this._schedulerQueue.length;
  3550. };
  3551. Scheduler.prototype.tickToNext = function (step, doTick, tickOptions) {
  3552. if (step === void 0) { step = 1; }
  3553. if (this._schedulerQueue.length < step) {
  3554. return;
  3555. }
  3556. // Find the last task currently queued in the scheduler queue and tick
  3557. // till that time.
  3558. var startTime = this._currentTickTime;
  3559. var targetTask = this._schedulerQueue[step - 1];
  3560. this.tick(targetTask.endTime - startTime, doTick, tickOptions);
  3561. };
  3562. Scheduler.prototype.tick = function (millis, doTick, tickOptions) {
  3563. if (millis === void 0) { millis = 0; }
  3564. var finalTime = this._currentTickTime + millis;
  3565. var lastCurrentTime = 0;
  3566. tickOptions = Object.assign({ processNewMacroTasksSynchronously: true }, tickOptions);
  3567. // we need to copy the schedulerQueue so nested timeout
  3568. // will not be wrongly called in the current tick
  3569. // https://github.com/angular/angular/issues/33799
  3570. var schedulerQueue = tickOptions.processNewMacroTasksSynchronously ?
  3571. this._schedulerQueue :
  3572. this._schedulerQueue.slice();
  3573. if (schedulerQueue.length === 0 && doTick) {
  3574. doTick(millis);
  3575. return;
  3576. }
  3577. while (schedulerQueue.length > 0) {
  3578. // clear requeueEntries before each loop
  3579. this._currentTickRequeuePeriodicEntries = [];
  3580. var current = schedulerQueue[0];
  3581. if (finalTime < current.endTime) {
  3582. // Done processing the queue since it's sorted by endTime.
  3583. break;
  3584. }
  3585. else {
  3586. // Time to run scheduled function. Remove it from the head of queue.
  3587. var current_1 = schedulerQueue.shift();
  3588. if (!tickOptions.processNewMacroTasksSynchronously) {
  3589. var idx = this._schedulerQueue.indexOf(current_1);
  3590. if (idx >= 0) {
  3591. this._schedulerQueue.splice(idx, 1);
  3592. }
  3593. }
  3594. lastCurrentTime = this._currentTickTime;
  3595. this._currentTickTime = current_1.endTime;
  3596. if (doTick) {
  3597. doTick(this._currentTickTime - lastCurrentTime);
  3598. }
  3599. var retval = current_1.func.apply(global, current_1.isRequestAnimationFrame ? [this._currentTickTime] : current_1.args);
  3600. if (!retval) {
  3601. // Uncaught exception in the current scheduled function. Stop processing the queue.
  3602. break;
  3603. }
  3604. // check is there any requeue periodic entry is added in
  3605. // current loop, if there is, we need to add to current loop
  3606. if (!tickOptions.processNewMacroTasksSynchronously) {
  3607. this._currentTickRequeuePeriodicEntries.forEach(function (newEntry) {
  3608. var i = 0;
  3609. for (; i < schedulerQueue.length; i++) {
  3610. var currentEntry = schedulerQueue[i];
  3611. if (newEntry.endTime < currentEntry.endTime) {
  3612. break;
  3613. }
  3614. }
  3615. schedulerQueue.splice(i, 0, newEntry);
  3616. });
  3617. }
  3618. }
  3619. }
  3620. lastCurrentTime = this._currentTickTime;
  3621. this._currentTickTime = finalTime;
  3622. if (doTick) {
  3623. doTick(this._currentTickTime - lastCurrentTime);
  3624. }
  3625. };
  3626. Scheduler.prototype.flushOnlyPendingTimers = function (doTick) {
  3627. if (this._schedulerQueue.length === 0) {
  3628. return 0;
  3629. }
  3630. // Find the last task currently queued in the scheduler queue and tick
  3631. // till that time.
  3632. var startTime = this._currentTickTime;
  3633. var lastTask = this._schedulerQueue[this._schedulerQueue.length - 1];
  3634. this.tick(lastTask.endTime - startTime, doTick, { processNewMacroTasksSynchronously: false });
  3635. return this._currentTickTime - startTime;
  3636. };
  3637. Scheduler.prototype.flush = function (limit, flushPeriodic, doTick) {
  3638. if (limit === void 0) { limit = 20; }
  3639. if (flushPeriodic === void 0) { flushPeriodic = false; }
  3640. if (flushPeriodic) {
  3641. return this.flushPeriodic(doTick);
  3642. }
  3643. else {
  3644. return this.flushNonPeriodic(limit, doTick);
  3645. }
  3646. };
  3647. Scheduler.prototype.flushPeriodic = function (doTick) {
  3648. if (this._schedulerQueue.length === 0) {
  3649. return 0;
  3650. }
  3651. // Find the last task currently queued in the scheduler queue and tick
  3652. // till that time.
  3653. var startTime = this._currentTickTime;
  3654. var lastTask = this._schedulerQueue[this._schedulerQueue.length - 1];
  3655. this.tick(lastTask.endTime - startTime, doTick);
  3656. return this._currentTickTime - startTime;
  3657. };
  3658. Scheduler.prototype.flushNonPeriodic = function (limit, doTick) {
  3659. var startTime = this._currentTickTime;
  3660. var lastCurrentTime = 0;
  3661. var count = 0;
  3662. while (this._schedulerQueue.length > 0) {
  3663. count++;
  3664. if (count > limit) {
  3665. throw new Error('flush failed after reaching the limit of ' + limit +
  3666. ' tasks. Does your code use a polling timeout?');
  3667. }
  3668. // flush only non-periodic timers.
  3669. // If the only remaining tasks are periodic(or requestAnimationFrame), finish flushing.
  3670. if (this._schedulerQueue.filter(function (task) { return !task.isPeriodic && !task.isRequestAnimationFrame; })
  3671. .length === 0) {
  3672. break;
  3673. }
  3674. var current = this._schedulerQueue.shift();
  3675. lastCurrentTime = this._currentTickTime;
  3676. this._currentTickTime = current.endTime;
  3677. if (doTick) {
  3678. // Update any secondary schedulers like Jasmine mock Date.
  3679. doTick(this._currentTickTime - lastCurrentTime);
  3680. }
  3681. var retval = current.func.apply(global, current.args);
  3682. if (!retval) {
  3683. // Uncaught exception in the current scheduled function. Stop processing the queue.
  3684. break;
  3685. }
  3686. }
  3687. return this._currentTickTime - startTime;
  3688. };
  3689. return Scheduler;
  3690. }());
  3691. // Next scheduler id.
  3692. Scheduler.nextId = 1;
  3693. var FakeAsyncTestZoneSpec = /** @class */ (function () {
  3694. function FakeAsyncTestZoneSpec(namePrefix, trackPendingRequestAnimationFrame, macroTaskOptions) {
  3695. if (trackPendingRequestAnimationFrame === void 0) { trackPendingRequestAnimationFrame = false; }
  3696. this.trackPendingRequestAnimationFrame = trackPendingRequestAnimationFrame;
  3697. this.macroTaskOptions = macroTaskOptions;
  3698. this._scheduler = new Scheduler();
  3699. this._microtasks = [];
  3700. this._lastError = null;
  3701. this._uncaughtPromiseErrors = Promise[Zone.__symbol__('uncaughtPromiseErrors')];
  3702. this.pendingPeriodicTimers = [];
  3703. this.pendingTimers = [];
  3704. this.patchDateLocked = false;
  3705. this.properties = { 'FakeAsyncTestZoneSpec': this };
  3706. this.name = 'fakeAsyncTestZone for ' + namePrefix;
  3707. // in case user can't access the construction of FakeAsyncTestSpec
  3708. // user can also define macroTaskOptions by define a global variable.
  3709. if (!this.macroTaskOptions) {
  3710. this.macroTaskOptions = global[Zone.__symbol__('FakeAsyncTestMacroTask')];
  3711. }
  3712. }
  3713. FakeAsyncTestZoneSpec.assertInZone = function () {
  3714. if (Zone.current.get('FakeAsyncTestZoneSpec') == null) {
  3715. throw new Error('The code should be running in the fakeAsync zone to call this function');
  3716. }
  3717. };
  3718. FakeAsyncTestZoneSpec.prototype._fnAndFlush = function (fn, completers) {
  3719. var _this = this;
  3720. return function () {
  3721. var args = [];
  3722. for (var _i = 0; _i < arguments.length; _i++) {
  3723. args[_i] = arguments[_i];
  3724. }
  3725. fn.apply(global, args);
  3726. if (_this._lastError === null) { // Success
  3727. if (completers.onSuccess != null) {
  3728. completers.onSuccess.apply(global);
  3729. }
  3730. // Flush microtasks only on success.
  3731. _this.flushMicrotasks();
  3732. }
  3733. else { // Failure
  3734. if (completers.onError != null) {
  3735. completers.onError.apply(global);
  3736. }
  3737. }
  3738. // Return true if there were no errors, false otherwise.
  3739. return _this._lastError === null;
  3740. };
  3741. };
  3742. FakeAsyncTestZoneSpec._removeTimer = function (timers, id) {
  3743. var index = timers.indexOf(id);
  3744. if (index > -1) {
  3745. timers.splice(index, 1);
  3746. }
  3747. };
  3748. FakeAsyncTestZoneSpec.prototype._dequeueTimer = function (id) {
  3749. var _this = this;
  3750. return function () {
  3751. FakeAsyncTestZoneSpec._removeTimer(_this.pendingTimers, id);
  3752. };
  3753. };
  3754. FakeAsyncTestZoneSpec.prototype._requeuePeriodicTimer = function (fn, interval, args, id) {
  3755. var _this = this;
  3756. return function () {
  3757. // Requeue the timer callback if it's not been canceled.
  3758. if (_this.pendingPeriodicTimers.indexOf(id) !== -1) {
  3759. _this._scheduler.scheduleFunction(fn, interval, { args: args, isPeriodic: true, id: id, isRequeuePeriodic: true });
  3760. }
  3761. };
  3762. };
  3763. FakeAsyncTestZoneSpec.prototype._dequeuePeriodicTimer = function (id) {
  3764. var _this = this;
  3765. return function () {
  3766. FakeAsyncTestZoneSpec._removeTimer(_this.pendingPeriodicTimers, id);
  3767. };
  3768. };
  3769. FakeAsyncTestZoneSpec.prototype._setTimeout = function (fn, delay, args, isTimer) {
  3770. if (isTimer === void 0) { isTimer = true; }
  3771. var removeTimerFn = this._dequeueTimer(Scheduler.nextId);
  3772. // Queue the callback and dequeue the timer on success and error.
  3773. var cb = this._fnAndFlush(fn, { onSuccess: removeTimerFn, onError: removeTimerFn });
  3774. var id = this._scheduler.scheduleFunction(cb, delay, { args: args, isRequestAnimationFrame: !isTimer });
  3775. if (isTimer) {
  3776. this.pendingTimers.push(id);
  3777. }
  3778. return id;
  3779. };
  3780. FakeAsyncTestZoneSpec.prototype._clearTimeout = function (id) {
  3781. FakeAsyncTestZoneSpec._removeTimer(this.pendingTimers, id);
  3782. this._scheduler.removeScheduledFunctionWithId(id);
  3783. };
  3784. FakeAsyncTestZoneSpec.prototype._setInterval = function (fn, interval, args) {
  3785. var id = Scheduler.nextId;
  3786. var completers = { onSuccess: null, onError: this._dequeuePeriodicTimer(id) };
  3787. var cb = this._fnAndFlush(fn, completers);
  3788. // Use the callback created above to requeue on success.
  3789. completers.onSuccess = this._requeuePeriodicTimer(cb, interval, args, id);
  3790. // Queue the callback and dequeue the periodic timer only on error.
  3791. this._scheduler.scheduleFunction(cb, interval, { args: args, isPeriodic: true });
  3792. this.pendingPeriodicTimers.push(id);
  3793. return id;
  3794. };
  3795. FakeAsyncTestZoneSpec.prototype._clearInterval = function (id) {
  3796. FakeAsyncTestZoneSpec._removeTimer(this.pendingPeriodicTimers, id);
  3797. this._scheduler.removeScheduledFunctionWithId(id);
  3798. };
  3799. FakeAsyncTestZoneSpec.prototype._resetLastErrorAndThrow = function () {
  3800. var error = this._lastError || this._uncaughtPromiseErrors[0];
  3801. this._uncaughtPromiseErrors.length = 0;
  3802. this._lastError = null;
  3803. throw error;
  3804. };
  3805. FakeAsyncTestZoneSpec.prototype.getCurrentTickTime = function () {
  3806. return this._scheduler.getCurrentTickTime();
  3807. };
  3808. FakeAsyncTestZoneSpec.prototype.getFakeSystemTime = function () {
  3809. return this._scheduler.getFakeSystemTime();
  3810. };
  3811. FakeAsyncTestZoneSpec.prototype.setFakeBaseSystemTime = function (realTime) {
  3812. this._scheduler.setFakeBaseSystemTime(realTime);
  3813. };
  3814. FakeAsyncTestZoneSpec.prototype.getRealSystemTime = function () {
  3815. return this._scheduler.getRealSystemTime();
  3816. };
  3817. FakeAsyncTestZoneSpec.patchDate = function () {
  3818. if (!!global[Zone.__symbol__('disableDatePatching')]) {
  3819. // we don't want to patch global Date
  3820. // because in some case, global Date
  3821. // is already being patched, we need to provide
  3822. // an option to let user still use their
  3823. // own version of Date.
  3824. return;
  3825. }
  3826. if (global['Date'] === FakeDate) {
  3827. // already patched
  3828. return;
  3829. }
  3830. global['Date'] = FakeDate;
  3831. FakeDate.prototype = OriginalDate.prototype;
  3832. // try check and reset timers
  3833. // because jasmine.clock().install() may
  3834. // have replaced the global timer
  3835. FakeAsyncTestZoneSpec.checkTimerPatch();
  3836. };
  3837. FakeAsyncTestZoneSpec.resetDate = function () {
  3838. if (global['Date'] === FakeDate) {
  3839. global['Date'] = OriginalDate;
  3840. }
  3841. };
  3842. FakeAsyncTestZoneSpec.checkTimerPatch = function () {
  3843. if (global.setTimeout !== timers.setTimeout) {
  3844. global.setTimeout = timers.setTimeout;
  3845. global.clearTimeout = timers.clearTimeout;
  3846. }
  3847. if (global.setInterval !== timers.setInterval) {
  3848. global.setInterval = timers.setInterval;
  3849. global.clearInterval = timers.clearInterval;
  3850. }
  3851. };
  3852. FakeAsyncTestZoneSpec.prototype.lockDatePatch = function () {
  3853. this.patchDateLocked = true;
  3854. FakeAsyncTestZoneSpec.patchDate();
  3855. };
  3856. FakeAsyncTestZoneSpec.prototype.unlockDatePatch = function () {
  3857. this.patchDateLocked = false;
  3858. FakeAsyncTestZoneSpec.resetDate();
  3859. };
  3860. FakeAsyncTestZoneSpec.prototype.tickToNext = function (steps, doTick, tickOptions) {
  3861. if (steps === void 0) { steps = 1; }
  3862. if (tickOptions === void 0) { tickOptions = { processNewMacroTasksSynchronously: true }; }
  3863. if (steps <= 0) {
  3864. return;
  3865. }
  3866. FakeAsyncTestZoneSpec.assertInZone();
  3867. this.flushMicrotasks();
  3868. this._scheduler.tickToNext(steps, doTick, tickOptions);
  3869. if (this._lastError !== null) {
  3870. this._resetLastErrorAndThrow();
  3871. }
  3872. };
  3873. FakeAsyncTestZoneSpec.prototype.tick = function (millis, doTick, tickOptions) {
  3874. if (millis === void 0) { millis = 0; }
  3875. if (tickOptions === void 0) { tickOptions = { processNewMacroTasksSynchronously: true }; }
  3876. FakeAsyncTestZoneSpec.assertInZone();
  3877. this.flushMicrotasks();
  3878. this._scheduler.tick(millis, doTick, tickOptions);
  3879. if (this._lastError !== null) {
  3880. this._resetLastErrorAndThrow();
  3881. }
  3882. };
  3883. FakeAsyncTestZoneSpec.prototype.flushMicrotasks = function () {
  3884. var _this = this;
  3885. FakeAsyncTestZoneSpec.assertInZone();
  3886. var flushErrors = function () {
  3887. if (_this._lastError !== null || _this._uncaughtPromiseErrors.length) {
  3888. // If there is an error stop processing the microtask queue and rethrow the error.
  3889. _this._resetLastErrorAndThrow();
  3890. }
  3891. };
  3892. while (this._microtasks.length > 0) {
  3893. var microtask = this._microtasks.shift();
  3894. microtask.func.apply(microtask.target, microtask.args);
  3895. }
  3896. flushErrors();
  3897. };
  3898. FakeAsyncTestZoneSpec.prototype.flush = function (limit, flushPeriodic, doTick) {
  3899. FakeAsyncTestZoneSpec.assertInZone();
  3900. this.flushMicrotasks();
  3901. var elapsed = this._scheduler.flush(limit, flushPeriodic, doTick);
  3902. if (this._lastError !== null) {
  3903. this._resetLastErrorAndThrow();
  3904. }
  3905. return elapsed;
  3906. };
  3907. FakeAsyncTestZoneSpec.prototype.flushOnlyPendingTimers = function (doTick) {
  3908. FakeAsyncTestZoneSpec.assertInZone();
  3909. this.flushMicrotasks();
  3910. var elapsed = this._scheduler.flushOnlyPendingTimers(doTick);
  3911. if (this._lastError !== null) {
  3912. this._resetLastErrorAndThrow();
  3913. }
  3914. return elapsed;
  3915. };
  3916. FakeAsyncTestZoneSpec.prototype.removeAllTimers = function () {
  3917. FakeAsyncTestZoneSpec.assertInZone();
  3918. this._scheduler.removeAll();
  3919. this.pendingPeriodicTimers = [];
  3920. this.pendingTimers = [];
  3921. };
  3922. FakeAsyncTestZoneSpec.prototype.getTimerCount = function () {
  3923. return this._scheduler.getTimerCount() + this._microtasks.length;
  3924. };
  3925. FakeAsyncTestZoneSpec.prototype.onScheduleTask = function (delegate, current, target, task) {
  3926. switch (task.type) {
  3927. case 'microTask':
  3928. var args = task.data && task.data.args;
  3929. // should pass additional arguments to callback if have any
  3930. // currently we know process.nextTick will have such additional
  3931. // arguments
  3932. var additionalArgs = void 0;
  3933. if (args) {
  3934. var callbackIndex = task.data.cbIdx;
  3935. if (typeof args.length === 'number' && args.length > callbackIndex + 1) {
  3936. additionalArgs = Array.prototype.slice.call(args, callbackIndex + 1);
  3937. }
  3938. }
  3939. this._microtasks.push({
  3940. func: task.invoke,
  3941. args: additionalArgs,
  3942. target: task.data && task.data.target
  3943. });
  3944. break;
  3945. case 'macroTask':
  3946. switch (task.source) {
  3947. case 'setTimeout':
  3948. task.data['handleId'] = this._setTimeout(task.invoke, task.data['delay'], Array.prototype.slice.call(task.data['args'], 2));
  3949. break;
  3950. case 'setImmediate':
  3951. task.data['handleId'] = this._setTimeout(task.invoke, 0, Array.prototype.slice.call(task.data['args'], 1));
  3952. break;
  3953. case 'setInterval':
  3954. task.data['handleId'] = this._setInterval(task.invoke, task.data['delay'], Array.prototype.slice.call(task.data['args'], 2));
  3955. break;
  3956. case 'XMLHttpRequest.send':
  3957. throw new Error('Cannot make XHRs from within a fake async test. Request URL: ' +
  3958. task.data['url']);
  3959. case 'requestAnimationFrame':
  3960. case 'webkitRequestAnimationFrame':
  3961. case 'mozRequestAnimationFrame':
  3962. // Simulate a requestAnimationFrame by using a setTimeout with 16 ms.
  3963. // (60 frames per second)
  3964. task.data['handleId'] = this._setTimeout(task.invoke, 16, task.data['args'], this.trackPendingRequestAnimationFrame);
  3965. break;
  3966. default:
  3967. // user can define which macroTask they want to support by passing
  3968. // macroTaskOptions
  3969. var macroTaskOption = this.findMacroTaskOption(task);
  3970. if (macroTaskOption) {
  3971. var args_1 = task.data && task.data['args'];
  3972. var delay = args_1 && args_1.length > 1 ? args_1[1] : 0;
  3973. var callbackArgs = macroTaskOption.callbackArgs ? macroTaskOption.callbackArgs : args_1;
  3974. if (!!macroTaskOption.isPeriodic) {
  3975. // periodic macroTask, use setInterval to simulate
  3976. task.data['handleId'] = this._setInterval(task.invoke, delay, callbackArgs);
  3977. task.data.isPeriodic = true;
  3978. }
  3979. else {
  3980. // not periodic, use setTimeout to simulate
  3981. task.data['handleId'] = this._setTimeout(task.invoke, delay, callbackArgs);
  3982. }
  3983. break;
  3984. }
  3985. throw new Error('Unknown macroTask scheduled in fake async test: ' + task.source);
  3986. }
  3987. break;
  3988. case 'eventTask':
  3989. task = delegate.scheduleTask(target, task);
  3990. break;
  3991. }
  3992. return task;
  3993. };
  3994. FakeAsyncTestZoneSpec.prototype.onCancelTask = function (delegate, current, target, task) {
  3995. switch (task.source) {
  3996. case 'setTimeout':
  3997. case 'requestAnimationFrame':
  3998. case 'webkitRequestAnimationFrame':
  3999. case 'mozRequestAnimationFrame':
  4000. return this._clearTimeout(task.data['handleId']);
  4001. case 'setInterval':
  4002. return this._clearInterval(task.data['handleId']);
  4003. default:
  4004. // user can define which macroTask they want to support by passing
  4005. // macroTaskOptions
  4006. var macroTaskOption = this.findMacroTaskOption(task);
  4007. if (macroTaskOption) {
  4008. var handleId = task.data['handleId'];
  4009. return macroTaskOption.isPeriodic ? this._clearInterval(handleId) :
  4010. this._clearTimeout(handleId);
  4011. }
  4012. return delegate.cancelTask(target, task);
  4013. }
  4014. };
  4015. FakeAsyncTestZoneSpec.prototype.onInvoke = function (delegate, current, target, callback, applyThis, applyArgs, source) {
  4016. try {
  4017. FakeAsyncTestZoneSpec.patchDate();
  4018. return delegate.invoke(target, callback, applyThis, applyArgs, source);
  4019. }
  4020. finally {
  4021. if (!this.patchDateLocked) {
  4022. FakeAsyncTestZoneSpec.resetDate();
  4023. }
  4024. }
  4025. };
  4026. FakeAsyncTestZoneSpec.prototype.findMacroTaskOption = function (task) {
  4027. if (!this.macroTaskOptions) {
  4028. return null;
  4029. }
  4030. for (var i = 0; i < this.macroTaskOptions.length; i++) {
  4031. var macroTaskOption = this.macroTaskOptions[i];
  4032. if (macroTaskOption.source === task.source) {
  4033. return macroTaskOption;
  4034. }
  4035. }
  4036. return null;
  4037. };
  4038. FakeAsyncTestZoneSpec.prototype.onHandleError = function (parentZoneDelegate, currentZone, targetZone, error) {
  4039. this._lastError = error;
  4040. return false; // Don't propagate error to parent zone.
  4041. };
  4042. return FakeAsyncTestZoneSpec;
  4043. }());
  4044. // Export the class so that new instances can be created with proper
  4045. // constructor params.
  4046. Zone['FakeAsyncTestZoneSpec'] = FakeAsyncTestZoneSpec;
  4047. })(typeof window === 'object' && window || typeof self === 'object' && self || global);
  4048. Zone.__load_patch('fakeasync', function (global, Zone, api) {
  4049. var FakeAsyncTestZoneSpec = Zone && Zone['FakeAsyncTestZoneSpec'];
  4050. function getProxyZoneSpec() {
  4051. return Zone && Zone['ProxyZoneSpec'];
  4052. }
  4053. var _fakeAsyncTestZoneSpec = null;
  4054. /**
  4055. * Clears out the shared fake async zone for a test.
  4056. * To be called in a global `beforeEach`.
  4057. *
  4058. * @experimental
  4059. */
  4060. function resetFakeAsyncZone() {
  4061. if (_fakeAsyncTestZoneSpec) {
  4062. _fakeAsyncTestZoneSpec.unlockDatePatch();
  4063. }
  4064. _fakeAsyncTestZoneSpec = null;
  4065. // in node.js testing we may not have ProxyZoneSpec in which case there is nothing to reset.
  4066. getProxyZoneSpec() && getProxyZoneSpec().assertPresent().resetDelegate();
  4067. }
  4068. /**
  4069. * Wraps a function to be executed in the fakeAsync zone:
  4070. * - microtasks are manually executed by calling `flushMicrotasks()`,
  4071. * - timers are synchronous, `tick()` simulates the asynchronous passage of time.
  4072. *
  4073. * If there are any pending timers at the end of the function, an exception will be thrown.
  4074. *
  4075. * Can be used to wrap inject() calls.
  4076. *
  4077. * ## Example
  4078. *
  4079. * {@example core/testing/ts/fake_async.ts region='basic'}
  4080. *
  4081. * @param fn
  4082. * @returns The function wrapped to be executed in the fakeAsync zone
  4083. *
  4084. * @experimental
  4085. */
  4086. function fakeAsync(fn) {
  4087. // Not using an arrow function to preserve context passed from call site
  4088. var fakeAsyncFn = function () {
  4089. var args = [];
  4090. for (var _i = 0; _i < arguments.length; _i++) {
  4091. args[_i] = arguments[_i];
  4092. }
  4093. var ProxyZoneSpec = getProxyZoneSpec();
  4094. if (!ProxyZoneSpec) {
  4095. throw new Error('ProxyZoneSpec is needed for the async() test helper but could not be found. ' +
  4096. 'Please make sure that your environment includes zone.js/plugins/proxy');
  4097. }
  4098. var proxyZoneSpec = ProxyZoneSpec.assertPresent();
  4099. if (Zone.current.get('FakeAsyncTestZoneSpec')) {
  4100. throw new Error('fakeAsync() calls can not be nested');
  4101. }
  4102. try {
  4103. // in case jasmine.clock init a fakeAsyncTestZoneSpec
  4104. if (!_fakeAsyncTestZoneSpec) {
  4105. if (proxyZoneSpec.getDelegate() instanceof FakeAsyncTestZoneSpec) {
  4106. throw new Error('fakeAsync() calls can not be nested');
  4107. }
  4108. _fakeAsyncTestZoneSpec = new FakeAsyncTestZoneSpec();
  4109. }
  4110. var res = void 0;
  4111. var lastProxyZoneSpec = proxyZoneSpec.getDelegate();
  4112. proxyZoneSpec.setDelegate(_fakeAsyncTestZoneSpec);
  4113. _fakeAsyncTestZoneSpec.lockDatePatch();
  4114. try {
  4115. res = fn.apply(this, args);
  4116. flushMicrotasks();
  4117. }
  4118. finally {
  4119. proxyZoneSpec.setDelegate(lastProxyZoneSpec);
  4120. }
  4121. if (_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length > 0) {
  4122. throw new Error("".concat(_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length, " ") +
  4123. "periodic timer(s) still in the queue.");
  4124. }
  4125. if (_fakeAsyncTestZoneSpec.pendingTimers.length > 0) {
  4126. throw new Error("".concat(_fakeAsyncTestZoneSpec.pendingTimers.length, " timer(s) still in the queue."));
  4127. }
  4128. return res;
  4129. }
  4130. finally {
  4131. resetFakeAsyncZone();
  4132. }
  4133. };
  4134. fakeAsyncFn.isFakeAsync = true;
  4135. return fakeAsyncFn;
  4136. }
  4137. function _getFakeAsyncZoneSpec() {
  4138. if (_fakeAsyncTestZoneSpec == null) {
  4139. _fakeAsyncTestZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  4140. if (_fakeAsyncTestZoneSpec == null) {
  4141. throw new Error('The code should be running in the fakeAsync zone to call this function');
  4142. }
  4143. }
  4144. return _fakeAsyncTestZoneSpec;
  4145. }
  4146. /**
  4147. * Simulates the asynchronous passage of time for the timers in the fakeAsync zone.
  4148. *
  4149. * The microtasks queue is drained at the very start of this function and after any timer callback
  4150. * has been executed.
  4151. *
  4152. * ## Example
  4153. *
  4154. * {@example core/testing/ts/fake_async.ts region='basic'}
  4155. *
  4156. * @experimental
  4157. */
  4158. function tick(millis, ignoreNestedTimeout) {
  4159. if (millis === void 0) { millis = 0; }
  4160. if (ignoreNestedTimeout === void 0) { ignoreNestedTimeout = false; }
  4161. _getFakeAsyncZoneSpec().tick(millis, null, ignoreNestedTimeout);
  4162. }
  4163. /**
  4164. * Simulates the asynchronous passage of time for the timers in the fakeAsync zone by
  4165. * draining the macrotask queue until it is empty. The returned value is the milliseconds
  4166. * of time that would have been elapsed.
  4167. *
  4168. * @param maxTurns
  4169. * @returns The simulated time elapsed, in millis.
  4170. *
  4171. * @experimental
  4172. */
  4173. function flush(maxTurns) {
  4174. return _getFakeAsyncZoneSpec().flush(maxTurns);
  4175. }
  4176. /**
  4177. * Discard all remaining periodic tasks.
  4178. *
  4179. * @experimental
  4180. */
  4181. function discardPeriodicTasks() {
  4182. var zoneSpec = _getFakeAsyncZoneSpec();
  4183. zoneSpec.pendingPeriodicTimers;
  4184. zoneSpec.pendingPeriodicTimers.length = 0;
  4185. }
  4186. /**
  4187. * Flush any pending microtasks.
  4188. *
  4189. * @experimental
  4190. */
  4191. function flushMicrotasks() {
  4192. _getFakeAsyncZoneSpec().flushMicrotasks();
  4193. }
  4194. Zone[api.symbol('fakeAsyncTest')] =
  4195. { resetFakeAsyncZone: resetFakeAsyncZone, flushMicrotasks: flushMicrotasks, discardPeriodicTasks: discardPeriodicTasks, tick: tick, flush: flush, fakeAsync: fakeAsync };
  4196. }, true);
  4197. /**
  4198. * Promise for async/fakeAsync zoneSpec test
  4199. * can support async operation which not supported by zone.js
  4200. * such as
  4201. * it ('test jsonp in AsyncZone', async() => {
  4202. * new Promise(res => {
  4203. * jsonp(url, (data) => {
  4204. * // success callback
  4205. * res(data);
  4206. * });
  4207. * }).then((jsonpResult) => {
  4208. * // get jsonp result.
  4209. *
  4210. * // user will expect AsyncZoneSpec wait for
  4211. * // then, but because jsonp is not zone aware
  4212. * // AsyncZone will finish before then is called.
  4213. * });
  4214. * });
  4215. */
  4216. Zone.__load_patch('promisefortest', function (global, Zone, api) {
  4217. var symbolState = api.symbol('state');
  4218. var UNRESOLVED = null;
  4219. var symbolParentUnresolved = api.symbol('parentUnresolved');
  4220. // patch Promise.prototype.then to keep an internal
  4221. // number for tracking unresolved chained promise
  4222. // we will decrease this number when the parent promise
  4223. // being resolved/rejected and chained promise was
  4224. // scheduled as a microTask.
  4225. // so we can know such kind of chained promise still
  4226. // not resolved in AsyncTestZone
  4227. Promise[api.symbol('patchPromiseForTest')] = function patchPromiseForTest() {
  4228. var oriThen = Promise[Zone.__symbol__('ZonePromiseThen')];
  4229. if (oriThen) {
  4230. return;
  4231. }
  4232. oriThen = Promise[Zone.__symbol__('ZonePromiseThen')] = Promise.prototype.then;
  4233. Promise.prototype.then = function () {
  4234. var chained = oriThen.apply(this, arguments);
  4235. if (this[symbolState] === UNRESOLVED) {
  4236. // parent promise is unresolved.
  4237. var asyncTestZoneSpec = Zone.current.get('AsyncTestZoneSpec');
  4238. if (asyncTestZoneSpec) {
  4239. asyncTestZoneSpec.unresolvedChainedPromiseCount++;
  4240. chained[symbolParentUnresolved] = true;
  4241. }
  4242. }
  4243. return chained;
  4244. };
  4245. };
  4246. Promise[api.symbol('unPatchPromiseForTest')] = function unpatchPromiseForTest() {
  4247. // restore origin then
  4248. var oriThen = Promise[Zone.__symbol__('ZonePromiseThen')];
  4249. if (oriThen) {
  4250. Promise.prototype.then = oriThen;
  4251. Promise[Zone.__symbol__('ZonePromiseThen')] = undefined;
  4252. }
  4253. };
  4254. });
  4255. }));