a zip code crypto-currency system good for red ONLY

zone-testing-bundle.js 194KB

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