zone-testing-bundle.umd.js 242 KB

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