zone-testing-bundle.js 268 KB

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