zone-testing-bundle.js 211 KB

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