router-Dwfin5Au.mjs 245 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929
  1. /**
  2. * @license Angular v19.2.13
  3. * (c) 2010-2025 Google LLC. https://angular.io/
  4. * License: MIT
  5. */
  6. import { DOCUMENT, Location } from '@angular/common';
  7. import * as i0 from '@angular/core';
  8. import { ɵisPromise as _isPromise, ɵRuntimeError as _RuntimeError, Injectable, ɵisNgModule as _isNgModule, isStandalone, createEnvironmentInjector, InjectionToken, EventEmitter, input, inject, ViewContainerRef, ChangeDetectorRef, Output, Input, Directive, reflectComponentType, Component, ɵisInjectable as _isInjectable, runInInjectionContext, NgModuleFactory, Compiler, NgZone, afterNextRender, EnvironmentInjector, DestroyRef, ɵConsole as _Console, ɵPendingTasksInternal as _PendingTasksInternal } from '@angular/core';
  9. import { isObservable, from, of, BehaviorSubject, combineLatest, EmptyError, concat, defer, pipe, throwError, EMPTY, ConnectableObservable, Subject, Subscription } from 'rxjs';
  10. import { map, switchMap, take, startWith, filter, mergeMap, first, concatMap, tap, catchError, scan, defaultIfEmpty, last as last$1, takeLast, finalize, refCount, takeUntil } from 'rxjs/operators';
  11. import * as i1 from '@angular/platform-browser';
  12. /**
  13. * The primary routing outlet.
  14. *
  15. * @publicApi
  16. */
  17. const PRIMARY_OUTLET = 'primary';
  18. /**
  19. * A private symbol used to store the value of `Route.title` inside the `Route.data` if it is a
  20. * static string or `Route.resolve` if anything else. This allows us to reuse the existing route
  21. * data/resolvers to support the title feature without new instrumentation in the `Router` pipeline.
  22. */
  23. const RouteTitleKey = /* @__PURE__ */ Symbol('RouteTitle');
  24. class ParamsAsMap {
  25. params;
  26. constructor(params) {
  27. this.params = params || {};
  28. }
  29. has(name) {
  30. return Object.prototype.hasOwnProperty.call(this.params, name);
  31. }
  32. get(name) {
  33. if (this.has(name)) {
  34. const v = this.params[name];
  35. return Array.isArray(v) ? v[0] : v;
  36. }
  37. return null;
  38. }
  39. getAll(name) {
  40. if (this.has(name)) {
  41. const v = this.params[name];
  42. return Array.isArray(v) ? v : [v];
  43. }
  44. return [];
  45. }
  46. get keys() {
  47. return Object.keys(this.params);
  48. }
  49. }
  50. /**
  51. * Converts a `Params` instance to a `ParamMap`.
  52. * @param params The instance to convert.
  53. * @returns The new map instance.
  54. *
  55. * @publicApi
  56. */
  57. function convertToParamMap(params) {
  58. return new ParamsAsMap(params);
  59. }
  60. /**
  61. * Matches the route configuration (`route`) against the actual URL (`segments`).
  62. *
  63. * When no matcher is defined on a `Route`, this is the matcher used by the Router by default.
  64. *
  65. * @param segments The remaining unmatched segments in the current navigation
  66. * @param segmentGroup The current segment group being matched
  67. * @param route The `Route` to match against.
  68. *
  69. * @see {@link UrlMatchResult}
  70. * @see {@link Route}
  71. *
  72. * @returns The resulting match information or `null` if the `route` should not match.
  73. * @publicApi
  74. */
  75. function defaultUrlMatcher(segments, segmentGroup, route) {
  76. const parts = route.path.split('/');
  77. if (parts.length > segments.length) {
  78. // The actual URL is shorter than the config, no match
  79. return null;
  80. }
  81. if (route.pathMatch === 'full' &&
  82. (segmentGroup.hasChildren() || parts.length < segments.length)) {
  83. // The config is longer than the actual URL but we are looking for a full match, return null
  84. return null;
  85. }
  86. const posParams = {};
  87. // Check each config part against the actual URL
  88. for (let index = 0; index < parts.length; index++) {
  89. const part = parts[index];
  90. const segment = segments[index];
  91. const isParameter = part[0] === ':';
  92. if (isParameter) {
  93. posParams[part.substring(1)] = segment;
  94. }
  95. else if (part !== segment.path) {
  96. // The actual URL part does not match the config, no match
  97. return null;
  98. }
  99. }
  100. return { consumed: segments.slice(0, parts.length), posParams };
  101. }
  102. function shallowEqualArrays(a, b) {
  103. if (a.length !== b.length)
  104. return false;
  105. for (let i = 0; i < a.length; ++i) {
  106. if (!shallowEqual(a[i], b[i]))
  107. return false;
  108. }
  109. return true;
  110. }
  111. function shallowEqual(a, b) {
  112. // While `undefined` should never be possible, it would sometimes be the case in IE 11
  113. // and pre-chromium Edge. The check below accounts for this edge case.
  114. const k1 = a ? getDataKeys(a) : undefined;
  115. const k2 = b ? getDataKeys(b) : undefined;
  116. if (!k1 || !k2 || k1.length != k2.length) {
  117. return false;
  118. }
  119. let key;
  120. for (let i = 0; i < k1.length; i++) {
  121. key = k1[i];
  122. if (!equalArraysOrString(a[key], b[key])) {
  123. return false;
  124. }
  125. }
  126. return true;
  127. }
  128. /**
  129. * Gets the keys of an object, including `symbol` keys.
  130. */
  131. function getDataKeys(obj) {
  132. return [...Object.keys(obj), ...Object.getOwnPropertySymbols(obj)];
  133. }
  134. /**
  135. * Test equality for arrays of strings or a string.
  136. */
  137. function equalArraysOrString(a, b) {
  138. if (Array.isArray(a) && Array.isArray(b)) {
  139. if (a.length !== b.length)
  140. return false;
  141. const aSorted = [...a].sort();
  142. const bSorted = [...b].sort();
  143. return aSorted.every((val, index) => bSorted[index] === val);
  144. }
  145. else {
  146. return a === b;
  147. }
  148. }
  149. /**
  150. * Return the last element of an array.
  151. */
  152. function last(a) {
  153. return a.length > 0 ? a[a.length - 1] : null;
  154. }
  155. function wrapIntoObservable(value) {
  156. if (isObservable(value)) {
  157. return value;
  158. }
  159. if (_isPromise(value)) {
  160. // Use `Promise.resolve()` to wrap promise-like instances.
  161. // Required ie when a Resolver returns a AngularJS `$q` promise to correctly trigger the
  162. // change detection.
  163. return from(Promise.resolve(value));
  164. }
  165. return of(value);
  166. }
  167. const pathCompareMap = {
  168. 'exact': equalSegmentGroups,
  169. 'subset': containsSegmentGroup,
  170. };
  171. const paramCompareMap = {
  172. 'exact': equalParams,
  173. 'subset': containsParams,
  174. 'ignored': () => true,
  175. };
  176. function containsTree(container, containee, options) {
  177. return (pathCompareMap[options.paths](container.root, containee.root, options.matrixParams) &&
  178. paramCompareMap[options.queryParams](container.queryParams, containee.queryParams) &&
  179. !(options.fragment === 'exact' && container.fragment !== containee.fragment));
  180. }
  181. function equalParams(container, containee) {
  182. // TODO: This does not handle array params correctly.
  183. return shallowEqual(container, containee);
  184. }
  185. function equalSegmentGroups(container, containee, matrixParams) {
  186. if (!equalPath(container.segments, containee.segments))
  187. return false;
  188. if (!matrixParamsMatch(container.segments, containee.segments, matrixParams)) {
  189. return false;
  190. }
  191. if (container.numberOfChildren !== containee.numberOfChildren)
  192. return false;
  193. for (const c in containee.children) {
  194. if (!container.children[c])
  195. return false;
  196. if (!equalSegmentGroups(container.children[c], containee.children[c], matrixParams))
  197. return false;
  198. }
  199. return true;
  200. }
  201. function containsParams(container, containee) {
  202. return (Object.keys(containee).length <= Object.keys(container).length &&
  203. Object.keys(containee).every((key) => equalArraysOrString(container[key], containee[key])));
  204. }
  205. function containsSegmentGroup(container, containee, matrixParams) {
  206. return containsSegmentGroupHelper(container, containee, containee.segments, matrixParams);
  207. }
  208. function containsSegmentGroupHelper(container, containee, containeePaths, matrixParams) {
  209. if (container.segments.length > containeePaths.length) {
  210. const current = container.segments.slice(0, containeePaths.length);
  211. if (!equalPath(current, containeePaths))
  212. return false;
  213. if (containee.hasChildren())
  214. return false;
  215. if (!matrixParamsMatch(current, containeePaths, matrixParams))
  216. return false;
  217. return true;
  218. }
  219. else if (container.segments.length === containeePaths.length) {
  220. if (!equalPath(container.segments, containeePaths))
  221. return false;
  222. if (!matrixParamsMatch(container.segments, containeePaths, matrixParams))
  223. return false;
  224. for (const c in containee.children) {
  225. if (!container.children[c])
  226. return false;
  227. if (!containsSegmentGroup(container.children[c], containee.children[c], matrixParams)) {
  228. return false;
  229. }
  230. }
  231. return true;
  232. }
  233. else {
  234. const current = containeePaths.slice(0, container.segments.length);
  235. const next = containeePaths.slice(container.segments.length);
  236. if (!equalPath(container.segments, current))
  237. return false;
  238. if (!matrixParamsMatch(container.segments, current, matrixParams))
  239. return false;
  240. if (!container.children[PRIMARY_OUTLET])
  241. return false;
  242. return containsSegmentGroupHelper(container.children[PRIMARY_OUTLET], containee, next, matrixParams);
  243. }
  244. }
  245. function matrixParamsMatch(containerPaths, containeePaths, options) {
  246. return containeePaths.every((containeeSegment, i) => {
  247. return paramCompareMap[options](containerPaths[i].parameters, containeeSegment.parameters);
  248. });
  249. }
  250. /**
  251. * @description
  252. *
  253. * Represents the parsed URL.
  254. *
  255. * Since a router state is a tree, and the URL is nothing but a serialized state, the URL is a
  256. * serialized tree.
  257. * UrlTree is a data structure that provides a lot of affordances in dealing with URLs
  258. *
  259. * @usageNotes
  260. * ### Example
  261. *
  262. * ```ts
  263. * @Component({templateUrl:'template.html'})
  264. * class MyComponent {
  265. * constructor(router: Router) {
  266. * const tree: UrlTree =
  267. * router.parseUrl('/team/33/(user/victor//support:help)?debug=true#fragment');
  268. * const f = tree.fragment; // return 'fragment'
  269. * const q = tree.queryParams; // returns {debug: 'true'}
  270. * const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET];
  271. * const s: UrlSegment[] = g.segments; // returns 2 segments 'team' and '33'
  272. * g.children[PRIMARY_OUTLET].segments; // returns 2 segments 'user' and 'victor'
  273. * g.children['support'].segments; // return 1 segment 'help'
  274. * }
  275. * }
  276. * ```
  277. *
  278. * @publicApi
  279. */
  280. class UrlTree {
  281. root;
  282. queryParams;
  283. fragment;
  284. /** @internal */
  285. _queryParamMap;
  286. constructor(
  287. /** The root segment group of the URL tree */
  288. root = new UrlSegmentGroup([], {}),
  289. /** The query params of the URL */
  290. queryParams = {},
  291. /** The fragment of the URL */
  292. fragment = null) {
  293. this.root = root;
  294. this.queryParams = queryParams;
  295. this.fragment = fragment;
  296. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  297. if (root.segments.length > 0) {
  298. throw new _RuntimeError(4015 /* RuntimeErrorCode.INVALID_ROOT_URL_SEGMENT */, 'The root `UrlSegmentGroup` should not contain `segments`. ' +
  299. 'Instead, these segments belong in the `children` so they can be associated with a named outlet.');
  300. }
  301. }
  302. }
  303. get queryParamMap() {
  304. this._queryParamMap ??= convertToParamMap(this.queryParams);
  305. return this._queryParamMap;
  306. }
  307. /** @docsNotRequired */
  308. toString() {
  309. return DEFAULT_SERIALIZER.serialize(this);
  310. }
  311. }
  312. /**
  313. * @description
  314. *
  315. * Represents the parsed URL segment group.
  316. *
  317. * See `UrlTree` for more information.
  318. *
  319. * @publicApi
  320. */
  321. class UrlSegmentGroup {
  322. segments;
  323. children;
  324. /** The parent node in the url tree */
  325. parent = null;
  326. constructor(
  327. /** The URL segments of this group. See `UrlSegment` for more information */
  328. segments,
  329. /** The list of children of this group */
  330. children) {
  331. this.segments = segments;
  332. this.children = children;
  333. Object.values(children).forEach((v) => (v.parent = this));
  334. }
  335. /** Whether the segment has child segments */
  336. hasChildren() {
  337. return this.numberOfChildren > 0;
  338. }
  339. /** Number of child segments */
  340. get numberOfChildren() {
  341. return Object.keys(this.children).length;
  342. }
  343. /** @docsNotRequired */
  344. toString() {
  345. return serializePaths(this);
  346. }
  347. }
  348. /**
  349. * @description
  350. *
  351. * Represents a single URL segment.
  352. *
  353. * A UrlSegment is a part of a URL between the two slashes. It contains a path and the matrix
  354. * parameters associated with the segment.
  355. *
  356. * @usageNotes
  357. * ### Example
  358. *
  359. * ```ts
  360. * @Component({templateUrl:'template.html'})
  361. * class MyComponent {
  362. * constructor(router: Router) {
  363. * const tree: UrlTree = router.parseUrl('/team;id=33');
  364. * const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET];
  365. * const s: UrlSegment[] = g.segments;
  366. * s[0].path; // returns 'team'
  367. * s[0].parameters; // returns {id: 33}
  368. * }
  369. * }
  370. * ```
  371. *
  372. * @publicApi
  373. */
  374. class UrlSegment {
  375. path;
  376. parameters;
  377. /** @internal */
  378. _parameterMap;
  379. constructor(
  380. /** The path part of a URL segment */
  381. path,
  382. /** The matrix parameters associated with a segment */
  383. parameters) {
  384. this.path = path;
  385. this.parameters = parameters;
  386. }
  387. get parameterMap() {
  388. this._parameterMap ??= convertToParamMap(this.parameters);
  389. return this._parameterMap;
  390. }
  391. /** @docsNotRequired */
  392. toString() {
  393. return serializePath(this);
  394. }
  395. }
  396. function equalSegments(as, bs) {
  397. return equalPath(as, bs) && as.every((a, i) => shallowEqual(a.parameters, bs[i].parameters));
  398. }
  399. function equalPath(as, bs) {
  400. if (as.length !== bs.length)
  401. return false;
  402. return as.every((a, i) => a.path === bs[i].path);
  403. }
  404. function mapChildrenIntoArray(segment, fn) {
  405. let res = [];
  406. Object.entries(segment.children).forEach(([childOutlet, child]) => {
  407. if (childOutlet === PRIMARY_OUTLET) {
  408. res = res.concat(fn(child, childOutlet));
  409. }
  410. });
  411. Object.entries(segment.children).forEach(([childOutlet, child]) => {
  412. if (childOutlet !== PRIMARY_OUTLET) {
  413. res = res.concat(fn(child, childOutlet));
  414. }
  415. });
  416. return res;
  417. }
  418. /**
  419. * @description
  420. *
  421. * Serializes and deserializes a URL string into a URL tree.
  422. *
  423. * The url serialization strategy is customizable. You can
  424. * make all URLs case insensitive by providing a custom UrlSerializer.
  425. *
  426. * See `DefaultUrlSerializer` for an example of a URL serializer.
  427. *
  428. * @publicApi
  429. */
  430. class UrlSerializer {
  431. static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: UrlSerializer, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
  432. static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: UrlSerializer, providedIn: 'root', useFactory: () => new DefaultUrlSerializer() });
  433. }
  434. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: UrlSerializer, decorators: [{
  435. type: Injectable,
  436. args: [{ providedIn: 'root', useFactory: () => new DefaultUrlSerializer() }]
  437. }] });
  438. /**
  439. * @description
  440. *
  441. * A default implementation of the `UrlSerializer`.
  442. *
  443. * Example URLs:
  444. *
  445. * ```
  446. * /inbox/33(popup:compose)
  447. * /inbox/33;open=true/messages/44
  448. * ```
  449. *
  450. * DefaultUrlSerializer uses parentheses to serialize secondary segments (e.g., popup:compose), the
  451. * colon syntax to specify the outlet, and the ';parameter=value' syntax (e.g., open=true) to
  452. * specify route specific parameters.
  453. *
  454. * @publicApi
  455. */
  456. class DefaultUrlSerializer {
  457. /** Parses a url into a `UrlTree` */
  458. parse(url) {
  459. const p = new UrlParser(url);
  460. return new UrlTree(p.parseRootSegment(), p.parseQueryParams(), p.parseFragment());
  461. }
  462. /** Converts a `UrlTree` into a url */
  463. serialize(tree) {
  464. const segment = `/${serializeSegment(tree.root, true)}`;
  465. const query = serializeQueryParams(tree.queryParams);
  466. const fragment = typeof tree.fragment === `string` ? `#${encodeUriFragment(tree.fragment)}` : '';
  467. return `${segment}${query}${fragment}`;
  468. }
  469. }
  470. const DEFAULT_SERIALIZER = new DefaultUrlSerializer();
  471. function serializePaths(segment) {
  472. return segment.segments.map((p) => serializePath(p)).join('/');
  473. }
  474. function serializeSegment(segment, root) {
  475. if (!segment.hasChildren()) {
  476. return serializePaths(segment);
  477. }
  478. if (root) {
  479. const primary = segment.children[PRIMARY_OUTLET]
  480. ? serializeSegment(segment.children[PRIMARY_OUTLET], false)
  481. : '';
  482. const children = [];
  483. Object.entries(segment.children).forEach(([k, v]) => {
  484. if (k !== PRIMARY_OUTLET) {
  485. children.push(`${k}:${serializeSegment(v, false)}`);
  486. }
  487. });
  488. return children.length > 0 ? `${primary}(${children.join('//')})` : primary;
  489. }
  490. else {
  491. const children = mapChildrenIntoArray(segment, (v, k) => {
  492. if (k === PRIMARY_OUTLET) {
  493. return [serializeSegment(segment.children[PRIMARY_OUTLET], false)];
  494. }
  495. return [`${k}:${serializeSegment(v, false)}`];
  496. });
  497. // use no parenthesis if the only child is a primary outlet route
  498. if (Object.keys(segment.children).length === 1 && segment.children[PRIMARY_OUTLET] != null) {
  499. return `${serializePaths(segment)}/${children[0]}`;
  500. }
  501. return `${serializePaths(segment)}/(${children.join('//')})`;
  502. }
  503. }
  504. /**
  505. * Encodes a URI string with the default encoding. This function will only ever be called from
  506. * `encodeUriQuery` or `encodeUriSegment` as it's the base set of encodings to be used. We need
  507. * a custom encoding because encodeURIComponent is too aggressive and encodes stuff that doesn't
  508. * have to be encoded per https://url.spec.whatwg.org.
  509. */
  510. function encodeUriString(s) {
  511. return encodeURIComponent(s)
  512. .replace(/%40/g, '@')
  513. .replace(/%3A/gi, ':')
  514. .replace(/%24/g, '$')
  515. .replace(/%2C/gi, ',');
  516. }
  517. /**
  518. * This function should be used to encode both keys and values in a query string key/value. In
  519. * the following URL, you need to call encodeUriQuery on "k" and "v":
  520. *
  521. * http://www.site.org/html;mk=mv?k=v#f
  522. */
  523. function encodeUriQuery(s) {
  524. return encodeUriString(s).replace(/%3B/gi, ';');
  525. }
  526. /**
  527. * This function should be used to encode a URL fragment. In the following URL, you need to call
  528. * encodeUriFragment on "f":
  529. *
  530. * http://www.site.org/html;mk=mv?k=v#f
  531. */
  532. function encodeUriFragment(s) {
  533. return encodeURI(s);
  534. }
  535. /**
  536. * This function should be run on any URI segment as well as the key and value in a key/value
  537. * pair for matrix params. In the following URL, you need to call encodeUriSegment on "html",
  538. * "mk", and "mv":
  539. *
  540. * http://www.site.org/html;mk=mv?k=v#f
  541. */
  542. function encodeUriSegment(s) {
  543. return encodeUriString(s).replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/%26/gi, '&');
  544. }
  545. function decode(s) {
  546. return decodeURIComponent(s);
  547. }
  548. // Query keys/values should have the "+" replaced first, as "+" in a query string is " ".
  549. // decodeURIComponent function will not decode "+" as a space.
  550. function decodeQuery(s) {
  551. return decode(s.replace(/\+/g, '%20'));
  552. }
  553. function serializePath(path) {
  554. return `${encodeUriSegment(path.path)}${serializeMatrixParams(path.parameters)}`;
  555. }
  556. function serializeMatrixParams(params) {
  557. return Object.entries(params)
  558. .map(([key, value]) => `;${encodeUriSegment(key)}=${encodeUriSegment(value)}`)
  559. .join('');
  560. }
  561. function serializeQueryParams(params) {
  562. const strParams = Object.entries(params)
  563. .map(([name, value]) => {
  564. return Array.isArray(value)
  565. ? value.map((v) => `${encodeUriQuery(name)}=${encodeUriQuery(v)}`).join('&')
  566. : `${encodeUriQuery(name)}=${encodeUriQuery(value)}`;
  567. })
  568. .filter((s) => s);
  569. return strParams.length ? `?${strParams.join('&')}` : '';
  570. }
  571. const SEGMENT_RE = /^[^\/()?;#]+/;
  572. function matchSegments(str) {
  573. const match = str.match(SEGMENT_RE);
  574. return match ? match[0] : '';
  575. }
  576. const MATRIX_PARAM_SEGMENT_RE = /^[^\/()?;=#]+/;
  577. function matchMatrixKeySegments(str) {
  578. const match = str.match(MATRIX_PARAM_SEGMENT_RE);
  579. return match ? match[0] : '';
  580. }
  581. const QUERY_PARAM_RE = /^[^=?&#]+/;
  582. // Return the name of the query param at the start of the string or an empty string
  583. function matchQueryParams(str) {
  584. const match = str.match(QUERY_PARAM_RE);
  585. return match ? match[0] : '';
  586. }
  587. const QUERY_PARAM_VALUE_RE = /^[^&#]+/;
  588. // Return the value of the query param at the start of the string or an empty string
  589. function matchUrlQueryParamValue(str) {
  590. const match = str.match(QUERY_PARAM_VALUE_RE);
  591. return match ? match[0] : '';
  592. }
  593. class UrlParser {
  594. url;
  595. remaining;
  596. constructor(url) {
  597. this.url = url;
  598. this.remaining = url;
  599. }
  600. parseRootSegment() {
  601. this.consumeOptional('/');
  602. if (this.remaining === '' || this.peekStartsWith('?') || this.peekStartsWith('#')) {
  603. return new UrlSegmentGroup([], {});
  604. }
  605. // The root segment group never has segments
  606. return new UrlSegmentGroup([], this.parseChildren());
  607. }
  608. parseQueryParams() {
  609. const params = {};
  610. if (this.consumeOptional('?')) {
  611. do {
  612. this.parseQueryParam(params);
  613. } while (this.consumeOptional('&'));
  614. }
  615. return params;
  616. }
  617. parseFragment() {
  618. return this.consumeOptional('#') ? decodeURIComponent(this.remaining) : null;
  619. }
  620. parseChildren() {
  621. if (this.remaining === '') {
  622. return {};
  623. }
  624. this.consumeOptional('/');
  625. const segments = [];
  626. if (!this.peekStartsWith('(')) {
  627. segments.push(this.parseSegment());
  628. }
  629. while (this.peekStartsWith('/') && !this.peekStartsWith('//') && !this.peekStartsWith('/(')) {
  630. this.capture('/');
  631. segments.push(this.parseSegment());
  632. }
  633. let children = {};
  634. if (this.peekStartsWith('/(')) {
  635. this.capture('/');
  636. children = this.parseParens(true);
  637. }
  638. let res = {};
  639. if (this.peekStartsWith('(')) {
  640. res = this.parseParens(false);
  641. }
  642. if (segments.length > 0 || Object.keys(children).length > 0) {
  643. res[PRIMARY_OUTLET] = new UrlSegmentGroup(segments, children);
  644. }
  645. return res;
  646. }
  647. // parse a segment with its matrix parameters
  648. // ie `name;k1=v1;k2`
  649. parseSegment() {
  650. const path = matchSegments(this.remaining);
  651. if (path === '' && this.peekStartsWith(';')) {
  652. throw new _RuntimeError(4009 /* RuntimeErrorCode.EMPTY_PATH_WITH_PARAMS */, (typeof ngDevMode === 'undefined' || ngDevMode) &&
  653. `Empty path url segment cannot have parameters: '${this.remaining}'.`);
  654. }
  655. this.capture(path);
  656. return new UrlSegment(decode(path), this.parseMatrixParams());
  657. }
  658. parseMatrixParams() {
  659. const params = {};
  660. while (this.consumeOptional(';')) {
  661. this.parseParam(params);
  662. }
  663. return params;
  664. }
  665. parseParam(params) {
  666. const key = matchMatrixKeySegments(this.remaining);
  667. if (!key) {
  668. return;
  669. }
  670. this.capture(key);
  671. let value = '';
  672. if (this.consumeOptional('=')) {
  673. const valueMatch = matchSegments(this.remaining);
  674. if (valueMatch) {
  675. value = valueMatch;
  676. this.capture(value);
  677. }
  678. }
  679. params[decode(key)] = decode(value);
  680. }
  681. // Parse a single query parameter `name[=value]`
  682. parseQueryParam(params) {
  683. const key = matchQueryParams(this.remaining);
  684. if (!key) {
  685. return;
  686. }
  687. this.capture(key);
  688. let value = '';
  689. if (this.consumeOptional('=')) {
  690. const valueMatch = matchUrlQueryParamValue(this.remaining);
  691. if (valueMatch) {
  692. value = valueMatch;
  693. this.capture(value);
  694. }
  695. }
  696. const decodedKey = decodeQuery(key);
  697. const decodedVal = decodeQuery(value);
  698. if (params.hasOwnProperty(decodedKey)) {
  699. // Append to existing values
  700. let currentVal = params[decodedKey];
  701. if (!Array.isArray(currentVal)) {
  702. currentVal = [currentVal];
  703. params[decodedKey] = currentVal;
  704. }
  705. currentVal.push(decodedVal);
  706. }
  707. else {
  708. // Create a new value
  709. params[decodedKey] = decodedVal;
  710. }
  711. }
  712. // parse `(a/b//outlet_name:c/d)`
  713. parseParens(allowPrimary) {
  714. const segments = {};
  715. this.capture('(');
  716. while (!this.consumeOptional(')') && this.remaining.length > 0) {
  717. const path = matchSegments(this.remaining);
  718. const next = this.remaining[path.length];
  719. // if is is not one of these characters, then the segment was unescaped
  720. // or the group was not closed
  721. if (next !== '/' && next !== ')' && next !== ';') {
  722. throw new _RuntimeError(4010 /* RuntimeErrorCode.UNPARSABLE_URL */, (typeof ngDevMode === 'undefined' || ngDevMode) && `Cannot parse url '${this.url}'`);
  723. }
  724. let outletName = undefined;
  725. if (path.indexOf(':') > -1) {
  726. outletName = path.slice(0, path.indexOf(':'));
  727. this.capture(outletName);
  728. this.capture(':');
  729. }
  730. else if (allowPrimary) {
  731. outletName = PRIMARY_OUTLET;
  732. }
  733. const children = this.parseChildren();
  734. segments[outletName] =
  735. Object.keys(children).length === 1
  736. ? children[PRIMARY_OUTLET]
  737. : new UrlSegmentGroup([], children);
  738. this.consumeOptional('//');
  739. }
  740. return segments;
  741. }
  742. peekStartsWith(str) {
  743. return this.remaining.startsWith(str);
  744. }
  745. // Consumes the prefix when it is present and returns whether it has been consumed
  746. consumeOptional(str) {
  747. if (this.peekStartsWith(str)) {
  748. this.remaining = this.remaining.substring(str.length);
  749. return true;
  750. }
  751. return false;
  752. }
  753. capture(str) {
  754. if (!this.consumeOptional(str)) {
  755. throw new _RuntimeError(4011 /* RuntimeErrorCode.UNEXPECTED_VALUE_IN_URL */, (typeof ngDevMode === 'undefined' || ngDevMode) && `Expected "${str}".`);
  756. }
  757. }
  758. }
  759. function createRoot(rootCandidate) {
  760. return rootCandidate.segments.length > 0
  761. ? new UrlSegmentGroup([], { [PRIMARY_OUTLET]: rootCandidate })
  762. : rootCandidate;
  763. }
  764. /**
  765. * Recursively
  766. * - merges primary segment children into their parents
  767. * - drops empty children (those which have no segments and no children themselves). This latter
  768. * prevents serializing a group into something like `/a(aux:)`, where `aux` is an empty child
  769. * segment.
  770. * - merges named outlets without a primary segment sibling into the children. This prevents
  771. * serializing a URL like `//(a:a)(b:b) instead of `/(a:a//b:b)` when the aux b route lives on the
  772. * root but the `a` route lives under an empty path primary route.
  773. */
  774. function squashSegmentGroup(segmentGroup) {
  775. const newChildren = {};
  776. for (const [childOutlet, child] of Object.entries(segmentGroup.children)) {
  777. const childCandidate = squashSegmentGroup(child);
  778. // moves named children in an empty path primary child into this group
  779. if (childOutlet === PRIMARY_OUTLET &&
  780. childCandidate.segments.length === 0 &&
  781. childCandidate.hasChildren()) {
  782. for (const [grandChildOutlet, grandChild] of Object.entries(childCandidate.children)) {
  783. newChildren[grandChildOutlet] = grandChild;
  784. }
  785. } // don't add empty children
  786. else if (childCandidate.segments.length > 0 || childCandidate.hasChildren()) {
  787. newChildren[childOutlet] = childCandidate;
  788. }
  789. }
  790. const s = new UrlSegmentGroup(segmentGroup.segments, newChildren);
  791. return mergeTrivialChildren(s);
  792. }
  793. /**
  794. * When possible, merges the primary outlet child into the parent `UrlSegmentGroup`.
  795. *
  796. * When a segment group has only one child which is a primary outlet, merges that child into the
  797. * parent. That is, the child segment group's segments are merged into the `s` and the child's
  798. * children become the children of `s`. Think of this like a 'squash', merging the child segment
  799. * group into the parent.
  800. */
  801. function mergeTrivialChildren(s) {
  802. if (s.numberOfChildren === 1 && s.children[PRIMARY_OUTLET]) {
  803. const c = s.children[PRIMARY_OUTLET];
  804. return new UrlSegmentGroup(s.segments.concat(c.segments), c.children);
  805. }
  806. return s;
  807. }
  808. function isUrlTree(v) {
  809. return v instanceof UrlTree;
  810. }
  811. /**
  812. * Creates a `UrlTree` relative to an `ActivatedRouteSnapshot`.
  813. *
  814. * @publicApi
  815. *
  816. *
  817. * @param relativeTo The `ActivatedRouteSnapshot` to apply the commands to
  818. * @param commands An array of URL fragments with which to construct the new URL tree.
  819. * If the path is static, can be the literal URL string. For a dynamic path, pass an array of path
  820. * segments, followed by the parameters for each segment.
  821. * The fragments are applied to the one provided in the `relativeTo` parameter.
  822. * @param queryParams The query parameters for the `UrlTree`. `null` if the `UrlTree` does not have
  823. * any query parameters.
  824. * @param fragment The fragment for the `UrlTree`. `null` if the `UrlTree` does not have a fragment.
  825. *
  826. * @usageNotes
  827. *
  828. * ```ts
  829. * // create /team/33/user/11
  830. * createUrlTreeFromSnapshot(snapshot, ['/team', 33, 'user', 11]);
  831. *
  832. * // create /team/33;expand=true/user/11
  833. * createUrlTreeFromSnapshot(snapshot, ['/team', 33, {expand: true}, 'user', 11]);
  834. *
  835. * // you can collapse static segments like this (this works only with the first passed-in value):
  836. * createUrlTreeFromSnapshot(snapshot, ['/team/33/user', userId]);
  837. *
  838. * // If the first segment can contain slashes, and you do not want the router to split it,
  839. * // you can do the following:
  840. * createUrlTreeFromSnapshot(snapshot, [{segmentPath: '/one/two'}]);
  841. *
  842. * // create /team/33/(user/11//right:chat)
  843. * createUrlTreeFromSnapshot(snapshot, ['/team', 33, {outlets: {primary: 'user/11', right:
  844. * 'chat'}}], null, null);
  845. *
  846. * // remove the right secondary node
  847. * createUrlTreeFromSnapshot(snapshot, ['/team', 33, {outlets: {primary: 'user/11', right: null}}]);
  848. *
  849. * // For the examples below, assume the current URL is for the `/team/33/user/11` and the
  850. * `ActivatedRouteSnapshot` points to `user/11`:
  851. *
  852. * // navigate to /team/33/user/11/details
  853. * createUrlTreeFromSnapshot(snapshot, ['details']);
  854. *
  855. * // navigate to /team/33/user/22
  856. * createUrlTreeFromSnapshot(snapshot, ['../22']);
  857. *
  858. * // navigate to /team/44/user/22
  859. * createUrlTreeFromSnapshot(snapshot, ['../../team/44/user/22']);
  860. * ```
  861. */
  862. function createUrlTreeFromSnapshot(relativeTo, commands, queryParams = null, fragment = null) {
  863. const relativeToUrlSegmentGroup = createSegmentGroupFromRoute(relativeTo);
  864. return createUrlTreeFromSegmentGroup(relativeToUrlSegmentGroup, commands, queryParams, fragment);
  865. }
  866. function createSegmentGroupFromRoute(route) {
  867. let targetGroup;
  868. function createSegmentGroupFromRouteRecursive(currentRoute) {
  869. const childOutlets = {};
  870. for (const childSnapshot of currentRoute.children) {
  871. const root = createSegmentGroupFromRouteRecursive(childSnapshot);
  872. childOutlets[childSnapshot.outlet] = root;
  873. }
  874. const segmentGroup = new UrlSegmentGroup(currentRoute.url, childOutlets);
  875. if (currentRoute === route) {
  876. targetGroup = segmentGroup;
  877. }
  878. return segmentGroup;
  879. }
  880. const rootCandidate = createSegmentGroupFromRouteRecursive(route.root);
  881. const rootSegmentGroup = createRoot(rootCandidate);
  882. return targetGroup ?? rootSegmentGroup;
  883. }
  884. function createUrlTreeFromSegmentGroup(relativeTo, commands, queryParams, fragment) {
  885. let root = relativeTo;
  886. while (root.parent) {
  887. root = root.parent;
  888. }
  889. // There are no commands so the `UrlTree` goes to the same path as the one created from the
  890. // `UrlSegmentGroup`. All we need to do is update the `queryParams` and `fragment` without
  891. // applying any other logic.
  892. if (commands.length === 0) {
  893. return tree(root, root, root, queryParams, fragment);
  894. }
  895. const nav = computeNavigation(commands);
  896. if (nav.toRoot()) {
  897. return tree(root, root, new UrlSegmentGroup([], {}), queryParams, fragment);
  898. }
  899. const position = findStartingPositionForTargetGroup(nav, root, relativeTo);
  900. const newSegmentGroup = position.processChildren
  901. ? updateSegmentGroupChildren(position.segmentGroup, position.index, nav.commands)
  902. : updateSegmentGroup(position.segmentGroup, position.index, nav.commands);
  903. return tree(root, position.segmentGroup, newSegmentGroup, queryParams, fragment);
  904. }
  905. function isMatrixParams(command) {
  906. return typeof command === 'object' && command != null && !command.outlets && !command.segmentPath;
  907. }
  908. /**
  909. * Determines if a given command has an `outlets` map. When we encounter a command
  910. * with an outlets k/v map, we need to apply each outlet individually to the existing segment.
  911. */
  912. function isCommandWithOutlets(command) {
  913. return typeof command === 'object' && command != null && command.outlets;
  914. }
  915. function tree(oldRoot, oldSegmentGroup, newSegmentGroup, queryParams, fragment) {
  916. let qp = {};
  917. if (queryParams) {
  918. Object.entries(queryParams).forEach(([name, value]) => {
  919. qp[name] = Array.isArray(value) ? value.map((v) => `${v}`) : `${value}`;
  920. });
  921. }
  922. let rootCandidate;
  923. if (oldRoot === oldSegmentGroup) {
  924. rootCandidate = newSegmentGroup;
  925. }
  926. else {
  927. rootCandidate = replaceSegment(oldRoot, oldSegmentGroup, newSegmentGroup);
  928. }
  929. const newRoot = createRoot(squashSegmentGroup(rootCandidate));
  930. return new UrlTree(newRoot, qp, fragment);
  931. }
  932. /**
  933. * Replaces the `oldSegment` which is located in some child of the `current` with the `newSegment`.
  934. * This also has the effect of creating new `UrlSegmentGroup` copies to update references. This
  935. * shouldn't be necessary but the fallback logic for an invalid ActivatedRoute in the creation uses
  936. * the Router's current url tree. If we don't create new segment groups, we end up modifying that
  937. * value.
  938. */
  939. function replaceSegment(current, oldSegment, newSegment) {
  940. const children = {};
  941. Object.entries(current.children).forEach(([outletName, c]) => {
  942. if (c === oldSegment) {
  943. children[outletName] = newSegment;
  944. }
  945. else {
  946. children[outletName] = replaceSegment(c, oldSegment, newSegment);
  947. }
  948. });
  949. return new UrlSegmentGroup(current.segments, children);
  950. }
  951. class Navigation {
  952. isAbsolute;
  953. numberOfDoubleDots;
  954. commands;
  955. constructor(isAbsolute, numberOfDoubleDots, commands) {
  956. this.isAbsolute = isAbsolute;
  957. this.numberOfDoubleDots = numberOfDoubleDots;
  958. this.commands = commands;
  959. if (isAbsolute && commands.length > 0 && isMatrixParams(commands[0])) {
  960. throw new _RuntimeError(4003 /* RuntimeErrorCode.ROOT_SEGMENT_MATRIX_PARAMS */, (typeof ngDevMode === 'undefined' || ngDevMode) &&
  961. 'Root segment cannot have matrix parameters');
  962. }
  963. const cmdWithOutlet = commands.find(isCommandWithOutlets);
  964. if (cmdWithOutlet && cmdWithOutlet !== last(commands)) {
  965. throw new _RuntimeError(4004 /* RuntimeErrorCode.MISPLACED_OUTLETS_COMMAND */, (typeof ngDevMode === 'undefined' || ngDevMode) &&
  966. '{outlets:{}} has to be the last command');
  967. }
  968. }
  969. toRoot() {
  970. return this.isAbsolute && this.commands.length === 1 && this.commands[0] == '/';
  971. }
  972. }
  973. /** Transforms commands to a normalized `Navigation` */
  974. function computeNavigation(commands) {
  975. if (typeof commands[0] === 'string' && commands.length === 1 && commands[0] === '/') {
  976. return new Navigation(true, 0, commands);
  977. }
  978. let numberOfDoubleDots = 0;
  979. let isAbsolute = false;
  980. const res = commands.reduce((res, cmd, cmdIdx) => {
  981. if (typeof cmd === 'object' && cmd != null) {
  982. if (cmd.outlets) {
  983. const outlets = {};
  984. Object.entries(cmd.outlets).forEach(([name, commands]) => {
  985. outlets[name] = typeof commands === 'string' ? commands.split('/') : commands;
  986. });
  987. return [...res, { outlets }];
  988. }
  989. if (cmd.segmentPath) {
  990. return [...res, cmd.segmentPath];
  991. }
  992. }
  993. if (!(typeof cmd === 'string')) {
  994. return [...res, cmd];
  995. }
  996. if (cmdIdx === 0) {
  997. cmd.split('/').forEach((urlPart, partIndex) => {
  998. if (partIndex == 0 && urlPart === '.') ;
  999. else if (partIndex == 0 && urlPart === '') {
  1000. // '/a'
  1001. isAbsolute = true;
  1002. }
  1003. else if (urlPart === '..') {
  1004. // '../a'
  1005. numberOfDoubleDots++;
  1006. }
  1007. else if (urlPart != '') {
  1008. res.push(urlPart);
  1009. }
  1010. });
  1011. return res;
  1012. }
  1013. return [...res, cmd];
  1014. }, []);
  1015. return new Navigation(isAbsolute, numberOfDoubleDots, res);
  1016. }
  1017. class Position {
  1018. segmentGroup;
  1019. processChildren;
  1020. index;
  1021. constructor(segmentGroup, processChildren, index) {
  1022. this.segmentGroup = segmentGroup;
  1023. this.processChildren = processChildren;
  1024. this.index = index;
  1025. }
  1026. }
  1027. function findStartingPositionForTargetGroup(nav, root, target) {
  1028. if (nav.isAbsolute) {
  1029. return new Position(root, true, 0);
  1030. }
  1031. if (!target) {
  1032. // `NaN` is used only to maintain backwards compatibility with incorrectly mocked
  1033. // `ActivatedRouteSnapshot` in tests. In prior versions of this code, the position here was
  1034. // determined based on an internal property that was rarely mocked, resulting in `NaN`. In
  1035. // reality, this code path should _never_ be touched since `target` is not allowed to be falsey.
  1036. return new Position(root, false, NaN);
  1037. }
  1038. if (target.parent === null) {
  1039. return new Position(target, true, 0);
  1040. }
  1041. const modifier = isMatrixParams(nav.commands[0]) ? 0 : 1;
  1042. const index = target.segments.length - 1 + modifier;
  1043. return createPositionApplyingDoubleDots(target, index, nav.numberOfDoubleDots);
  1044. }
  1045. function createPositionApplyingDoubleDots(group, index, numberOfDoubleDots) {
  1046. let g = group;
  1047. let ci = index;
  1048. let dd = numberOfDoubleDots;
  1049. while (dd > ci) {
  1050. dd -= ci;
  1051. g = g.parent;
  1052. if (!g) {
  1053. throw new _RuntimeError(4005 /* RuntimeErrorCode.INVALID_DOUBLE_DOTS */, (typeof ngDevMode === 'undefined' || ngDevMode) && "Invalid number of '../'");
  1054. }
  1055. ci = g.segments.length;
  1056. }
  1057. return new Position(g, false, ci - dd);
  1058. }
  1059. function getOutlets(commands) {
  1060. if (isCommandWithOutlets(commands[0])) {
  1061. return commands[0].outlets;
  1062. }
  1063. return { [PRIMARY_OUTLET]: commands };
  1064. }
  1065. function updateSegmentGroup(segmentGroup, startIndex, commands) {
  1066. segmentGroup ??= new UrlSegmentGroup([], {});
  1067. if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) {
  1068. return updateSegmentGroupChildren(segmentGroup, startIndex, commands);
  1069. }
  1070. const m = prefixedWith(segmentGroup, startIndex, commands);
  1071. const slicedCommands = commands.slice(m.commandIndex);
  1072. if (m.match && m.pathIndex < segmentGroup.segments.length) {
  1073. const g = new UrlSegmentGroup(segmentGroup.segments.slice(0, m.pathIndex), {});
  1074. g.children[PRIMARY_OUTLET] = new UrlSegmentGroup(segmentGroup.segments.slice(m.pathIndex), segmentGroup.children);
  1075. return updateSegmentGroupChildren(g, 0, slicedCommands);
  1076. }
  1077. else if (m.match && slicedCommands.length === 0) {
  1078. return new UrlSegmentGroup(segmentGroup.segments, {});
  1079. }
  1080. else if (m.match && !segmentGroup.hasChildren()) {
  1081. return createNewSegmentGroup(segmentGroup, startIndex, commands);
  1082. }
  1083. else if (m.match) {
  1084. return updateSegmentGroupChildren(segmentGroup, 0, slicedCommands);
  1085. }
  1086. else {
  1087. return createNewSegmentGroup(segmentGroup, startIndex, commands);
  1088. }
  1089. }
  1090. function updateSegmentGroupChildren(segmentGroup, startIndex, commands) {
  1091. if (commands.length === 0) {
  1092. return new UrlSegmentGroup(segmentGroup.segments, {});
  1093. }
  1094. else {
  1095. const outlets = getOutlets(commands);
  1096. const children = {};
  1097. // If the set of commands applies to anything other than the primary outlet and the child
  1098. // segment is an empty path primary segment on its own, we want to apply the commands to the
  1099. // empty child path rather than here. The outcome is that the empty primary child is effectively
  1100. // removed from the final output UrlTree. Imagine the following config:
  1101. //
  1102. // {path: '', children: [{path: '**', outlet: 'popup'}]}.
  1103. //
  1104. // Navigation to /(popup:a) will activate the child outlet correctly Given a follow-up
  1105. // navigation with commands
  1106. // ['/', {outlets: {'popup': 'b'}}], we _would not_ want to apply the outlet commands to the
  1107. // root segment because that would result in
  1108. // //(popup:a)(popup:b) since the outlet command got applied one level above where it appears in
  1109. // the `ActivatedRoute` rather than updating the existing one.
  1110. //
  1111. // Because empty paths do not appear in the URL segments and the fact that the segments used in
  1112. // the output `UrlTree` are squashed to eliminate these empty paths where possible
  1113. // https://github.com/angular/angular/blob/13f10de40e25c6900ca55bd83b36bd533dacfa9e/packages/router/src/url_tree.ts#L755
  1114. // it can be hard to determine what is the right thing to do when applying commands to a
  1115. // `UrlSegmentGroup` that is created from an "unsquashed"/expanded `ActivatedRoute` tree.
  1116. // This code effectively "squashes" empty path primary routes when they have no siblings on
  1117. // the same level of the tree.
  1118. if (Object.keys(outlets).some((o) => o !== PRIMARY_OUTLET) &&
  1119. segmentGroup.children[PRIMARY_OUTLET] &&
  1120. segmentGroup.numberOfChildren === 1 &&
  1121. segmentGroup.children[PRIMARY_OUTLET].segments.length === 0) {
  1122. const childrenOfEmptyChild = updateSegmentGroupChildren(segmentGroup.children[PRIMARY_OUTLET], startIndex, commands);
  1123. return new UrlSegmentGroup(segmentGroup.segments, childrenOfEmptyChild.children);
  1124. }
  1125. Object.entries(outlets).forEach(([outlet, commands]) => {
  1126. if (typeof commands === 'string') {
  1127. commands = [commands];
  1128. }
  1129. if (commands !== null) {
  1130. children[outlet] = updateSegmentGroup(segmentGroup.children[outlet], startIndex, commands);
  1131. }
  1132. });
  1133. Object.entries(segmentGroup.children).forEach(([childOutlet, child]) => {
  1134. if (outlets[childOutlet] === undefined) {
  1135. children[childOutlet] = child;
  1136. }
  1137. });
  1138. return new UrlSegmentGroup(segmentGroup.segments, children);
  1139. }
  1140. }
  1141. function prefixedWith(segmentGroup, startIndex, commands) {
  1142. let currentCommandIndex = 0;
  1143. let currentPathIndex = startIndex;
  1144. const noMatch = { match: false, pathIndex: 0, commandIndex: 0 };
  1145. while (currentPathIndex < segmentGroup.segments.length) {
  1146. if (currentCommandIndex >= commands.length)
  1147. return noMatch;
  1148. const path = segmentGroup.segments[currentPathIndex];
  1149. const command = commands[currentCommandIndex];
  1150. // Do not try to consume command as part of the prefixing if it has outlets because it can
  1151. // contain outlets other than the one being processed. Consuming the outlets command would
  1152. // result in other outlets being ignored.
  1153. if (isCommandWithOutlets(command)) {
  1154. break;
  1155. }
  1156. const curr = `${command}`;
  1157. const next = currentCommandIndex < commands.length - 1 ? commands[currentCommandIndex + 1] : null;
  1158. if (currentPathIndex > 0 && curr === undefined)
  1159. break;
  1160. if (curr && next && typeof next === 'object' && next.outlets === undefined) {
  1161. if (!compare(curr, next, path))
  1162. return noMatch;
  1163. currentCommandIndex += 2;
  1164. }
  1165. else {
  1166. if (!compare(curr, {}, path))
  1167. return noMatch;
  1168. currentCommandIndex++;
  1169. }
  1170. currentPathIndex++;
  1171. }
  1172. return { match: true, pathIndex: currentPathIndex, commandIndex: currentCommandIndex };
  1173. }
  1174. function createNewSegmentGroup(segmentGroup, startIndex, commands) {
  1175. const paths = segmentGroup.segments.slice(0, startIndex);
  1176. let i = 0;
  1177. while (i < commands.length) {
  1178. const command = commands[i];
  1179. if (isCommandWithOutlets(command)) {
  1180. const children = createNewSegmentChildren(command.outlets);
  1181. return new UrlSegmentGroup(paths, children);
  1182. }
  1183. // if we start with an object literal, we need to reuse the path part from the segment
  1184. if (i === 0 && isMatrixParams(commands[0])) {
  1185. const p = segmentGroup.segments[startIndex];
  1186. paths.push(new UrlSegment(p.path, stringify(commands[0])));
  1187. i++;
  1188. continue;
  1189. }
  1190. const curr = isCommandWithOutlets(command) ? command.outlets[PRIMARY_OUTLET] : `${command}`;
  1191. const next = i < commands.length - 1 ? commands[i + 1] : null;
  1192. if (curr && next && isMatrixParams(next)) {
  1193. paths.push(new UrlSegment(curr, stringify(next)));
  1194. i += 2;
  1195. }
  1196. else {
  1197. paths.push(new UrlSegment(curr, {}));
  1198. i++;
  1199. }
  1200. }
  1201. return new UrlSegmentGroup(paths, {});
  1202. }
  1203. function createNewSegmentChildren(outlets) {
  1204. const children = {};
  1205. Object.entries(outlets).forEach(([outlet, commands]) => {
  1206. if (typeof commands === 'string') {
  1207. commands = [commands];
  1208. }
  1209. if (commands !== null) {
  1210. children[outlet] = createNewSegmentGroup(new UrlSegmentGroup([], {}), 0, commands);
  1211. }
  1212. });
  1213. return children;
  1214. }
  1215. function stringify(params) {
  1216. const res = {};
  1217. Object.entries(params).forEach(([k, v]) => (res[k] = `${v}`));
  1218. return res;
  1219. }
  1220. function compare(path, params, segment) {
  1221. return path == segment.path && shallowEqual(params, segment.parameters);
  1222. }
  1223. const IMPERATIVE_NAVIGATION = 'imperative';
  1224. /**
  1225. * Identifies the type of a router event.
  1226. *
  1227. * @publicApi
  1228. */
  1229. var EventType;
  1230. (function (EventType) {
  1231. EventType[EventType["NavigationStart"] = 0] = "NavigationStart";
  1232. EventType[EventType["NavigationEnd"] = 1] = "NavigationEnd";
  1233. EventType[EventType["NavigationCancel"] = 2] = "NavigationCancel";
  1234. EventType[EventType["NavigationError"] = 3] = "NavigationError";
  1235. EventType[EventType["RoutesRecognized"] = 4] = "RoutesRecognized";
  1236. EventType[EventType["ResolveStart"] = 5] = "ResolveStart";
  1237. EventType[EventType["ResolveEnd"] = 6] = "ResolveEnd";
  1238. EventType[EventType["GuardsCheckStart"] = 7] = "GuardsCheckStart";
  1239. EventType[EventType["GuardsCheckEnd"] = 8] = "GuardsCheckEnd";
  1240. EventType[EventType["RouteConfigLoadStart"] = 9] = "RouteConfigLoadStart";
  1241. EventType[EventType["RouteConfigLoadEnd"] = 10] = "RouteConfigLoadEnd";
  1242. EventType[EventType["ChildActivationStart"] = 11] = "ChildActivationStart";
  1243. EventType[EventType["ChildActivationEnd"] = 12] = "ChildActivationEnd";
  1244. EventType[EventType["ActivationStart"] = 13] = "ActivationStart";
  1245. EventType[EventType["ActivationEnd"] = 14] = "ActivationEnd";
  1246. EventType[EventType["Scroll"] = 15] = "Scroll";
  1247. EventType[EventType["NavigationSkipped"] = 16] = "NavigationSkipped";
  1248. })(EventType || (EventType = {}));
  1249. /**
  1250. * Base for events the router goes through, as opposed to events tied to a specific
  1251. * route. Fired one time for any given navigation.
  1252. *
  1253. * The following code shows how a class subscribes to router events.
  1254. *
  1255. * ```ts
  1256. * import {Event, RouterEvent, Router} from '@angular/router';
  1257. *
  1258. * class MyService {
  1259. * constructor(public router: Router) {
  1260. * router.events.pipe(
  1261. * filter((e: Event | RouterEvent): e is RouterEvent => e instanceof RouterEvent)
  1262. * ).subscribe((e: RouterEvent) => {
  1263. * // Do something
  1264. * });
  1265. * }
  1266. * }
  1267. * ```
  1268. *
  1269. * @see {@link Event}
  1270. * @see [Router events summary](guide/routing/router-reference#router-events)
  1271. * @publicApi
  1272. */
  1273. class RouterEvent {
  1274. id;
  1275. url;
  1276. constructor(
  1277. /** A unique ID that the router assigns to every router navigation. */
  1278. id,
  1279. /** The URL that is the destination for this navigation. */
  1280. url) {
  1281. this.id = id;
  1282. this.url = url;
  1283. }
  1284. }
  1285. /**
  1286. * An event triggered when a navigation starts.
  1287. *
  1288. * @publicApi
  1289. */
  1290. class NavigationStart extends RouterEvent {
  1291. type = EventType.NavigationStart;
  1292. /**
  1293. * Identifies the call or event that triggered the navigation.
  1294. * An `imperative` trigger is a call to `router.navigateByUrl()` or `router.navigate()`.
  1295. *
  1296. * @see {@link NavigationEnd}
  1297. * @see {@link NavigationCancel}
  1298. * @see {@link NavigationError}
  1299. */
  1300. navigationTrigger;
  1301. /**
  1302. * The navigation state that was previously supplied to the `pushState` call,
  1303. * when the navigation is triggered by a `popstate` event. Otherwise null.
  1304. *
  1305. * The state object is defined by `NavigationExtras`, and contains any
  1306. * developer-defined state value, as well as a unique ID that
  1307. * the router assigns to every router transition/navigation.
  1308. *
  1309. * From the perspective of the router, the router never "goes back".
  1310. * When the user clicks on the back button in the browser,
  1311. * a new navigation ID is created.
  1312. *
  1313. * Use the ID in this previous-state object to differentiate between a newly created
  1314. * state and one returned to by a `popstate` event, so that you can restore some
  1315. * remembered state, such as scroll position.
  1316. *
  1317. */
  1318. restoredState;
  1319. constructor(
  1320. /** @docsNotRequired */
  1321. id,
  1322. /** @docsNotRequired */
  1323. url,
  1324. /** @docsNotRequired */
  1325. navigationTrigger = 'imperative',
  1326. /** @docsNotRequired */
  1327. restoredState = null) {
  1328. super(id, url);
  1329. this.navigationTrigger = navigationTrigger;
  1330. this.restoredState = restoredState;
  1331. }
  1332. /** @docsNotRequired */
  1333. toString() {
  1334. return `NavigationStart(id: ${this.id}, url: '${this.url}')`;
  1335. }
  1336. }
  1337. /**
  1338. * An event triggered when a navigation ends successfully.
  1339. *
  1340. * @see {@link NavigationStart}
  1341. * @see {@link NavigationCancel}
  1342. * @see {@link NavigationError}
  1343. *
  1344. * @publicApi
  1345. */
  1346. class NavigationEnd extends RouterEvent {
  1347. urlAfterRedirects;
  1348. type = EventType.NavigationEnd;
  1349. constructor(
  1350. /** @docsNotRequired */
  1351. id,
  1352. /** @docsNotRequired */
  1353. url,
  1354. /** @docsNotRequired */
  1355. urlAfterRedirects) {
  1356. super(id, url);
  1357. this.urlAfterRedirects = urlAfterRedirects;
  1358. }
  1359. /** @docsNotRequired */
  1360. toString() {
  1361. return `NavigationEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}')`;
  1362. }
  1363. }
  1364. /**
  1365. * A code for the `NavigationCancel` event of the `Router` to indicate the
  1366. * reason a navigation failed.
  1367. *
  1368. * @publicApi
  1369. */
  1370. var NavigationCancellationCode;
  1371. (function (NavigationCancellationCode) {
  1372. /**
  1373. * A navigation failed because a guard returned a `UrlTree` to redirect.
  1374. */
  1375. NavigationCancellationCode[NavigationCancellationCode["Redirect"] = 0] = "Redirect";
  1376. /**
  1377. * A navigation failed because a more recent navigation started.
  1378. */
  1379. NavigationCancellationCode[NavigationCancellationCode["SupersededByNewNavigation"] = 1] = "SupersededByNewNavigation";
  1380. /**
  1381. * A navigation failed because one of the resolvers completed without emitting a value.
  1382. */
  1383. NavigationCancellationCode[NavigationCancellationCode["NoDataFromResolver"] = 2] = "NoDataFromResolver";
  1384. /**
  1385. * A navigation failed because a guard returned `false`.
  1386. */
  1387. NavigationCancellationCode[NavigationCancellationCode["GuardRejected"] = 3] = "GuardRejected";
  1388. })(NavigationCancellationCode || (NavigationCancellationCode = {}));
  1389. /**
  1390. * A code for the `NavigationSkipped` event of the `Router` to indicate the
  1391. * reason a navigation was skipped.
  1392. *
  1393. * @publicApi
  1394. */
  1395. var NavigationSkippedCode;
  1396. (function (NavigationSkippedCode) {
  1397. /**
  1398. * A navigation was skipped because the navigation URL was the same as the current Router URL.
  1399. */
  1400. NavigationSkippedCode[NavigationSkippedCode["IgnoredSameUrlNavigation"] = 0] = "IgnoredSameUrlNavigation";
  1401. /**
  1402. * A navigation was skipped because the configured `UrlHandlingStrategy` return `false` for both
  1403. * the current Router URL and the target of the navigation.
  1404. *
  1405. * @see {@link UrlHandlingStrategy}
  1406. */
  1407. NavigationSkippedCode[NavigationSkippedCode["IgnoredByUrlHandlingStrategy"] = 1] = "IgnoredByUrlHandlingStrategy";
  1408. })(NavigationSkippedCode || (NavigationSkippedCode = {}));
  1409. /**
  1410. * An event triggered when a navigation is canceled, directly or indirectly.
  1411. * This can happen for several reasons including when a route guard
  1412. * returns `false` or initiates a redirect by returning a `UrlTree`.
  1413. *
  1414. * @see {@link NavigationStart}
  1415. * @see {@link NavigationEnd}
  1416. * @see {@link NavigationError}
  1417. *
  1418. * @publicApi
  1419. */
  1420. class NavigationCancel extends RouterEvent {
  1421. reason;
  1422. code;
  1423. type = EventType.NavigationCancel;
  1424. constructor(
  1425. /** @docsNotRequired */
  1426. id,
  1427. /** @docsNotRequired */
  1428. url,
  1429. /**
  1430. * A description of why the navigation was cancelled. For debug purposes only. Use `code`
  1431. * instead for a stable cancellation reason that can be used in production.
  1432. */
  1433. reason,
  1434. /**
  1435. * A code to indicate why the navigation was canceled. This cancellation code is stable for
  1436. * the reason and can be relied on whereas the `reason` string could change and should not be
  1437. * used in production.
  1438. */
  1439. code) {
  1440. super(id, url);
  1441. this.reason = reason;
  1442. this.code = code;
  1443. }
  1444. /** @docsNotRequired */
  1445. toString() {
  1446. return `NavigationCancel(id: ${this.id}, url: '${this.url}')`;
  1447. }
  1448. }
  1449. /**
  1450. * An event triggered when a navigation is skipped.
  1451. * This can happen for a couple reasons including onSameUrlHandling
  1452. * is set to `ignore` and the navigation URL is not different than the
  1453. * current state.
  1454. *
  1455. * @publicApi
  1456. */
  1457. class NavigationSkipped extends RouterEvent {
  1458. reason;
  1459. code;
  1460. type = EventType.NavigationSkipped;
  1461. constructor(
  1462. /** @docsNotRequired */
  1463. id,
  1464. /** @docsNotRequired */
  1465. url,
  1466. /**
  1467. * A description of why the navigation was skipped. For debug purposes only. Use `code`
  1468. * instead for a stable skipped reason that can be used in production.
  1469. */
  1470. reason,
  1471. /**
  1472. * A code to indicate why the navigation was skipped. This code is stable for
  1473. * the reason and can be relied on whereas the `reason` string could change and should not be
  1474. * used in production.
  1475. */
  1476. code) {
  1477. super(id, url);
  1478. this.reason = reason;
  1479. this.code = code;
  1480. }
  1481. }
  1482. /**
  1483. * An event triggered when a navigation fails due to an unexpected error.
  1484. *
  1485. * @see {@link NavigationStart}
  1486. * @see {@link NavigationEnd}
  1487. * @see {@link NavigationCancel}
  1488. *
  1489. * @publicApi
  1490. */
  1491. class NavigationError extends RouterEvent {
  1492. error;
  1493. target;
  1494. type = EventType.NavigationError;
  1495. constructor(
  1496. /** @docsNotRequired */
  1497. id,
  1498. /** @docsNotRequired */
  1499. url,
  1500. /** @docsNotRequired */
  1501. error,
  1502. /**
  1503. * The target of the navigation when the error occurred.
  1504. *
  1505. * Note that this can be `undefined` because an error could have occurred before the
  1506. * `RouterStateSnapshot` was created for the navigation.
  1507. */
  1508. target) {
  1509. super(id, url);
  1510. this.error = error;
  1511. this.target = target;
  1512. }
  1513. /** @docsNotRequired */
  1514. toString() {
  1515. return `NavigationError(id: ${this.id}, url: '${this.url}', error: ${this.error})`;
  1516. }
  1517. }
  1518. /**
  1519. * An event triggered when routes are recognized.
  1520. *
  1521. * @publicApi
  1522. */
  1523. class RoutesRecognized extends RouterEvent {
  1524. urlAfterRedirects;
  1525. state;
  1526. type = EventType.RoutesRecognized;
  1527. constructor(
  1528. /** @docsNotRequired */
  1529. id,
  1530. /** @docsNotRequired */
  1531. url,
  1532. /** @docsNotRequired */
  1533. urlAfterRedirects,
  1534. /** @docsNotRequired */
  1535. state) {
  1536. super(id, url);
  1537. this.urlAfterRedirects = urlAfterRedirects;
  1538. this.state = state;
  1539. }
  1540. /** @docsNotRequired */
  1541. toString() {
  1542. return `RoutesRecognized(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`;
  1543. }
  1544. }
  1545. /**
  1546. * An event triggered at the start of the Guard phase of routing.
  1547. *
  1548. * @see {@link GuardsCheckEnd}
  1549. *
  1550. * @publicApi
  1551. */
  1552. class GuardsCheckStart extends RouterEvent {
  1553. urlAfterRedirects;
  1554. state;
  1555. type = EventType.GuardsCheckStart;
  1556. constructor(
  1557. /** @docsNotRequired */
  1558. id,
  1559. /** @docsNotRequired */
  1560. url,
  1561. /** @docsNotRequired */
  1562. urlAfterRedirects,
  1563. /** @docsNotRequired */
  1564. state) {
  1565. super(id, url);
  1566. this.urlAfterRedirects = urlAfterRedirects;
  1567. this.state = state;
  1568. }
  1569. toString() {
  1570. return `GuardsCheckStart(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`;
  1571. }
  1572. }
  1573. /**
  1574. * An event triggered at the end of the Guard phase of routing.
  1575. *
  1576. * @see {@link GuardsCheckStart}
  1577. *
  1578. * @publicApi
  1579. */
  1580. class GuardsCheckEnd extends RouterEvent {
  1581. urlAfterRedirects;
  1582. state;
  1583. shouldActivate;
  1584. type = EventType.GuardsCheckEnd;
  1585. constructor(
  1586. /** @docsNotRequired */
  1587. id,
  1588. /** @docsNotRequired */
  1589. url,
  1590. /** @docsNotRequired */
  1591. urlAfterRedirects,
  1592. /** @docsNotRequired */
  1593. state,
  1594. /** @docsNotRequired */
  1595. shouldActivate) {
  1596. super(id, url);
  1597. this.urlAfterRedirects = urlAfterRedirects;
  1598. this.state = state;
  1599. this.shouldActivate = shouldActivate;
  1600. }
  1601. toString() {
  1602. return `GuardsCheckEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state}, shouldActivate: ${this.shouldActivate})`;
  1603. }
  1604. }
  1605. /**
  1606. * An event triggered at the start of the Resolve phase of routing.
  1607. *
  1608. * Runs in the "resolve" phase whether or not there is anything to resolve.
  1609. * In future, may change to only run when there are things to be resolved.
  1610. *
  1611. * @see {@link ResolveEnd}
  1612. *
  1613. * @publicApi
  1614. */
  1615. class ResolveStart extends RouterEvent {
  1616. urlAfterRedirects;
  1617. state;
  1618. type = EventType.ResolveStart;
  1619. constructor(
  1620. /** @docsNotRequired */
  1621. id,
  1622. /** @docsNotRequired */
  1623. url,
  1624. /** @docsNotRequired */
  1625. urlAfterRedirects,
  1626. /** @docsNotRequired */
  1627. state) {
  1628. super(id, url);
  1629. this.urlAfterRedirects = urlAfterRedirects;
  1630. this.state = state;
  1631. }
  1632. toString() {
  1633. return `ResolveStart(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`;
  1634. }
  1635. }
  1636. /**
  1637. * An event triggered at the end of the Resolve phase of routing.
  1638. * @see {@link ResolveStart}
  1639. *
  1640. * @publicApi
  1641. */
  1642. class ResolveEnd extends RouterEvent {
  1643. urlAfterRedirects;
  1644. state;
  1645. type = EventType.ResolveEnd;
  1646. constructor(
  1647. /** @docsNotRequired */
  1648. id,
  1649. /** @docsNotRequired */
  1650. url,
  1651. /** @docsNotRequired */
  1652. urlAfterRedirects,
  1653. /** @docsNotRequired */
  1654. state) {
  1655. super(id, url);
  1656. this.urlAfterRedirects = urlAfterRedirects;
  1657. this.state = state;
  1658. }
  1659. toString() {
  1660. return `ResolveEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`;
  1661. }
  1662. }
  1663. /**
  1664. * An event triggered before lazy loading a route configuration.
  1665. *
  1666. * @see {@link RouteConfigLoadEnd}
  1667. *
  1668. * @publicApi
  1669. */
  1670. class RouteConfigLoadStart {
  1671. route;
  1672. type = EventType.RouteConfigLoadStart;
  1673. constructor(
  1674. /** @docsNotRequired */
  1675. route) {
  1676. this.route = route;
  1677. }
  1678. toString() {
  1679. return `RouteConfigLoadStart(path: ${this.route.path})`;
  1680. }
  1681. }
  1682. /**
  1683. * An event triggered when a route has been lazy loaded.
  1684. *
  1685. * @see {@link RouteConfigLoadStart}
  1686. *
  1687. * @publicApi
  1688. */
  1689. class RouteConfigLoadEnd {
  1690. route;
  1691. type = EventType.RouteConfigLoadEnd;
  1692. constructor(
  1693. /** @docsNotRequired */
  1694. route) {
  1695. this.route = route;
  1696. }
  1697. toString() {
  1698. return `RouteConfigLoadEnd(path: ${this.route.path})`;
  1699. }
  1700. }
  1701. /**
  1702. * An event triggered at the start of the child-activation
  1703. * part of the Resolve phase of routing.
  1704. * @see {@link ChildActivationEnd}
  1705. * @see {@link ResolveStart}
  1706. *
  1707. * @publicApi
  1708. */
  1709. class ChildActivationStart {
  1710. snapshot;
  1711. type = EventType.ChildActivationStart;
  1712. constructor(
  1713. /** @docsNotRequired */
  1714. snapshot) {
  1715. this.snapshot = snapshot;
  1716. }
  1717. toString() {
  1718. const path = (this.snapshot.routeConfig && this.snapshot.routeConfig.path) || '';
  1719. return `ChildActivationStart(path: '${path}')`;
  1720. }
  1721. }
  1722. /**
  1723. * An event triggered at the end of the child-activation part
  1724. * of the Resolve phase of routing.
  1725. * @see {@link ChildActivationStart}
  1726. * @see {@link ResolveStart}
  1727. * @publicApi
  1728. */
  1729. class ChildActivationEnd {
  1730. snapshot;
  1731. type = EventType.ChildActivationEnd;
  1732. constructor(
  1733. /** @docsNotRequired */
  1734. snapshot) {
  1735. this.snapshot = snapshot;
  1736. }
  1737. toString() {
  1738. const path = (this.snapshot.routeConfig && this.snapshot.routeConfig.path) || '';
  1739. return `ChildActivationEnd(path: '${path}')`;
  1740. }
  1741. }
  1742. /**
  1743. * An event triggered at the start of the activation part
  1744. * of the Resolve phase of routing.
  1745. * @see {@link ActivationEnd}
  1746. * @see {@link ResolveStart}
  1747. *
  1748. * @publicApi
  1749. */
  1750. class ActivationStart {
  1751. snapshot;
  1752. type = EventType.ActivationStart;
  1753. constructor(
  1754. /** @docsNotRequired */
  1755. snapshot) {
  1756. this.snapshot = snapshot;
  1757. }
  1758. toString() {
  1759. const path = (this.snapshot.routeConfig && this.snapshot.routeConfig.path) || '';
  1760. return `ActivationStart(path: '${path}')`;
  1761. }
  1762. }
  1763. /**
  1764. * An event triggered at the end of the activation part
  1765. * of the Resolve phase of routing.
  1766. * @see {@link ActivationStart}
  1767. * @see {@link ResolveStart}
  1768. *
  1769. * @publicApi
  1770. */
  1771. class ActivationEnd {
  1772. snapshot;
  1773. type = EventType.ActivationEnd;
  1774. constructor(
  1775. /** @docsNotRequired */
  1776. snapshot) {
  1777. this.snapshot = snapshot;
  1778. }
  1779. toString() {
  1780. const path = (this.snapshot.routeConfig && this.snapshot.routeConfig.path) || '';
  1781. return `ActivationEnd(path: '${path}')`;
  1782. }
  1783. }
  1784. /**
  1785. * An event triggered by scrolling.
  1786. *
  1787. * @publicApi
  1788. */
  1789. class Scroll {
  1790. routerEvent;
  1791. position;
  1792. anchor;
  1793. type = EventType.Scroll;
  1794. constructor(
  1795. /** @docsNotRequired */
  1796. routerEvent,
  1797. /** @docsNotRequired */
  1798. position,
  1799. /** @docsNotRequired */
  1800. anchor) {
  1801. this.routerEvent = routerEvent;
  1802. this.position = position;
  1803. this.anchor = anchor;
  1804. }
  1805. toString() {
  1806. const pos = this.position ? `${this.position[0]}, ${this.position[1]}` : null;
  1807. return `Scroll(anchor: '${this.anchor}', position: '${pos}')`;
  1808. }
  1809. }
  1810. class BeforeActivateRoutes {
  1811. }
  1812. class RedirectRequest {
  1813. url;
  1814. navigationBehaviorOptions;
  1815. constructor(url, navigationBehaviorOptions) {
  1816. this.url = url;
  1817. this.navigationBehaviorOptions = navigationBehaviorOptions;
  1818. }
  1819. }
  1820. function stringifyEvent(routerEvent) {
  1821. switch (routerEvent.type) {
  1822. case EventType.ActivationEnd:
  1823. return `ActivationEnd(path: '${routerEvent.snapshot.routeConfig?.path || ''}')`;
  1824. case EventType.ActivationStart:
  1825. return `ActivationStart(path: '${routerEvent.snapshot.routeConfig?.path || ''}')`;
  1826. case EventType.ChildActivationEnd:
  1827. return `ChildActivationEnd(path: '${routerEvent.snapshot.routeConfig?.path || ''}')`;
  1828. case EventType.ChildActivationStart:
  1829. return `ChildActivationStart(path: '${routerEvent.snapshot.routeConfig?.path || ''}')`;
  1830. case EventType.GuardsCheckEnd:
  1831. return `GuardsCheckEnd(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}', state: ${routerEvent.state}, shouldActivate: ${routerEvent.shouldActivate})`;
  1832. case EventType.GuardsCheckStart:
  1833. return `GuardsCheckStart(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}', state: ${routerEvent.state})`;
  1834. case EventType.NavigationCancel:
  1835. return `NavigationCancel(id: ${routerEvent.id}, url: '${routerEvent.url}')`;
  1836. case EventType.NavigationSkipped:
  1837. return `NavigationSkipped(id: ${routerEvent.id}, url: '${routerEvent.url}')`;
  1838. case EventType.NavigationEnd:
  1839. return `NavigationEnd(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}')`;
  1840. case EventType.NavigationError:
  1841. return `NavigationError(id: ${routerEvent.id}, url: '${routerEvent.url}', error: ${routerEvent.error})`;
  1842. case EventType.NavigationStart:
  1843. return `NavigationStart(id: ${routerEvent.id}, url: '${routerEvent.url}')`;
  1844. case EventType.ResolveEnd:
  1845. return `ResolveEnd(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}', state: ${routerEvent.state})`;
  1846. case EventType.ResolveStart:
  1847. return `ResolveStart(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}', state: ${routerEvent.state})`;
  1848. case EventType.RouteConfigLoadEnd:
  1849. return `RouteConfigLoadEnd(path: ${routerEvent.route.path})`;
  1850. case EventType.RouteConfigLoadStart:
  1851. return `RouteConfigLoadStart(path: ${routerEvent.route.path})`;
  1852. case EventType.RoutesRecognized:
  1853. return `RoutesRecognized(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}', state: ${routerEvent.state})`;
  1854. case EventType.Scroll:
  1855. const pos = routerEvent.position
  1856. ? `${routerEvent.position[0]}, ${routerEvent.position[1]}`
  1857. : null;
  1858. return `Scroll(anchor: '${routerEvent.anchor}', position: '${pos}')`;
  1859. }
  1860. }
  1861. /**
  1862. * Creates an `EnvironmentInjector` if the `Route` has providers and one does not already exist
  1863. * and returns the injector. Otherwise, if the `Route` does not have `providers`, returns the
  1864. * `currentInjector`.
  1865. *
  1866. * @param route The route that might have providers
  1867. * @param currentInjector The parent injector of the `Route`
  1868. */
  1869. function getOrCreateRouteInjectorIfNeeded(route, currentInjector) {
  1870. if (route.providers && !route._injector) {
  1871. route._injector = createEnvironmentInjector(route.providers, currentInjector, `Route: ${route.path}`);
  1872. }
  1873. return route._injector ?? currentInjector;
  1874. }
  1875. function validateConfig(config, parentPath = '', requireStandaloneComponents = false) {
  1876. // forEach doesn't iterate undefined values
  1877. for (let i = 0; i < config.length; i++) {
  1878. const route = config[i];
  1879. const fullPath = getFullPath(parentPath, route);
  1880. validateNode(route, fullPath, requireStandaloneComponents);
  1881. }
  1882. }
  1883. function assertStandalone(fullPath, component) {
  1884. if (component && _isNgModule(component)) {
  1885. throw new _RuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}'. You are using 'loadComponent' with a module, ` +
  1886. `but it must be used with standalone components. Use 'loadChildren' instead.`);
  1887. }
  1888. else if (component && !isStandalone(component)) {
  1889. throw new _RuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}'. The component must be standalone.`);
  1890. }
  1891. }
  1892. function validateNode(route, fullPath, requireStandaloneComponents) {
  1893. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  1894. if (!route) {
  1895. throw new _RuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `
  1896. Invalid configuration of route '${fullPath}': Encountered undefined route.
  1897. The reason might be an extra comma.
  1898. Example:
  1899. const routes: Routes = [
  1900. { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
  1901. { path: 'dashboard', component: DashboardComponent },, << two commas
  1902. { path: 'detail/:id', component: HeroDetailComponent }
  1903. ];
  1904. `);
  1905. }
  1906. if (Array.isArray(route)) {
  1907. throw new _RuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': Array cannot be specified`);
  1908. }
  1909. if (!route.redirectTo &&
  1910. !route.component &&
  1911. !route.loadComponent &&
  1912. !route.children &&
  1913. !route.loadChildren &&
  1914. route.outlet &&
  1915. route.outlet !== PRIMARY_OUTLET) {
  1916. throw new _RuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': a componentless route without children or loadChildren cannot have a named outlet set`);
  1917. }
  1918. if (route.redirectTo && route.children) {
  1919. throw new _RuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': redirectTo and children cannot be used together`);
  1920. }
  1921. if (route.redirectTo && route.loadChildren) {
  1922. throw new _RuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': redirectTo and loadChildren cannot be used together`);
  1923. }
  1924. if (route.children && route.loadChildren) {
  1925. throw new _RuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': children and loadChildren cannot be used together`);
  1926. }
  1927. if (route.redirectTo && (route.component || route.loadComponent)) {
  1928. throw new _RuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': redirectTo and component/loadComponent cannot be used together`);
  1929. }
  1930. if (route.component && route.loadComponent) {
  1931. throw new _RuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': component and loadComponent cannot be used together`);
  1932. }
  1933. if (route.redirectTo && route.canActivate) {
  1934. throw new _RuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': redirectTo and canActivate cannot be used together. Redirects happen before activation ` +
  1935. `so canActivate will never be executed.`);
  1936. }
  1937. if (route.path && route.matcher) {
  1938. throw new _RuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': path and matcher cannot be used together`);
  1939. }
  1940. if (route.redirectTo === void 0 &&
  1941. !route.component &&
  1942. !route.loadComponent &&
  1943. !route.children &&
  1944. !route.loadChildren) {
  1945. throw new _RuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}'. One of the following must be provided: component, loadComponent, redirectTo, children or loadChildren`);
  1946. }
  1947. if (route.path === void 0 && route.matcher === void 0) {
  1948. throw new _RuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': routes must have either a path or a matcher specified`);
  1949. }
  1950. if (typeof route.path === 'string' && route.path.charAt(0) === '/') {
  1951. throw new _RuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': path cannot start with a slash`);
  1952. }
  1953. if (route.path === '' && route.redirectTo !== void 0 && route.pathMatch === void 0) {
  1954. const exp = `The default value of 'pathMatch' is 'prefix', but often the intent is to use 'full'.`;
  1955. throw new _RuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '{path: "${fullPath}", redirectTo: "${route.redirectTo}"}': please provide 'pathMatch'. ${exp}`);
  1956. }
  1957. if (requireStandaloneComponents) {
  1958. assertStandalone(fullPath, route.component);
  1959. }
  1960. }
  1961. if (route.children) {
  1962. validateConfig(route.children, fullPath, requireStandaloneComponents);
  1963. }
  1964. }
  1965. function getFullPath(parentPath, currentRoute) {
  1966. if (!currentRoute) {
  1967. return parentPath;
  1968. }
  1969. if (!parentPath && !currentRoute.path) {
  1970. return '';
  1971. }
  1972. else if (parentPath && !currentRoute.path) {
  1973. return `${parentPath}/`;
  1974. }
  1975. else if (!parentPath && currentRoute.path) {
  1976. return currentRoute.path;
  1977. }
  1978. else {
  1979. return `${parentPath}/${currentRoute.path}`;
  1980. }
  1981. }
  1982. /** Returns the `route.outlet` or PRIMARY_OUTLET if none exists. */
  1983. function getOutlet(route) {
  1984. return route.outlet || PRIMARY_OUTLET;
  1985. }
  1986. /**
  1987. * Sorts the `routes` such that the ones with an outlet matching `outletName` come first.
  1988. * The order of the configs is otherwise preserved.
  1989. */
  1990. function sortByMatchingOutlets(routes, outletName) {
  1991. const sortedConfig = routes.filter((r) => getOutlet(r) === outletName);
  1992. sortedConfig.push(...routes.filter((r) => getOutlet(r) !== outletName));
  1993. return sortedConfig;
  1994. }
  1995. /**
  1996. * Gets the first injector in the snapshot's parent tree.
  1997. *
  1998. * If the `Route` has a static list of providers, the returned injector will be the one created from
  1999. * those. If it does not exist, the returned injector may come from the parents, which may be from a
  2000. * loaded config or their static providers.
  2001. *
  2002. * Returns `null` if there is neither this nor any parents have a stored injector.
  2003. *
  2004. * Generally used for retrieving the injector to use for getting tokens for guards/resolvers and
  2005. * also used for getting the correct injector to use for creating components.
  2006. */
  2007. function getClosestRouteInjector(snapshot) {
  2008. if (!snapshot)
  2009. return null;
  2010. // If the current route has its own injector, which is created from the static providers on the
  2011. // route itself, we should use that. Otherwise, we start at the parent since we do not want to
  2012. // include the lazy loaded injector from this route.
  2013. if (snapshot.routeConfig?._injector) {
  2014. return snapshot.routeConfig._injector;
  2015. }
  2016. for (let s = snapshot.parent; s; s = s.parent) {
  2017. const route = s.routeConfig;
  2018. // Note that the order here is important. `_loadedInjector` stored on the route with
  2019. // `loadChildren: () => NgModule` so it applies to child routes with priority. The `_injector`
  2020. // is created from the static providers on that parent route, so it applies to the children as
  2021. // well, but only if there is no lazy loaded NgModuleRef injector.
  2022. if (route?._loadedInjector)
  2023. return route._loadedInjector;
  2024. if (route?._injector)
  2025. return route._injector;
  2026. }
  2027. return null;
  2028. }
  2029. /**
  2030. * Store contextual information about a `RouterOutlet`
  2031. *
  2032. * @publicApi
  2033. */
  2034. class OutletContext {
  2035. rootInjector;
  2036. outlet = null;
  2037. route = null;
  2038. children;
  2039. attachRef = null;
  2040. get injector() {
  2041. return getClosestRouteInjector(this.route?.snapshot) ?? this.rootInjector;
  2042. }
  2043. constructor(rootInjector) {
  2044. this.rootInjector = rootInjector;
  2045. this.children = new ChildrenOutletContexts(this.rootInjector);
  2046. }
  2047. }
  2048. /**
  2049. * Store contextual information about the children (= nested) `RouterOutlet`
  2050. *
  2051. * @publicApi
  2052. */
  2053. class ChildrenOutletContexts {
  2054. rootInjector;
  2055. // contexts for child outlets, by name.
  2056. contexts = new Map();
  2057. /** @docs-private */
  2058. constructor(rootInjector) {
  2059. this.rootInjector = rootInjector;
  2060. }
  2061. /** Called when a `RouterOutlet` directive is instantiated */
  2062. onChildOutletCreated(childName, outlet) {
  2063. const context = this.getOrCreateContext(childName);
  2064. context.outlet = outlet;
  2065. this.contexts.set(childName, context);
  2066. }
  2067. /**
  2068. * Called when a `RouterOutlet` directive is destroyed.
  2069. * We need to keep the context as the outlet could be destroyed inside a NgIf and might be
  2070. * re-created later.
  2071. */
  2072. onChildOutletDestroyed(childName) {
  2073. const context = this.getContext(childName);
  2074. if (context) {
  2075. context.outlet = null;
  2076. context.attachRef = null;
  2077. }
  2078. }
  2079. /**
  2080. * Called when the corresponding route is deactivated during navigation.
  2081. * Because the component get destroyed, all children outlet are destroyed.
  2082. */
  2083. onOutletDeactivated() {
  2084. const contexts = this.contexts;
  2085. this.contexts = new Map();
  2086. return contexts;
  2087. }
  2088. onOutletReAttached(contexts) {
  2089. this.contexts = contexts;
  2090. }
  2091. getOrCreateContext(childName) {
  2092. let context = this.getContext(childName);
  2093. if (!context) {
  2094. context = new OutletContext(this.rootInjector);
  2095. this.contexts.set(childName, context);
  2096. }
  2097. return context;
  2098. }
  2099. getContext(childName) {
  2100. return this.contexts.get(childName) || null;
  2101. }
  2102. static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: ChildrenOutletContexts, deps: [{ token: i0.EnvironmentInjector }], target: i0.ɵɵFactoryTarget.Injectable });
  2103. static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: ChildrenOutletContexts, providedIn: 'root' });
  2104. }
  2105. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: ChildrenOutletContexts, decorators: [{
  2106. type: Injectable,
  2107. args: [{ providedIn: 'root' }]
  2108. }], ctorParameters: () => [{ type: i0.EnvironmentInjector }] });
  2109. class Tree {
  2110. /** @internal */
  2111. _root;
  2112. constructor(root) {
  2113. this._root = root;
  2114. }
  2115. get root() {
  2116. return this._root.value;
  2117. }
  2118. /**
  2119. * @internal
  2120. */
  2121. parent(t) {
  2122. const p = this.pathFromRoot(t);
  2123. return p.length > 1 ? p[p.length - 2] : null;
  2124. }
  2125. /**
  2126. * @internal
  2127. */
  2128. children(t) {
  2129. const n = findNode(t, this._root);
  2130. return n ? n.children.map((t) => t.value) : [];
  2131. }
  2132. /**
  2133. * @internal
  2134. */
  2135. firstChild(t) {
  2136. const n = findNode(t, this._root);
  2137. return n && n.children.length > 0 ? n.children[0].value : null;
  2138. }
  2139. /**
  2140. * @internal
  2141. */
  2142. siblings(t) {
  2143. const p = findPath(t, this._root);
  2144. if (p.length < 2)
  2145. return [];
  2146. const c = p[p.length - 2].children.map((c) => c.value);
  2147. return c.filter((cc) => cc !== t);
  2148. }
  2149. /**
  2150. * @internal
  2151. */
  2152. pathFromRoot(t) {
  2153. return findPath(t, this._root).map((s) => s.value);
  2154. }
  2155. }
  2156. // DFS for the node matching the value
  2157. function findNode(value, node) {
  2158. if (value === node.value)
  2159. return node;
  2160. for (const child of node.children) {
  2161. const node = findNode(value, child);
  2162. if (node)
  2163. return node;
  2164. }
  2165. return null;
  2166. }
  2167. // Return the path to the node with the given value using DFS
  2168. function findPath(value, node) {
  2169. if (value === node.value)
  2170. return [node];
  2171. for (const child of node.children) {
  2172. const path = findPath(value, child);
  2173. if (path.length) {
  2174. path.unshift(node);
  2175. return path;
  2176. }
  2177. }
  2178. return [];
  2179. }
  2180. class TreeNode {
  2181. value;
  2182. children;
  2183. constructor(value, children) {
  2184. this.value = value;
  2185. this.children = children;
  2186. }
  2187. toString() {
  2188. return `TreeNode(${this.value})`;
  2189. }
  2190. }
  2191. // Return the list of T indexed by outlet name
  2192. function nodeChildrenAsMap(node) {
  2193. const map = {};
  2194. if (node) {
  2195. node.children.forEach((child) => (map[child.value.outlet] = child));
  2196. }
  2197. return map;
  2198. }
  2199. /**
  2200. * Represents the state of the router as a tree of activated routes.
  2201. *
  2202. * @usageNotes
  2203. *
  2204. * Every node in the route tree is an `ActivatedRoute` instance
  2205. * that knows about the "consumed" URL segments, the extracted parameters,
  2206. * and the resolved data.
  2207. * Use the `ActivatedRoute` properties to traverse the tree from any node.
  2208. *
  2209. * The following fragment shows how a component gets the root node
  2210. * of the current state to establish its own route tree:
  2211. *
  2212. * ```ts
  2213. * @Component({templateUrl:'template.html'})
  2214. * class MyComponent {
  2215. * constructor(router: Router) {
  2216. * const state: RouterState = router.routerState;
  2217. * const root: ActivatedRoute = state.root;
  2218. * const child = root.firstChild;
  2219. * const id: Observable<string> = child.params.map(p => p.id);
  2220. * //...
  2221. * }
  2222. * }
  2223. * ```
  2224. *
  2225. * @see {@link ActivatedRoute}
  2226. * @see [Getting route information](guide/routing/common-router-tasks#getting-route-information)
  2227. *
  2228. * @publicApi
  2229. */
  2230. class RouterState extends Tree {
  2231. snapshot;
  2232. /** @internal */
  2233. constructor(root,
  2234. /** The current snapshot of the router state */
  2235. snapshot) {
  2236. super(root);
  2237. this.snapshot = snapshot;
  2238. setRouterState(this, root);
  2239. }
  2240. toString() {
  2241. return this.snapshot.toString();
  2242. }
  2243. }
  2244. function createEmptyState(rootComponent) {
  2245. const snapshot = createEmptyStateSnapshot(rootComponent);
  2246. const emptyUrl = new BehaviorSubject([new UrlSegment('', {})]);
  2247. const emptyParams = new BehaviorSubject({});
  2248. const emptyData = new BehaviorSubject({});
  2249. const emptyQueryParams = new BehaviorSubject({});
  2250. const fragment = new BehaviorSubject('');
  2251. const activated = new ActivatedRoute(emptyUrl, emptyParams, emptyQueryParams, fragment, emptyData, PRIMARY_OUTLET, rootComponent, snapshot.root);
  2252. activated.snapshot = snapshot.root;
  2253. return new RouterState(new TreeNode(activated, []), snapshot);
  2254. }
  2255. function createEmptyStateSnapshot(rootComponent) {
  2256. const emptyParams = {};
  2257. const emptyData = {};
  2258. const emptyQueryParams = {};
  2259. const fragment = '';
  2260. const activated = new ActivatedRouteSnapshot([], emptyParams, emptyQueryParams, fragment, emptyData, PRIMARY_OUTLET, rootComponent, null, {});
  2261. return new RouterStateSnapshot('', new TreeNode(activated, []));
  2262. }
  2263. /**
  2264. * Provides access to information about a route associated with a component
  2265. * that is loaded in an outlet.
  2266. * Use to traverse the `RouterState` tree and extract information from nodes.
  2267. *
  2268. * The following example shows how to construct a component using information from a
  2269. * currently activated route.
  2270. *
  2271. * Note: the observables in this class only emit when the current and previous values differ based
  2272. * on shallow equality. For example, changing deeply nested properties in resolved `data` will not
  2273. * cause the `ActivatedRoute.data` `Observable` to emit a new value.
  2274. *
  2275. * {@example router/activated-route/module.ts region="activated-route"
  2276. * header="activated-route.component.ts"}
  2277. *
  2278. * @see [Getting route information](guide/routing/common-router-tasks#getting-route-information)
  2279. *
  2280. * @publicApi
  2281. */
  2282. class ActivatedRoute {
  2283. urlSubject;
  2284. paramsSubject;
  2285. queryParamsSubject;
  2286. fragmentSubject;
  2287. dataSubject;
  2288. outlet;
  2289. component;
  2290. /** The current snapshot of this route */
  2291. snapshot;
  2292. /** @internal */
  2293. _futureSnapshot;
  2294. /** @internal */
  2295. _routerState;
  2296. /** @internal */
  2297. _paramMap;
  2298. /** @internal */
  2299. _queryParamMap;
  2300. /** An Observable of the resolved route title */
  2301. title;
  2302. /** An observable of the URL segments matched by this route. */
  2303. url;
  2304. /** An observable of the matrix parameters scoped to this route. */
  2305. params;
  2306. /** An observable of the query parameters shared by all the routes. */
  2307. queryParams;
  2308. /** An observable of the URL fragment shared by all the routes. */
  2309. fragment;
  2310. /** An observable of the static and resolved data of this route. */
  2311. data;
  2312. /** @internal */
  2313. constructor(
  2314. /** @internal */
  2315. urlSubject,
  2316. /** @internal */
  2317. paramsSubject,
  2318. /** @internal */
  2319. queryParamsSubject,
  2320. /** @internal */
  2321. fragmentSubject,
  2322. /** @internal */
  2323. dataSubject,
  2324. /** The outlet name of the route, a constant. */
  2325. outlet,
  2326. /** The component of the route, a constant. */
  2327. component, futureSnapshot) {
  2328. this.urlSubject = urlSubject;
  2329. this.paramsSubject = paramsSubject;
  2330. this.queryParamsSubject = queryParamsSubject;
  2331. this.fragmentSubject = fragmentSubject;
  2332. this.dataSubject = dataSubject;
  2333. this.outlet = outlet;
  2334. this.component = component;
  2335. this._futureSnapshot = futureSnapshot;
  2336. this.title = this.dataSubject?.pipe(map((d) => d[RouteTitleKey])) ?? of(undefined);
  2337. // TODO(atscott): Verify that these can be changed to `.asObservable()` with TGP.
  2338. this.url = urlSubject;
  2339. this.params = paramsSubject;
  2340. this.queryParams = queryParamsSubject;
  2341. this.fragment = fragmentSubject;
  2342. this.data = dataSubject;
  2343. }
  2344. /** The configuration used to match this route. */
  2345. get routeConfig() {
  2346. return this._futureSnapshot.routeConfig;
  2347. }
  2348. /** The root of the router state. */
  2349. get root() {
  2350. return this._routerState.root;
  2351. }
  2352. /** The parent of this route in the router state tree. */
  2353. get parent() {
  2354. return this._routerState.parent(this);
  2355. }
  2356. /** The first child of this route in the router state tree. */
  2357. get firstChild() {
  2358. return this._routerState.firstChild(this);
  2359. }
  2360. /** The children of this route in the router state tree. */
  2361. get children() {
  2362. return this._routerState.children(this);
  2363. }
  2364. /** The path from the root of the router state tree to this route. */
  2365. get pathFromRoot() {
  2366. return this._routerState.pathFromRoot(this);
  2367. }
  2368. /**
  2369. * An Observable that contains a map of the required and optional parameters
  2370. * specific to the route.
  2371. * The map supports retrieving single and multiple values from the same parameter.
  2372. */
  2373. get paramMap() {
  2374. this._paramMap ??= this.params.pipe(map((p) => convertToParamMap(p)));
  2375. return this._paramMap;
  2376. }
  2377. /**
  2378. * An Observable that contains a map of the query parameters available to all routes.
  2379. * The map supports retrieving single and multiple values from the query parameter.
  2380. */
  2381. get queryParamMap() {
  2382. this._queryParamMap ??= this.queryParams.pipe(map((p) => convertToParamMap(p)));
  2383. return this._queryParamMap;
  2384. }
  2385. toString() {
  2386. return this.snapshot ? this.snapshot.toString() : `Future(${this._futureSnapshot})`;
  2387. }
  2388. }
  2389. /**
  2390. * Returns the inherited params, data, and resolve for a given route.
  2391. *
  2392. * By default, we do not inherit parent data unless the current route is path-less or the parent
  2393. * route is component-less.
  2394. */
  2395. function getInherited(route, parent, paramsInheritanceStrategy = 'emptyOnly') {
  2396. let inherited;
  2397. const { routeConfig } = route;
  2398. if (parent !== null &&
  2399. (paramsInheritanceStrategy === 'always' ||
  2400. // inherit parent data if route is empty path
  2401. routeConfig?.path === '' ||
  2402. // inherit parent data if parent was componentless
  2403. (!parent.component && !parent.routeConfig?.loadComponent))) {
  2404. inherited = {
  2405. params: { ...parent.params, ...route.params },
  2406. data: { ...parent.data, ...route.data },
  2407. resolve: {
  2408. // Snapshots are created with data inherited from parent and guards (i.e. canActivate) can
  2409. // change data because it's not frozen...
  2410. // This first line could be deleted chose to break/disallow mutating the `data` object in
  2411. // guards.
  2412. // Note that data from parents still override this mutated data so anyone relying on this
  2413. // might be surprised that it doesn't work if parent data is inherited but otherwise does.
  2414. ...route.data,
  2415. // Ensure inherited resolved data overrides inherited static data
  2416. ...parent.data,
  2417. // static data from the current route overrides any inherited data
  2418. ...routeConfig?.data,
  2419. // resolved data from current route overrides everything
  2420. ...route._resolvedData,
  2421. },
  2422. };
  2423. }
  2424. else {
  2425. inherited = {
  2426. params: { ...route.params },
  2427. data: { ...route.data },
  2428. resolve: { ...route.data, ...(route._resolvedData ?? {}) },
  2429. };
  2430. }
  2431. if (routeConfig && hasStaticTitle(routeConfig)) {
  2432. inherited.resolve[RouteTitleKey] = routeConfig.title;
  2433. }
  2434. return inherited;
  2435. }
  2436. /**
  2437. * @description
  2438. *
  2439. * Contains the information about a route associated with a component loaded in an
  2440. * outlet at a particular moment in time. ActivatedRouteSnapshot can also be used to
  2441. * traverse the router state tree.
  2442. *
  2443. * The following example initializes a component with route information extracted
  2444. * from the snapshot of the root node at the time of creation.
  2445. *
  2446. * ```ts
  2447. * @Component({templateUrl:'./my-component.html'})
  2448. * class MyComponent {
  2449. * constructor(route: ActivatedRoute) {
  2450. * const id: string = route.snapshot.params.id;
  2451. * const url: string = route.snapshot.url.join('');
  2452. * const user = route.snapshot.data.user;
  2453. * }
  2454. * }
  2455. * ```
  2456. *
  2457. * @publicApi
  2458. */
  2459. class ActivatedRouteSnapshot {
  2460. url;
  2461. params;
  2462. queryParams;
  2463. fragment;
  2464. data;
  2465. outlet;
  2466. component;
  2467. /** The configuration used to match this route **/
  2468. routeConfig;
  2469. /** @internal */
  2470. _resolve;
  2471. /** @internal */
  2472. _resolvedData;
  2473. /** @internal */
  2474. _routerState;
  2475. /** @internal */
  2476. _paramMap;
  2477. /** @internal */
  2478. _queryParamMap;
  2479. /** The resolved route title */
  2480. get title() {
  2481. // Note: This _must_ be a getter because the data is mutated in the resolvers. Title will not be
  2482. // available at the time of class instantiation.
  2483. return this.data?.[RouteTitleKey];
  2484. }
  2485. /** @internal */
  2486. constructor(
  2487. /** The URL segments matched by this route */
  2488. url,
  2489. /**
  2490. * The matrix parameters scoped to this route.
  2491. *
  2492. * You can compute all params (or data) in the router state or to get params outside
  2493. * of an activated component by traversing the `RouterState` tree as in the following
  2494. * example:
  2495. * ```ts
  2496. * collectRouteParams(router: Router) {
  2497. * let params = {};
  2498. * let stack: ActivatedRouteSnapshot[] = [router.routerState.snapshot.root];
  2499. * while (stack.length > 0) {
  2500. * const route = stack.pop()!;
  2501. * params = {...params, ...route.params};
  2502. * stack.push(...route.children);
  2503. * }
  2504. * return params;
  2505. * }
  2506. * ```
  2507. */
  2508. params,
  2509. /** The query parameters shared by all the routes */
  2510. queryParams,
  2511. /** The URL fragment shared by all the routes */
  2512. fragment,
  2513. /** The static and resolved data of this route */
  2514. data,
  2515. /** The outlet name of the route */
  2516. outlet,
  2517. /** The component of the route */
  2518. component, routeConfig, resolve) {
  2519. this.url = url;
  2520. this.params = params;
  2521. this.queryParams = queryParams;
  2522. this.fragment = fragment;
  2523. this.data = data;
  2524. this.outlet = outlet;
  2525. this.component = component;
  2526. this.routeConfig = routeConfig;
  2527. this._resolve = resolve;
  2528. }
  2529. /** The root of the router state */
  2530. get root() {
  2531. return this._routerState.root;
  2532. }
  2533. /** The parent of this route in the router state tree */
  2534. get parent() {
  2535. return this._routerState.parent(this);
  2536. }
  2537. /** The first child of this route in the router state tree */
  2538. get firstChild() {
  2539. return this._routerState.firstChild(this);
  2540. }
  2541. /** The children of this route in the router state tree */
  2542. get children() {
  2543. return this._routerState.children(this);
  2544. }
  2545. /** The path from the root of the router state tree to this route */
  2546. get pathFromRoot() {
  2547. return this._routerState.pathFromRoot(this);
  2548. }
  2549. get paramMap() {
  2550. this._paramMap ??= convertToParamMap(this.params);
  2551. return this._paramMap;
  2552. }
  2553. get queryParamMap() {
  2554. this._queryParamMap ??= convertToParamMap(this.queryParams);
  2555. return this._queryParamMap;
  2556. }
  2557. toString() {
  2558. const url = this.url.map((segment) => segment.toString()).join('/');
  2559. const matched = this.routeConfig ? this.routeConfig.path : '';
  2560. return `Route(url:'${url}', path:'${matched}')`;
  2561. }
  2562. }
  2563. /**
  2564. * @description
  2565. *
  2566. * Represents the state of the router at a moment in time.
  2567. *
  2568. * This is a tree of activated route snapshots. Every node in this tree knows about
  2569. * the "consumed" URL segments, the extracted parameters, and the resolved data.
  2570. *
  2571. * The following example shows how a component is initialized with information
  2572. * from the snapshot of the root node's state at the time of creation.
  2573. *
  2574. * ```ts
  2575. * @Component({templateUrl:'template.html'})
  2576. * class MyComponent {
  2577. * constructor(router: Router) {
  2578. * const state: RouterState = router.routerState;
  2579. * const snapshot: RouterStateSnapshot = state.snapshot;
  2580. * const root: ActivatedRouteSnapshot = snapshot.root;
  2581. * const child = root.firstChild;
  2582. * const id: Observable<string> = child.params.map(p => p.id);
  2583. * //...
  2584. * }
  2585. * }
  2586. * ```
  2587. *
  2588. * @publicApi
  2589. */
  2590. class RouterStateSnapshot extends Tree {
  2591. url;
  2592. /** @internal */
  2593. constructor(
  2594. /** The url from which this snapshot was created */
  2595. url, root) {
  2596. super(root);
  2597. this.url = url;
  2598. setRouterState(this, root);
  2599. }
  2600. toString() {
  2601. return serializeNode(this._root);
  2602. }
  2603. }
  2604. function setRouterState(state, node) {
  2605. node.value._routerState = state;
  2606. node.children.forEach((c) => setRouterState(state, c));
  2607. }
  2608. function serializeNode(node) {
  2609. const c = node.children.length > 0 ? ` { ${node.children.map(serializeNode).join(', ')} } ` : '';
  2610. return `${node.value}${c}`;
  2611. }
  2612. /**
  2613. * The expectation is that the activate route is created with the right set of parameters.
  2614. * So we push new values into the observables only when they are not the initial values.
  2615. * And we detect that by checking if the snapshot field is set.
  2616. */
  2617. function advanceActivatedRoute(route) {
  2618. if (route.snapshot) {
  2619. const currentSnapshot = route.snapshot;
  2620. const nextSnapshot = route._futureSnapshot;
  2621. route.snapshot = nextSnapshot;
  2622. if (!shallowEqual(currentSnapshot.queryParams, nextSnapshot.queryParams)) {
  2623. route.queryParamsSubject.next(nextSnapshot.queryParams);
  2624. }
  2625. if (currentSnapshot.fragment !== nextSnapshot.fragment) {
  2626. route.fragmentSubject.next(nextSnapshot.fragment);
  2627. }
  2628. if (!shallowEqual(currentSnapshot.params, nextSnapshot.params)) {
  2629. route.paramsSubject.next(nextSnapshot.params);
  2630. }
  2631. if (!shallowEqualArrays(currentSnapshot.url, nextSnapshot.url)) {
  2632. route.urlSubject.next(nextSnapshot.url);
  2633. }
  2634. if (!shallowEqual(currentSnapshot.data, nextSnapshot.data)) {
  2635. route.dataSubject.next(nextSnapshot.data);
  2636. }
  2637. }
  2638. else {
  2639. route.snapshot = route._futureSnapshot;
  2640. // this is for resolved data
  2641. route.dataSubject.next(route._futureSnapshot.data);
  2642. }
  2643. }
  2644. function equalParamsAndUrlSegments(a, b) {
  2645. const equalUrlParams = shallowEqual(a.params, b.params) && equalSegments(a.url, b.url);
  2646. const parentsMismatch = !a.parent !== !b.parent;
  2647. return (equalUrlParams &&
  2648. !parentsMismatch &&
  2649. (!a.parent || equalParamsAndUrlSegments(a.parent, b.parent)));
  2650. }
  2651. function hasStaticTitle(config) {
  2652. return typeof config.title === 'string' || config.title === null;
  2653. }
  2654. /**
  2655. * An `InjectionToken` provided by the `RouterOutlet` and can be set using the `routerOutletData`
  2656. * input.
  2657. *
  2658. * When unset, this value is `null` by default.
  2659. *
  2660. * @usageNotes
  2661. *
  2662. * To set the data from the template of the component with `router-outlet`:
  2663. * ```html
  2664. * <router-outlet [routerOutletData]="{name: 'Angular'}" />
  2665. * ```
  2666. *
  2667. * To read the data in the routed component:
  2668. * ```ts
  2669. * data = inject(ROUTER_OUTLET_DATA) as Signal<{name: string}>;
  2670. * ```
  2671. *
  2672. * @publicApi
  2673. */
  2674. const ROUTER_OUTLET_DATA = new InjectionToken(ngDevMode ? 'RouterOutlet data' : '');
  2675. /**
  2676. * @description
  2677. *
  2678. * Acts as a placeholder that Angular dynamically fills based on the current router state.
  2679. *
  2680. * Each outlet can have a unique name, determined by the optional `name` attribute.
  2681. * The name cannot be set or changed dynamically. If not set, default value is "primary".
  2682. *
  2683. * ```html
  2684. * <router-outlet></router-outlet>
  2685. * <router-outlet name='left'></router-outlet>
  2686. * <router-outlet name='right'></router-outlet>
  2687. * ```
  2688. *
  2689. * Named outlets can be the targets of secondary routes.
  2690. * The `Route` object for a secondary route has an `outlet` property to identify the target outlet:
  2691. *
  2692. * `{path: <base-path>, component: <component>, outlet: <target_outlet_name>}`
  2693. *
  2694. * Using named outlets and secondary routes, you can target multiple outlets in
  2695. * the same `RouterLink` directive.
  2696. *
  2697. * The router keeps track of separate branches in a navigation tree for each named outlet and
  2698. * generates a representation of that tree in the URL.
  2699. * The URL for a secondary route uses the following syntax to specify both the primary and secondary
  2700. * routes at the same time:
  2701. *
  2702. * `http://base-path/primary-route-path(outlet-name:route-path)`
  2703. *
  2704. * A router outlet emits an activate event when a new component is instantiated,
  2705. * deactivate event when a component is destroyed.
  2706. * An attached event emits when the `RouteReuseStrategy` instructs the outlet to reattach the
  2707. * subtree, and the detached event emits when the `RouteReuseStrategy` instructs the outlet to
  2708. * detach the subtree.
  2709. *
  2710. * ```html
  2711. * <router-outlet
  2712. * (activate)='onActivate($event)'
  2713. * (deactivate)='onDeactivate($event)'
  2714. * (attach)='onAttach($event)'
  2715. * (detach)='onDetach($event)'></router-outlet>
  2716. * ```
  2717. *
  2718. * @see {@link RouterLink}
  2719. * @see {@link Route}
  2720. * @ngModule RouterModule
  2721. *
  2722. * @publicApi
  2723. */
  2724. class RouterOutlet {
  2725. activated = null;
  2726. /** @internal */
  2727. get activatedComponentRef() {
  2728. return this.activated;
  2729. }
  2730. _activatedRoute = null;
  2731. /**
  2732. * The name of the outlet
  2733. *
  2734. */
  2735. name = PRIMARY_OUTLET;
  2736. activateEvents = new EventEmitter();
  2737. deactivateEvents = new EventEmitter();
  2738. /**
  2739. * Emits an attached component instance when the `RouteReuseStrategy` instructs to re-attach a
  2740. * previously detached subtree.
  2741. **/
  2742. attachEvents = new EventEmitter();
  2743. /**
  2744. * Emits a detached component instance when the `RouteReuseStrategy` instructs to detach the
  2745. * subtree.
  2746. */
  2747. detachEvents = new EventEmitter();
  2748. /**
  2749. * Data that will be provided to the child injector through the `ROUTER_OUTLET_DATA` token.
  2750. *
  2751. * When unset, the value of the token is `undefined` by default.
  2752. */
  2753. routerOutletData = input(undefined);
  2754. parentContexts = inject(ChildrenOutletContexts);
  2755. location = inject(ViewContainerRef);
  2756. changeDetector = inject(ChangeDetectorRef);
  2757. inputBinder = inject(INPUT_BINDER, { optional: true });
  2758. /** @docs-private */
  2759. supportsBindingToComponentInputs = true;
  2760. /** @docs-private */
  2761. ngOnChanges(changes) {
  2762. if (changes['name']) {
  2763. const { firstChange, previousValue } = changes['name'];
  2764. if (firstChange) {
  2765. // The first change is handled by ngOnInit. Because ngOnChanges doesn't get called when no
  2766. // input is set at all, we need to centrally handle the first change there.
  2767. return;
  2768. }
  2769. // unregister with the old name
  2770. if (this.isTrackedInParentContexts(previousValue)) {
  2771. this.deactivate();
  2772. this.parentContexts.onChildOutletDestroyed(previousValue);
  2773. }
  2774. // register the new name
  2775. this.initializeOutletWithName();
  2776. }
  2777. }
  2778. /** @docs-private */
  2779. ngOnDestroy() {
  2780. // Ensure that the registered outlet is this one before removing it on the context.
  2781. if (this.isTrackedInParentContexts(this.name)) {
  2782. this.parentContexts.onChildOutletDestroyed(this.name);
  2783. }
  2784. this.inputBinder?.unsubscribeFromRouteData(this);
  2785. }
  2786. isTrackedInParentContexts(outletName) {
  2787. return this.parentContexts.getContext(outletName)?.outlet === this;
  2788. }
  2789. /** @docs-private */
  2790. ngOnInit() {
  2791. this.initializeOutletWithName();
  2792. }
  2793. initializeOutletWithName() {
  2794. this.parentContexts.onChildOutletCreated(this.name, this);
  2795. if (this.activated) {
  2796. return;
  2797. }
  2798. // If the outlet was not instantiated at the time the route got activated we need to populate
  2799. // the outlet when it is initialized (ie inside a NgIf)
  2800. const context = this.parentContexts.getContext(this.name);
  2801. if (context?.route) {
  2802. if (context.attachRef) {
  2803. // `attachRef` is populated when there is an existing component to mount
  2804. this.attach(context.attachRef, context.route);
  2805. }
  2806. else {
  2807. // otherwise the component defined in the configuration is created
  2808. this.activateWith(context.route, context.injector);
  2809. }
  2810. }
  2811. }
  2812. get isActivated() {
  2813. return !!this.activated;
  2814. }
  2815. /**
  2816. * @returns The currently activated component instance.
  2817. * @throws An error if the outlet is not activated.
  2818. */
  2819. get component() {
  2820. if (!this.activated)
  2821. throw new _RuntimeError(4012 /* RuntimeErrorCode.OUTLET_NOT_ACTIVATED */, (typeof ngDevMode === 'undefined' || ngDevMode) && 'Outlet is not activated');
  2822. return this.activated.instance;
  2823. }
  2824. get activatedRoute() {
  2825. if (!this.activated)
  2826. throw new _RuntimeError(4012 /* RuntimeErrorCode.OUTLET_NOT_ACTIVATED */, (typeof ngDevMode === 'undefined' || ngDevMode) && 'Outlet is not activated');
  2827. return this._activatedRoute;
  2828. }
  2829. get activatedRouteData() {
  2830. if (this._activatedRoute) {
  2831. return this._activatedRoute.snapshot.data;
  2832. }
  2833. return {};
  2834. }
  2835. /**
  2836. * Called when the `RouteReuseStrategy` instructs to detach the subtree
  2837. */
  2838. detach() {
  2839. if (!this.activated)
  2840. throw new _RuntimeError(4012 /* RuntimeErrorCode.OUTLET_NOT_ACTIVATED */, (typeof ngDevMode === 'undefined' || ngDevMode) && 'Outlet is not activated');
  2841. this.location.detach();
  2842. const cmp = this.activated;
  2843. this.activated = null;
  2844. this._activatedRoute = null;
  2845. this.detachEvents.emit(cmp.instance);
  2846. return cmp;
  2847. }
  2848. /**
  2849. * Called when the `RouteReuseStrategy` instructs to re-attach a previously detached subtree
  2850. */
  2851. attach(ref, activatedRoute) {
  2852. this.activated = ref;
  2853. this._activatedRoute = activatedRoute;
  2854. this.location.insert(ref.hostView);
  2855. this.inputBinder?.bindActivatedRouteToOutletComponent(this);
  2856. this.attachEvents.emit(ref.instance);
  2857. }
  2858. deactivate() {
  2859. if (this.activated) {
  2860. const c = this.component;
  2861. this.activated.destroy();
  2862. this.activated = null;
  2863. this._activatedRoute = null;
  2864. this.deactivateEvents.emit(c);
  2865. }
  2866. }
  2867. activateWith(activatedRoute, environmentInjector) {
  2868. if (this.isActivated) {
  2869. throw new _RuntimeError(4013 /* RuntimeErrorCode.OUTLET_ALREADY_ACTIVATED */, (typeof ngDevMode === 'undefined' || ngDevMode) &&
  2870. 'Cannot activate an already activated outlet');
  2871. }
  2872. this._activatedRoute = activatedRoute;
  2873. const location = this.location;
  2874. const snapshot = activatedRoute.snapshot;
  2875. const component = snapshot.component;
  2876. const childContexts = this.parentContexts.getOrCreateContext(this.name).children;
  2877. const injector = new OutletInjector(activatedRoute, childContexts, location.injector, this.routerOutletData);
  2878. this.activated = location.createComponent(component, {
  2879. index: location.length,
  2880. injector,
  2881. environmentInjector: environmentInjector,
  2882. });
  2883. // Calling `markForCheck` to make sure we will run the change detection when the
  2884. // `RouterOutlet` is inside a `ChangeDetectionStrategy.OnPush` component.
  2885. this.changeDetector.markForCheck();
  2886. this.inputBinder?.bindActivatedRouteToOutletComponent(this);
  2887. this.activateEvents.emit(this.activated.instance);
  2888. }
  2889. static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: RouterOutlet, deps: [], target: i0.ɵɵFactoryTarget.Directive });
  2890. static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "19.2.13", type: RouterOutlet, isStandalone: true, selector: "router-outlet", inputs: { name: { classPropertyName: "name", publicName: "name", isSignal: false, isRequired: false, transformFunction: null }, routerOutletData: { classPropertyName: "routerOutletData", publicName: "routerOutletData", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { activateEvents: "activate", deactivateEvents: "deactivate", attachEvents: "attach", detachEvents: "detach" }, exportAs: ["outlet"], usesOnChanges: true, ngImport: i0 });
  2891. }
  2892. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: RouterOutlet, decorators: [{
  2893. type: Directive,
  2894. args: [{
  2895. selector: 'router-outlet',
  2896. exportAs: 'outlet',
  2897. }]
  2898. }], propDecorators: { name: [{
  2899. type: Input
  2900. }], activateEvents: [{
  2901. type: Output,
  2902. args: ['activate']
  2903. }], deactivateEvents: [{
  2904. type: Output,
  2905. args: ['deactivate']
  2906. }], attachEvents: [{
  2907. type: Output,
  2908. args: ['attach']
  2909. }], detachEvents: [{
  2910. type: Output,
  2911. args: ['detach']
  2912. }] } });
  2913. class OutletInjector {
  2914. route;
  2915. childContexts;
  2916. parent;
  2917. outletData;
  2918. constructor(route, childContexts, parent, outletData) {
  2919. this.route = route;
  2920. this.childContexts = childContexts;
  2921. this.parent = parent;
  2922. this.outletData = outletData;
  2923. }
  2924. get(token, notFoundValue) {
  2925. if (token === ActivatedRoute) {
  2926. return this.route;
  2927. }
  2928. if (token === ChildrenOutletContexts) {
  2929. return this.childContexts;
  2930. }
  2931. if (token === ROUTER_OUTLET_DATA) {
  2932. return this.outletData;
  2933. }
  2934. return this.parent.get(token, notFoundValue);
  2935. }
  2936. }
  2937. const INPUT_BINDER = new InjectionToken('');
  2938. /**
  2939. * Injectable used as a tree-shakable provider for opting in to binding router data to component
  2940. * inputs.
  2941. *
  2942. * The RouterOutlet registers itself with this service when an `ActivatedRoute` is attached or
  2943. * activated. When this happens, the service subscribes to the `ActivatedRoute` observables (params,
  2944. * queryParams, data) and sets the inputs of the component using `ComponentRef.setInput`.
  2945. * Importantly, when an input does not have an item in the route data with a matching key, this
  2946. * input is set to `undefined`. If it were not done this way, the previous information would be
  2947. * retained if the data got removed from the route (i.e. if a query parameter is removed).
  2948. *
  2949. * The `RouterOutlet` should unregister itself when destroyed via `unsubscribeFromRouteData` so that
  2950. * the subscriptions are cleaned up.
  2951. */
  2952. class RoutedComponentInputBinder {
  2953. outletDataSubscriptions = new Map();
  2954. bindActivatedRouteToOutletComponent(outlet) {
  2955. this.unsubscribeFromRouteData(outlet);
  2956. this.subscribeToRouteData(outlet);
  2957. }
  2958. unsubscribeFromRouteData(outlet) {
  2959. this.outletDataSubscriptions.get(outlet)?.unsubscribe();
  2960. this.outletDataSubscriptions.delete(outlet);
  2961. }
  2962. subscribeToRouteData(outlet) {
  2963. const { activatedRoute } = outlet;
  2964. const dataSubscription = combineLatest([
  2965. activatedRoute.queryParams,
  2966. activatedRoute.params,
  2967. activatedRoute.data,
  2968. ])
  2969. .pipe(switchMap(([queryParams, params, data], index) => {
  2970. data = { ...queryParams, ...params, ...data };
  2971. // Get the first result from the data subscription synchronously so it's available to
  2972. // the component as soon as possible (and doesn't require a second change detection).
  2973. if (index === 0) {
  2974. return of(data);
  2975. }
  2976. // Promise.resolve is used to avoid synchronously writing the wrong data when
  2977. // two of the Observables in the `combineLatest` stream emit one after
  2978. // another.
  2979. return Promise.resolve(data);
  2980. }))
  2981. .subscribe((data) => {
  2982. // Outlet may have been deactivated or changed names to be associated with a different
  2983. // route
  2984. if (!outlet.isActivated ||
  2985. !outlet.activatedComponentRef ||
  2986. outlet.activatedRoute !== activatedRoute ||
  2987. activatedRoute.component === null) {
  2988. this.unsubscribeFromRouteData(outlet);
  2989. return;
  2990. }
  2991. const mirror = reflectComponentType(activatedRoute.component);
  2992. if (!mirror) {
  2993. this.unsubscribeFromRouteData(outlet);
  2994. return;
  2995. }
  2996. for (const { templateName } of mirror.inputs) {
  2997. outlet.activatedComponentRef.setInput(templateName, data[templateName]);
  2998. }
  2999. });
  3000. this.outletDataSubscriptions.set(outlet, dataSubscription);
  3001. }
  3002. static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: RoutedComponentInputBinder, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
  3003. static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: RoutedComponentInputBinder });
  3004. }
  3005. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: RoutedComponentInputBinder, decorators: [{
  3006. type: Injectable
  3007. }] });
  3008. /**
  3009. * This component is used internally within the router to be a placeholder when an empty
  3010. * router-outlet is needed. For example, with a config such as:
  3011. *
  3012. * `{path: 'parent', outlet: 'nav', children: [...]}`
  3013. *
  3014. * In order to render, there needs to be a component on this config, which will default
  3015. * to this `EmptyOutletComponent`.
  3016. */
  3017. class ɵEmptyOutletComponent {
  3018. static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: ɵEmptyOutletComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
  3019. static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "19.2.13", type: ɵEmptyOutletComponent, isStandalone: true, selector: "ng-component", exportAs: ["emptyRouterOutlet"], ngImport: i0, template: `<router-outlet/>`, isInline: true, dependencies: [{ kind: "directive", type: RouterOutlet, selector: "router-outlet", inputs: ["name", "routerOutletData"], outputs: ["activate", "deactivate", "attach", "detach"], exportAs: ["outlet"] }] });
  3020. }
  3021. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: ɵEmptyOutletComponent, decorators: [{
  3022. type: Component,
  3023. args: [{
  3024. template: `<router-outlet/>`,
  3025. imports: [RouterOutlet],
  3026. // Used to avoid component ID collisions with user code.
  3027. exportAs: 'emptyRouterOutlet',
  3028. }]
  3029. }] });
  3030. /**
  3031. * Makes a copy of the config and adds any default required properties.
  3032. */
  3033. function standardizeConfig(r) {
  3034. const children = r.children && r.children.map(standardizeConfig);
  3035. const c = children ? { ...r, children } : { ...r };
  3036. if (!c.component &&
  3037. !c.loadComponent &&
  3038. (children || c.loadChildren) &&
  3039. c.outlet &&
  3040. c.outlet !== PRIMARY_OUTLET) {
  3041. c.component = ɵEmptyOutletComponent;
  3042. }
  3043. return c;
  3044. }
  3045. function createRouterState(routeReuseStrategy, curr, prevState) {
  3046. const root = createNode(routeReuseStrategy, curr._root, prevState ? prevState._root : undefined);
  3047. return new RouterState(root, curr);
  3048. }
  3049. function createNode(routeReuseStrategy, curr, prevState) {
  3050. // reuse an activated route that is currently displayed on the screen
  3051. if (prevState && routeReuseStrategy.shouldReuseRoute(curr.value, prevState.value.snapshot)) {
  3052. const value = prevState.value;
  3053. value._futureSnapshot = curr.value;
  3054. const children = createOrReuseChildren(routeReuseStrategy, curr, prevState);
  3055. return new TreeNode(value, children);
  3056. }
  3057. else {
  3058. if (routeReuseStrategy.shouldAttach(curr.value)) {
  3059. // retrieve an activated route that is used to be displayed, but is not currently displayed
  3060. const detachedRouteHandle = routeReuseStrategy.retrieve(curr.value);
  3061. if (detachedRouteHandle !== null) {
  3062. const tree = detachedRouteHandle.route;
  3063. tree.value._futureSnapshot = curr.value;
  3064. tree.children = curr.children.map((c) => createNode(routeReuseStrategy, c));
  3065. return tree;
  3066. }
  3067. }
  3068. const value = createActivatedRoute(curr.value);
  3069. const children = curr.children.map((c) => createNode(routeReuseStrategy, c));
  3070. return new TreeNode(value, children);
  3071. }
  3072. }
  3073. function createOrReuseChildren(routeReuseStrategy, curr, prevState) {
  3074. return curr.children.map((child) => {
  3075. for (const p of prevState.children) {
  3076. if (routeReuseStrategy.shouldReuseRoute(child.value, p.value.snapshot)) {
  3077. return createNode(routeReuseStrategy, child, p);
  3078. }
  3079. }
  3080. return createNode(routeReuseStrategy, child);
  3081. });
  3082. }
  3083. function createActivatedRoute(c) {
  3084. return new ActivatedRoute(new BehaviorSubject(c.url), new BehaviorSubject(c.params), new BehaviorSubject(c.queryParams), new BehaviorSubject(c.fragment), new BehaviorSubject(c.data), c.outlet, c.component, c);
  3085. }
  3086. /**
  3087. * Can be returned by a `Router` guard to instruct the `Router` to redirect rather than continue
  3088. * processing the path of the in-flight navigation. The `redirectTo` indicates _where_ the new
  3089. * navigation should go to and the optional `navigationBehaviorOptions` can provide more information
  3090. * about _how_ to perform the navigation.
  3091. *
  3092. * ```ts
  3093. * const route: Route = {
  3094. * path: "user/:userId",
  3095. * component: User,
  3096. * canActivate: [
  3097. * () => {
  3098. * const router = inject(Router);
  3099. * const authService = inject(AuthenticationService);
  3100. *
  3101. * if (!authService.isLoggedIn()) {
  3102. * const loginPath = router.parseUrl("/login");
  3103. * return new RedirectCommand(loginPath, {
  3104. * skipLocationChange: "true",
  3105. * });
  3106. * }
  3107. *
  3108. * return true;
  3109. * },
  3110. * ],
  3111. * };
  3112. * ```
  3113. * @see [Routing guide](guide/routing/common-router-tasks#preventing-unauthorized-access)
  3114. *
  3115. * @publicApi
  3116. */
  3117. class RedirectCommand {
  3118. redirectTo;
  3119. navigationBehaviorOptions;
  3120. constructor(redirectTo, navigationBehaviorOptions) {
  3121. this.redirectTo = redirectTo;
  3122. this.navigationBehaviorOptions = navigationBehaviorOptions;
  3123. }
  3124. }
  3125. const NAVIGATION_CANCELING_ERROR = 'ngNavigationCancelingError';
  3126. function redirectingNavigationError(urlSerializer, redirect) {
  3127. const { redirectTo, navigationBehaviorOptions } = isUrlTree(redirect)
  3128. ? { redirectTo: redirect, navigationBehaviorOptions: undefined }
  3129. : redirect;
  3130. const error = navigationCancelingError(ngDevMode && `Redirecting to "${urlSerializer.serialize(redirectTo)}"`, NavigationCancellationCode.Redirect);
  3131. error.url = redirectTo;
  3132. error.navigationBehaviorOptions = navigationBehaviorOptions;
  3133. return error;
  3134. }
  3135. function navigationCancelingError(message, code) {
  3136. const error = new Error(`NavigationCancelingError: ${message || ''}`);
  3137. error[NAVIGATION_CANCELING_ERROR] = true;
  3138. error.cancellationCode = code;
  3139. return error;
  3140. }
  3141. function isRedirectingNavigationCancelingError(error) {
  3142. return (isNavigationCancelingError(error) &&
  3143. isUrlTree(error.url));
  3144. }
  3145. function isNavigationCancelingError(error) {
  3146. return !!error && error[NAVIGATION_CANCELING_ERROR];
  3147. }
  3148. let warnedAboutUnsupportedInputBinding = false;
  3149. const activateRoutes = (rootContexts, routeReuseStrategy, forwardEvent, inputBindingEnabled) => map((t) => {
  3150. new ActivateRoutes(routeReuseStrategy, t.targetRouterState, t.currentRouterState, forwardEvent, inputBindingEnabled).activate(rootContexts);
  3151. return t;
  3152. });
  3153. class ActivateRoutes {
  3154. routeReuseStrategy;
  3155. futureState;
  3156. currState;
  3157. forwardEvent;
  3158. inputBindingEnabled;
  3159. constructor(routeReuseStrategy, futureState, currState, forwardEvent, inputBindingEnabled) {
  3160. this.routeReuseStrategy = routeReuseStrategy;
  3161. this.futureState = futureState;
  3162. this.currState = currState;
  3163. this.forwardEvent = forwardEvent;
  3164. this.inputBindingEnabled = inputBindingEnabled;
  3165. }
  3166. activate(parentContexts) {
  3167. const futureRoot = this.futureState._root;
  3168. const currRoot = this.currState ? this.currState._root : null;
  3169. this.deactivateChildRoutes(futureRoot, currRoot, parentContexts);
  3170. advanceActivatedRoute(this.futureState.root);
  3171. this.activateChildRoutes(futureRoot, currRoot, parentContexts);
  3172. }
  3173. // De-activate the child route that are not re-used for the future state
  3174. deactivateChildRoutes(futureNode, currNode, contexts) {
  3175. const children = nodeChildrenAsMap(currNode);
  3176. // Recurse on the routes active in the future state to de-activate deeper children
  3177. futureNode.children.forEach((futureChild) => {
  3178. const childOutletName = futureChild.value.outlet;
  3179. this.deactivateRoutes(futureChild, children[childOutletName], contexts);
  3180. delete children[childOutletName];
  3181. });
  3182. // De-activate the routes that will not be re-used
  3183. Object.values(children).forEach((v) => {
  3184. this.deactivateRouteAndItsChildren(v, contexts);
  3185. });
  3186. }
  3187. deactivateRoutes(futureNode, currNode, parentContext) {
  3188. const future = futureNode.value;
  3189. const curr = currNode ? currNode.value : null;
  3190. if (future === curr) {
  3191. // Reusing the node, check to see if the children need to be de-activated
  3192. if (future.component) {
  3193. // If we have a normal route, we need to go through an outlet.
  3194. const context = parentContext.getContext(future.outlet);
  3195. if (context) {
  3196. this.deactivateChildRoutes(futureNode, currNode, context.children);
  3197. }
  3198. }
  3199. else {
  3200. // if we have a componentless route, we recurse but keep the same outlet map.
  3201. this.deactivateChildRoutes(futureNode, currNode, parentContext);
  3202. }
  3203. }
  3204. else {
  3205. if (curr) {
  3206. // Deactivate the current route which will not be re-used
  3207. this.deactivateRouteAndItsChildren(currNode, parentContext);
  3208. }
  3209. }
  3210. }
  3211. deactivateRouteAndItsChildren(route, parentContexts) {
  3212. // If there is no component, the Route is never attached to an outlet (because there is no
  3213. // component to attach).
  3214. if (route.value.component && this.routeReuseStrategy.shouldDetach(route.value.snapshot)) {
  3215. this.detachAndStoreRouteSubtree(route, parentContexts);
  3216. }
  3217. else {
  3218. this.deactivateRouteAndOutlet(route, parentContexts);
  3219. }
  3220. }
  3221. detachAndStoreRouteSubtree(route, parentContexts) {
  3222. const context = parentContexts.getContext(route.value.outlet);
  3223. const contexts = context && route.value.component ? context.children : parentContexts;
  3224. const children = nodeChildrenAsMap(route);
  3225. for (const treeNode of Object.values(children)) {
  3226. this.deactivateRouteAndItsChildren(treeNode, contexts);
  3227. }
  3228. if (context && context.outlet) {
  3229. const componentRef = context.outlet.detach();
  3230. const contexts = context.children.onOutletDeactivated();
  3231. this.routeReuseStrategy.store(route.value.snapshot, { componentRef, route, contexts });
  3232. }
  3233. }
  3234. deactivateRouteAndOutlet(route, parentContexts) {
  3235. const context = parentContexts.getContext(route.value.outlet);
  3236. // The context could be `null` if we are on a componentless route but there may still be
  3237. // children that need deactivating.
  3238. const contexts = context && route.value.component ? context.children : parentContexts;
  3239. const children = nodeChildrenAsMap(route);
  3240. for (const treeNode of Object.values(children)) {
  3241. this.deactivateRouteAndItsChildren(treeNode, contexts);
  3242. }
  3243. if (context) {
  3244. if (context.outlet) {
  3245. // Destroy the component
  3246. context.outlet.deactivate();
  3247. // Destroy the contexts for all the outlets that were in the component
  3248. context.children.onOutletDeactivated();
  3249. }
  3250. // Clear the information about the attached component on the context but keep the reference to
  3251. // the outlet. Clear even if outlet was not yet activated to avoid activating later with old
  3252. // info
  3253. context.attachRef = null;
  3254. context.route = null;
  3255. }
  3256. }
  3257. activateChildRoutes(futureNode, currNode, contexts) {
  3258. const children = nodeChildrenAsMap(currNode);
  3259. futureNode.children.forEach((c) => {
  3260. this.activateRoutes(c, children[c.value.outlet], contexts);
  3261. this.forwardEvent(new ActivationEnd(c.value.snapshot));
  3262. });
  3263. if (futureNode.children.length) {
  3264. this.forwardEvent(new ChildActivationEnd(futureNode.value.snapshot));
  3265. }
  3266. }
  3267. activateRoutes(futureNode, currNode, parentContexts) {
  3268. const future = futureNode.value;
  3269. const curr = currNode ? currNode.value : null;
  3270. advanceActivatedRoute(future);
  3271. // reusing the node
  3272. if (future === curr) {
  3273. if (future.component) {
  3274. // If we have a normal route, we need to go through an outlet.
  3275. const context = parentContexts.getOrCreateContext(future.outlet);
  3276. this.activateChildRoutes(futureNode, currNode, context.children);
  3277. }
  3278. else {
  3279. // if we have a componentless route, we recurse but keep the same outlet map.
  3280. this.activateChildRoutes(futureNode, currNode, parentContexts);
  3281. }
  3282. }
  3283. else {
  3284. if (future.component) {
  3285. // if we have a normal route, we need to place the component into the outlet and recurse.
  3286. const context = parentContexts.getOrCreateContext(future.outlet);
  3287. if (this.routeReuseStrategy.shouldAttach(future.snapshot)) {
  3288. const stored = (this.routeReuseStrategy.retrieve(future.snapshot));
  3289. this.routeReuseStrategy.store(future.snapshot, null);
  3290. context.children.onOutletReAttached(stored.contexts);
  3291. context.attachRef = stored.componentRef;
  3292. context.route = stored.route.value;
  3293. if (context.outlet) {
  3294. // Attach right away when the outlet has already been instantiated
  3295. // Otherwise attach from `RouterOutlet.ngOnInit` when it is instantiated
  3296. context.outlet.attach(stored.componentRef, stored.route.value);
  3297. }
  3298. advanceActivatedRoute(stored.route.value);
  3299. this.activateChildRoutes(futureNode, null, context.children);
  3300. }
  3301. else {
  3302. context.attachRef = null;
  3303. context.route = future;
  3304. if (context.outlet) {
  3305. // Activate the outlet when it has already been instantiated
  3306. // Otherwise it will get activated from its `ngOnInit` when instantiated
  3307. context.outlet.activateWith(future, context.injector);
  3308. }
  3309. this.activateChildRoutes(futureNode, null, context.children);
  3310. }
  3311. }
  3312. else {
  3313. // if we have a componentless route, we recurse but keep the same outlet map.
  3314. this.activateChildRoutes(futureNode, null, parentContexts);
  3315. }
  3316. }
  3317. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  3318. const context = parentContexts.getOrCreateContext(future.outlet);
  3319. const outlet = context.outlet;
  3320. if (outlet &&
  3321. this.inputBindingEnabled &&
  3322. !outlet.supportsBindingToComponentInputs &&
  3323. !warnedAboutUnsupportedInputBinding) {
  3324. console.warn(`'withComponentInputBinding' feature is enabled but ` +
  3325. `this application is using an outlet that may not support binding to component inputs.`);
  3326. warnedAboutUnsupportedInputBinding = true;
  3327. }
  3328. }
  3329. }
  3330. }
  3331. class CanActivate {
  3332. path;
  3333. route;
  3334. constructor(path) {
  3335. this.path = path;
  3336. this.route = this.path[this.path.length - 1];
  3337. }
  3338. }
  3339. class CanDeactivate {
  3340. component;
  3341. route;
  3342. constructor(component, route) {
  3343. this.component = component;
  3344. this.route = route;
  3345. }
  3346. }
  3347. function getAllRouteGuards(future, curr, parentContexts) {
  3348. const futureRoot = future._root;
  3349. const currRoot = curr ? curr._root : null;
  3350. return getChildRouteGuards(futureRoot, currRoot, parentContexts, [futureRoot.value]);
  3351. }
  3352. function getCanActivateChild(p) {
  3353. const canActivateChild = p.routeConfig ? p.routeConfig.canActivateChild : null;
  3354. if (!canActivateChild || canActivateChild.length === 0)
  3355. return null;
  3356. return { node: p, guards: canActivateChild };
  3357. }
  3358. function getTokenOrFunctionIdentity(tokenOrFunction, injector) {
  3359. const NOT_FOUND = Symbol();
  3360. const result = injector.get(tokenOrFunction, NOT_FOUND);
  3361. if (result === NOT_FOUND) {
  3362. if (typeof tokenOrFunction === 'function' && !_isInjectable(tokenOrFunction)) {
  3363. // We think the token is just a function so return it as-is
  3364. return tokenOrFunction;
  3365. }
  3366. else {
  3367. // This will throw the not found error
  3368. return injector.get(tokenOrFunction);
  3369. }
  3370. }
  3371. return result;
  3372. }
  3373. function getChildRouteGuards(futureNode, currNode, contexts, futurePath, checks = {
  3374. canDeactivateChecks: [],
  3375. canActivateChecks: [],
  3376. }) {
  3377. const prevChildren = nodeChildrenAsMap(currNode);
  3378. // Process the children of the future route
  3379. futureNode.children.forEach((c) => {
  3380. getRouteGuards(c, prevChildren[c.value.outlet], contexts, futurePath.concat([c.value]), checks);
  3381. delete prevChildren[c.value.outlet];
  3382. });
  3383. // Process any children left from the current route (not active for the future route)
  3384. Object.entries(prevChildren).forEach(([k, v]) => deactivateRouteAndItsChildren(v, contexts.getContext(k), checks));
  3385. return checks;
  3386. }
  3387. function getRouteGuards(futureNode, currNode, parentContexts, futurePath, checks = {
  3388. canDeactivateChecks: [],
  3389. canActivateChecks: [],
  3390. }) {
  3391. const future = futureNode.value;
  3392. const curr = currNode ? currNode.value : null;
  3393. const context = parentContexts ? parentContexts.getContext(futureNode.value.outlet) : null;
  3394. // reusing the node
  3395. if (curr && future.routeConfig === curr.routeConfig) {
  3396. const shouldRun = shouldRunGuardsAndResolvers(curr, future, future.routeConfig.runGuardsAndResolvers);
  3397. if (shouldRun) {
  3398. checks.canActivateChecks.push(new CanActivate(futurePath));
  3399. }
  3400. else {
  3401. // we need to set the data
  3402. future.data = curr.data;
  3403. future._resolvedData = curr._resolvedData;
  3404. }
  3405. // If we have a component, we need to go through an outlet.
  3406. if (future.component) {
  3407. getChildRouteGuards(futureNode, currNode, context ? context.children : null, futurePath, checks);
  3408. // if we have a componentless route, we recurse but keep the same outlet map.
  3409. }
  3410. else {
  3411. getChildRouteGuards(futureNode, currNode, parentContexts, futurePath, checks);
  3412. }
  3413. if (shouldRun && context && context.outlet && context.outlet.isActivated) {
  3414. checks.canDeactivateChecks.push(new CanDeactivate(context.outlet.component, curr));
  3415. }
  3416. }
  3417. else {
  3418. if (curr) {
  3419. deactivateRouteAndItsChildren(currNode, context, checks);
  3420. }
  3421. checks.canActivateChecks.push(new CanActivate(futurePath));
  3422. // If we have a component, we need to go through an outlet.
  3423. if (future.component) {
  3424. getChildRouteGuards(futureNode, null, context ? context.children : null, futurePath, checks);
  3425. // if we have a componentless route, we recurse but keep the same outlet map.
  3426. }
  3427. else {
  3428. getChildRouteGuards(futureNode, null, parentContexts, futurePath, checks);
  3429. }
  3430. }
  3431. return checks;
  3432. }
  3433. function shouldRunGuardsAndResolvers(curr, future, mode) {
  3434. if (typeof mode === 'function') {
  3435. return mode(curr, future);
  3436. }
  3437. switch (mode) {
  3438. case 'pathParamsChange':
  3439. return !equalPath(curr.url, future.url);
  3440. case 'pathParamsOrQueryParamsChange':
  3441. return (!equalPath(curr.url, future.url) || !shallowEqual(curr.queryParams, future.queryParams));
  3442. case 'always':
  3443. return true;
  3444. case 'paramsOrQueryParamsChange':
  3445. return (!equalParamsAndUrlSegments(curr, future) ||
  3446. !shallowEqual(curr.queryParams, future.queryParams));
  3447. case 'paramsChange':
  3448. default:
  3449. return !equalParamsAndUrlSegments(curr, future);
  3450. }
  3451. }
  3452. function deactivateRouteAndItsChildren(route, context, checks) {
  3453. const children = nodeChildrenAsMap(route);
  3454. const r = route.value;
  3455. Object.entries(children).forEach(([childName, node]) => {
  3456. if (!r.component) {
  3457. deactivateRouteAndItsChildren(node, context, checks);
  3458. }
  3459. else if (context) {
  3460. deactivateRouteAndItsChildren(node, context.children.getContext(childName), checks);
  3461. }
  3462. else {
  3463. deactivateRouteAndItsChildren(node, null, checks);
  3464. }
  3465. });
  3466. if (!r.component) {
  3467. checks.canDeactivateChecks.push(new CanDeactivate(null, r));
  3468. }
  3469. else if (context && context.outlet && context.outlet.isActivated) {
  3470. checks.canDeactivateChecks.push(new CanDeactivate(context.outlet.component, r));
  3471. }
  3472. else {
  3473. checks.canDeactivateChecks.push(new CanDeactivate(null, r));
  3474. }
  3475. }
  3476. /**
  3477. * Simple function check, but generic so type inference will flow. Example:
  3478. *
  3479. * function product(a: number, b: number) {
  3480. * return a * b;
  3481. * }
  3482. *
  3483. * if (isFunction<product>(fn)) {
  3484. * return fn(1, 2);
  3485. * } else {
  3486. * throw "Must provide the `product` function";
  3487. * }
  3488. */
  3489. function isFunction(v) {
  3490. return typeof v === 'function';
  3491. }
  3492. function isBoolean(v) {
  3493. return typeof v === 'boolean';
  3494. }
  3495. function isCanLoad(guard) {
  3496. return guard && isFunction(guard.canLoad);
  3497. }
  3498. function isCanActivate(guard) {
  3499. return guard && isFunction(guard.canActivate);
  3500. }
  3501. function isCanActivateChild(guard) {
  3502. return guard && isFunction(guard.canActivateChild);
  3503. }
  3504. function isCanDeactivate(guard) {
  3505. return guard && isFunction(guard.canDeactivate);
  3506. }
  3507. function isCanMatch(guard) {
  3508. return guard && isFunction(guard.canMatch);
  3509. }
  3510. function isEmptyError(e) {
  3511. return e instanceof EmptyError || e?.name === 'EmptyError';
  3512. }
  3513. const INITIAL_VALUE = /* @__PURE__ */ Symbol('INITIAL_VALUE');
  3514. function prioritizedGuardValue() {
  3515. return switchMap((obs) => {
  3516. return combineLatest(obs.map((o) => o.pipe(take(1), startWith(INITIAL_VALUE)))).pipe(map((results) => {
  3517. for (const result of results) {
  3518. if (result === true) {
  3519. // If result is true, check the next one
  3520. continue;
  3521. }
  3522. else if (result === INITIAL_VALUE) {
  3523. // If guard has not finished, we need to stop processing.
  3524. return INITIAL_VALUE;
  3525. }
  3526. else if (result === false || isRedirect(result)) {
  3527. // Result finished and was not true. Return the result.
  3528. // Note that we only allow false/UrlTree/RedirectCommand. Other values are considered invalid and
  3529. // ignored.
  3530. return result;
  3531. }
  3532. }
  3533. // Everything resolved to true. Return true.
  3534. return true;
  3535. }), filter((item) => item !== INITIAL_VALUE), take(1));
  3536. });
  3537. }
  3538. function isRedirect(val) {
  3539. return isUrlTree(val) || val instanceof RedirectCommand;
  3540. }
  3541. function checkGuards(injector, forwardEvent) {
  3542. return mergeMap((t) => {
  3543. const { targetSnapshot, currentSnapshot, guards: { canActivateChecks, canDeactivateChecks }, } = t;
  3544. if (canDeactivateChecks.length === 0 && canActivateChecks.length === 0) {
  3545. return of({ ...t, guardsResult: true });
  3546. }
  3547. return runCanDeactivateChecks(canDeactivateChecks, targetSnapshot, currentSnapshot, injector).pipe(mergeMap((canDeactivate) => {
  3548. return canDeactivate && isBoolean(canDeactivate)
  3549. ? runCanActivateChecks(targetSnapshot, canActivateChecks, injector, forwardEvent)
  3550. : of(canDeactivate);
  3551. }), map((guardsResult) => ({ ...t, guardsResult })));
  3552. });
  3553. }
  3554. function runCanDeactivateChecks(checks, futureRSS, currRSS, injector) {
  3555. return from(checks).pipe(mergeMap((check) => runCanDeactivate(check.component, check.route, currRSS, futureRSS, injector)), first((result) => {
  3556. return result !== true;
  3557. }, true));
  3558. }
  3559. function runCanActivateChecks(futureSnapshot, checks, injector, forwardEvent) {
  3560. return from(checks).pipe(concatMap((check) => {
  3561. return concat(fireChildActivationStart(check.route.parent, forwardEvent), fireActivationStart(check.route, forwardEvent), runCanActivateChild(futureSnapshot, check.path, injector), runCanActivate(futureSnapshot, check.route, injector));
  3562. }), first((result) => {
  3563. return result !== true;
  3564. }, true));
  3565. }
  3566. /**
  3567. * This should fire off `ActivationStart` events for each route being activated at this
  3568. * level.
  3569. * In other words, if you're activating `a` and `b` below, `path` will contain the
  3570. * `ActivatedRouteSnapshot`s for both and we will fire `ActivationStart` for both. Always
  3571. * return
  3572. * `true` so checks continue to run.
  3573. */
  3574. function fireActivationStart(snapshot, forwardEvent) {
  3575. if (snapshot !== null && forwardEvent) {
  3576. forwardEvent(new ActivationStart(snapshot));
  3577. }
  3578. return of(true);
  3579. }
  3580. /**
  3581. * This should fire off `ChildActivationStart` events for each route being activated at this
  3582. * level.
  3583. * In other words, if you're activating `a` and `b` below, `path` will contain the
  3584. * `ActivatedRouteSnapshot`s for both and we will fire `ChildActivationStart` for both. Always
  3585. * return
  3586. * `true` so checks continue to run.
  3587. */
  3588. function fireChildActivationStart(snapshot, forwardEvent) {
  3589. if (snapshot !== null && forwardEvent) {
  3590. forwardEvent(new ChildActivationStart(snapshot));
  3591. }
  3592. return of(true);
  3593. }
  3594. function runCanActivate(futureRSS, futureARS, injector) {
  3595. const canActivate = futureARS.routeConfig ? futureARS.routeConfig.canActivate : null;
  3596. if (!canActivate || canActivate.length === 0)
  3597. return of(true);
  3598. const canActivateObservables = canActivate.map((canActivate) => {
  3599. return defer(() => {
  3600. const closestInjector = getClosestRouteInjector(futureARS) ?? injector;
  3601. const guard = getTokenOrFunctionIdentity(canActivate, closestInjector);
  3602. const guardVal = isCanActivate(guard)
  3603. ? guard.canActivate(futureARS, futureRSS)
  3604. : runInInjectionContext(closestInjector, () => guard(futureARS, futureRSS));
  3605. return wrapIntoObservable(guardVal).pipe(first());
  3606. });
  3607. });
  3608. return of(canActivateObservables).pipe(prioritizedGuardValue());
  3609. }
  3610. function runCanActivateChild(futureRSS, path, injector) {
  3611. const futureARS = path[path.length - 1];
  3612. const canActivateChildGuards = path
  3613. .slice(0, path.length - 1)
  3614. .reverse()
  3615. .map((p) => getCanActivateChild(p))
  3616. .filter((_) => _ !== null);
  3617. const canActivateChildGuardsMapped = canActivateChildGuards.map((d) => {
  3618. return defer(() => {
  3619. const guardsMapped = d.guards.map((canActivateChild) => {
  3620. const closestInjector = getClosestRouteInjector(d.node) ?? injector;
  3621. const guard = getTokenOrFunctionIdentity(canActivateChild, closestInjector);
  3622. const guardVal = isCanActivateChild(guard)
  3623. ? guard.canActivateChild(futureARS, futureRSS)
  3624. : runInInjectionContext(closestInjector, () => guard(futureARS, futureRSS));
  3625. return wrapIntoObservable(guardVal).pipe(first());
  3626. });
  3627. return of(guardsMapped).pipe(prioritizedGuardValue());
  3628. });
  3629. });
  3630. return of(canActivateChildGuardsMapped).pipe(prioritizedGuardValue());
  3631. }
  3632. function runCanDeactivate(component, currARS, currRSS, futureRSS, injector) {
  3633. const canDeactivate = currARS && currARS.routeConfig ? currARS.routeConfig.canDeactivate : null;
  3634. if (!canDeactivate || canDeactivate.length === 0)
  3635. return of(true);
  3636. const canDeactivateObservables = canDeactivate.map((c) => {
  3637. const closestInjector = getClosestRouteInjector(currARS) ?? injector;
  3638. const guard = getTokenOrFunctionIdentity(c, closestInjector);
  3639. const guardVal = isCanDeactivate(guard)
  3640. ? guard.canDeactivate(component, currARS, currRSS, futureRSS)
  3641. : runInInjectionContext(closestInjector, () => guard(component, currARS, currRSS, futureRSS));
  3642. return wrapIntoObservable(guardVal).pipe(first());
  3643. });
  3644. return of(canDeactivateObservables).pipe(prioritizedGuardValue());
  3645. }
  3646. function runCanLoadGuards(injector, route, segments, urlSerializer) {
  3647. const canLoad = route.canLoad;
  3648. if (canLoad === undefined || canLoad.length === 0) {
  3649. return of(true);
  3650. }
  3651. const canLoadObservables = canLoad.map((injectionToken) => {
  3652. const guard = getTokenOrFunctionIdentity(injectionToken, injector);
  3653. const guardVal = isCanLoad(guard)
  3654. ? guard.canLoad(route, segments)
  3655. : runInInjectionContext(injector, () => guard(route, segments));
  3656. return wrapIntoObservable(guardVal);
  3657. });
  3658. return of(canLoadObservables).pipe(prioritizedGuardValue(), redirectIfUrlTree(urlSerializer));
  3659. }
  3660. function redirectIfUrlTree(urlSerializer) {
  3661. return pipe(tap((result) => {
  3662. if (typeof result === 'boolean')
  3663. return;
  3664. throw redirectingNavigationError(urlSerializer, result);
  3665. }), map((result) => result === true));
  3666. }
  3667. function runCanMatchGuards(injector, route, segments, urlSerializer) {
  3668. const canMatch = route.canMatch;
  3669. if (!canMatch || canMatch.length === 0)
  3670. return of(true);
  3671. const canMatchObservables = canMatch.map((injectionToken) => {
  3672. const guard = getTokenOrFunctionIdentity(injectionToken, injector);
  3673. const guardVal = isCanMatch(guard)
  3674. ? guard.canMatch(route, segments)
  3675. : runInInjectionContext(injector, () => guard(route, segments));
  3676. return wrapIntoObservable(guardVal);
  3677. });
  3678. return of(canMatchObservables).pipe(prioritizedGuardValue(), redirectIfUrlTree(urlSerializer));
  3679. }
  3680. class NoMatch {
  3681. segmentGroup;
  3682. constructor(segmentGroup) {
  3683. this.segmentGroup = segmentGroup || null;
  3684. }
  3685. }
  3686. class AbsoluteRedirect extends Error {
  3687. urlTree;
  3688. constructor(urlTree) {
  3689. super();
  3690. this.urlTree = urlTree;
  3691. }
  3692. }
  3693. function noMatch$1(segmentGroup) {
  3694. return throwError(new NoMatch(segmentGroup));
  3695. }
  3696. function namedOutletsRedirect(redirectTo) {
  3697. return throwError(new _RuntimeError(4000 /* RuntimeErrorCode.NAMED_OUTLET_REDIRECT */, (typeof ngDevMode === 'undefined' || ngDevMode) &&
  3698. `Only absolute redirects can have named outlets. redirectTo: '${redirectTo}'`));
  3699. }
  3700. function canLoadFails(route) {
  3701. return throwError(navigationCancelingError((typeof ngDevMode === 'undefined' || ngDevMode) &&
  3702. `Cannot load children because the guard of the route "path: '${route.path}'" returned false`, NavigationCancellationCode.GuardRejected));
  3703. }
  3704. class ApplyRedirects {
  3705. urlSerializer;
  3706. urlTree;
  3707. constructor(urlSerializer, urlTree) {
  3708. this.urlSerializer = urlSerializer;
  3709. this.urlTree = urlTree;
  3710. }
  3711. lineralizeSegments(route, urlTree) {
  3712. let res = [];
  3713. let c = urlTree.root;
  3714. while (true) {
  3715. res = res.concat(c.segments);
  3716. if (c.numberOfChildren === 0) {
  3717. return of(res);
  3718. }
  3719. if (c.numberOfChildren > 1 || !c.children[PRIMARY_OUTLET]) {
  3720. return namedOutletsRedirect(`${route.redirectTo}`);
  3721. }
  3722. c = c.children[PRIMARY_OUTLET];
  3723. }
  3724. }
  3725. applyRedirectCommands(segments, redirectTo, posParams, currentSnapshot, injector) {
  3726. if (typeof redirectTo !== 'string') {
  3727. const redirectToFn = redirectTo;
  3728. const { queryParams, fragment, routeConfig, url, outlet, params, data, title } = currentSnapshot;
  3729. const newRedirect = runInInjectionContext(injector, () => redirectToFn({ params, data, queryParams, fragment, routeConfig, url, outlet, title }));
  3730. if (newRedirect instanceof UrlTree) {
  3731. throw new AbsoluteRedirect(newRedirect);
  3732. }
  3733. redirectTo = newRedirect;
  3734. }
  3735. const newTree = this.applyRedirectCreateUrlTree(redirectTo, this.urlSerializer.parse(redirectTo), segments, posParams);
  3736. if (redirectTo[0] === '/') {
  3737. throw new AbsoluteRedirect(newTree);
  3738. }
  3739. return newTree;
  3740. }
  3741. applyRedirectCreateUrlTree(redirectTo, urlTree, segments, posParams) {
  3742. const newRoot = this.createSegmentGroup(redirectTo, urlTree.root, segments, posParams);
  3743. return new UrlTree(newRoot, this.createQueryParams(urlTree.queryParams, this.urlTree.queryParams), urlTree.fragment);
  3744. }
  3745. createQueryParams(redirectToParams, actualParams) {
  3746. const res = {};
  3747. Object.entries(redirectToParams).forEach(([k, v]) => {
  3748. const copySourceValue = typeof v === 'string' && v[0] === ':';
  3749. if (copySourceValue) {
  3750. const sourceName = v.substring(1);
  3751. res[k] = actualParams[sourceName];
  3752. }
  3753. else {
  3754. res[k] = v;
  3755. }
  3756. });
  3757. return res;
  3758. }
  3759. createSegmentGroup(redirectTo, group, segments, posParams) {
  3760. const updatedSegments = this.createSegments(redirectTo, group.segments, segments, posParams);
  3761. let children = {};
  3762. Object.entries(group.children).forEach(([name, child]) => {
  3763. children[name] = this.createSegmentGroup(redirectTo, child, segments, posParams);
  3764. });
  3765. return new UrlSegmentGroup(updatedSegments, children);
  3766. }
  3767. createSegments(redirectTo, redirectToSegments, actualSegments, posParams) {
  3768. return redirectToSegments.map((s) => s.path[0] === ':'
  3769. ? this.findPosParam(redirectTo, s, posParams)
  3770. : this.findOrReturn(s, actualSegments));
  3771. }
  3772. findPosParam(redirectTo, redirectToUrlSegment, posParams) {
  3773. const pos = posParams[redirectToUrlSegment.path.substring(1)];
  3774. if (!pos)
  3775. throw new _RuntimeError(4001 /* RuntimeErrorCode.MISSING_REDIRECT */, (typeof ngDevMode === 'undefined' || ngDevMode) &&
  3776. `Cannot redirect to '${redirectTo}'. Cannot find '${redirectToUrlSegment.path}'.`);
  3777. return pos;
  3778. }
  3779. findOrReturn(redirectToUrlSegment, actualSegments) {
  3780. let idx = 0;
  3781. for (const s of actualSegments) {
  3782. if (s.path === redirectToUrlSegment.path) {
  3783. actualSegments.splice(idx);
  3784. return s;
  3785. }
  3786. idx++;
  3787. }
  3788. return redirectToUrlSegment;
  3789. }
  3790. }
  3791. const noMatch = {
  3792. matched: false,
  3793. consumedSegments: [],
  3794. remainingSegments: [],
  3795. parameters: {},
  3796. positionalParamSegments: {},
  3797. };
  3798. function matchWithChecks(segmentGroup, route, segments, injector, urlSerializer) {
  3799. const result = match(segmentGroup, route, segments);
  3800. if (!result.matched) {
  3801. return of(result);
  3802. }
  3803. // Only create the Route's `EnvironmentInjector` if it matches the attempted
  3804. // navigation
  3805. injector = getOrCreateRouteInjectorIfNeeded(route, injector);
  3806. return runCanMatchGuards(injector, route, segments, urlSerializer).pipe(map((v) => (v === true ? result : { ...noMatch })));
  3807. }
  3808. function match(segmentGroup, route, segments) {
  3809. if (route.path === '**') {
  3810. return createWildcardMatchResult(segments);
  3811. }
  3812. if (route.path === '') {
  3813. if (route.pathMatch === 'full' && (segmentGroup.hasChildren() || segments.length > 0)) {
  3814. return { ...noMatch };
  3815. }
  3816. return {
  3817. matched: true,
  3818. consumedSegments: [],
  3819. remainingSegments: segments,
  3820. parameters: {},
  3821. positionalParamSegments: {},
  3822. };
  3823. }
  3824. const matcher = route.matcher || defaultUrlMatcher;
  3825. const res = matcher(segments, segmentGroup, route);
  3826. if (!res)
  3827. return { ...noMatch };
  3828. const posParams = {};
  3829. Object.entries(res.posParams ?? {}).forEach(([k, v]) => {
  3830. posParams[k] = v.path;
  3831. });
  3832. const parameters = res.consumed.length > 0
  3833. ? { ...posParams, ...res.consumed[res.consumed.length - 1].parameters }
  3834. : posParams;
  3835. return {
  3836. matched: true,
  3837. consumedSegments: res.consumed,
  3838. remainingSegments: segments.slice(res.consumed.length),
  3839. // TODO(atscott): investigate combining parameters and positionalParamSegments
  3840. parameters,
  3841. positionalParamSegments: res.posParams ?? {},
  3842. };
  3843. }
  3844. function createWildcardMatchResult(segments) {
  3845. return {
  3846. matched: true,
  3847. parameters: segments.length > 0 ? last(segments).parameters : {},
  3848. consumedSegments: segments,
  3849. remainingSegments: [],
  3850. positionalParamSegments: {},
  3851. };
  3852. }
  3853. function split(segmentGroup, consumedSegments, slicedSegments, config) {
  3854. if (slicedSegments.length > 0 &&
  3855. containsEmptyPathMatchesWithNamedOutlets(segmentGroup, slicedSegments, config)) {
  3856. const s = new UrlSegmentGroup(consumedSegments, createChildrenForEmptyPaths(config, new UrlSegmentGroup(slicedSegments, segmentGroup.children)));
  3857. return { segmentGroup: s, slicedSegments: [] };
  3858. }
  3859. if (slicedSegments.length === 0 &&
  3860. containsEmptyPathMatches(segmentGroup, slicedSegments, config)) {
  3861. const s = new UrlSegmentGroup(segmentGroup.segments, addEmptyPathsToChildrenIfNeeded(segmentGroup, slicedSegments, config, segmentGroup.children));
  3862. return { segmentGroup: s, slicedSegments };
  3863. }
  3864. const s = new UrlSegmentGroup(segmentGroup.segments, segmentGroup.children);
  3865. return { segmentGroup: s, slicedSegments };
  3866. }
  3867. function addEmptyPathsToChildrenIfNeeded(segmentGroup, slicedSegments, routes, children) {
  3868. const res = {};
  3869. for (const r of routes) {
  3870. if (emptyPathMatch(segmentGroup, slicedSegments, r) && !children[getOutlet(r)]) {
  3871. const s = new UrlSegmentGroup([], {});
  3872. res[getOutlet(r)] = s;
  3873. }
  3874. }
  3875. return { ...children, ...res };
  3876. }
  3877. function createChildrenForEmptyPaths(routes, primarySegment) {
  3878. const res = {};
  3879. res[PRIMARY_OUTLET] = primarySegment;
  3880. for (const r of routes) {
  3881. if (r.path === '' && getOutlet(r) !== PRIMARY_OUTLET) {
  3882. const s = new UrlSegmentGroup([], {});
  3883. res[getOutlet(r)] = s;
  3884. }
  3885. }
  3886. return res;
  3887. }
  3888. function containsEmptyPathMatchesWithNamedOutlets(segmentGroup, slicedSegments, routes) {
  3889. return routes.some((r) => emptyPathMatch(segmentGroup, slicedSegments, r) && getOutlet(r) !== PRIMARY_OUTLET);
  3890. }
  3891. function containsEmptyPathMatches(segmentGroup, slicedSegments, routes) {
  3892. return routes.some((r) => emptyPathMatch(segmentGroup, slicedSegments, r));
  3893. }
  3894. function emptyPathMatch(segmentGroup, slicedSegments, r) {
  3895. if ((segmentGroup.hasChildren() || slicedSegments.length > 0) && r.pathMatch === 'full') {
  3896. return false;
  3897. }
  3898. return r.path === '';
  3899. }
  3900. function noLeftoversInUrl(segmentGroup, segments, outlet) {
  3901. return segments.length === 0 && !segmentGroup.children[outlet];
  3902. }
  3903. /**
  3904. * Class used to indicate there were no additional route config matches but that all segments of
  3905. * the URL were consumed during matching so the route was URL matched. When this happens, we still
  3906. * try to match child configs in case there are empty path children.
  3907. */
  3908. class NoLeftoversInUrl {
  3909. }
  3910. function recognize$1(injector, configLoader, rootComponentType, config, urlTree, urlSerializer, paramsInheritanceStrategy = 'emptyOnly') {
  3911. return new Recognizer(injector, configLoader, rootComponentType, config, urlTree, paramsInheritanceStrategy, urlSerializer).recognize();
  3912. }
  3913. const MAX_ALLOWED_REDIRECTS = 31;
  3914. class Recognizer {
  3915. injector;
  3916. configLoader;
  3917. rootComponentType;
  3918. config;
  3919. urlTree;
  3920. paramsInheritanceStrategy;
  3921. urlSerializer;
  3922. applyRedirects;
  3923. absoluteRedirectCount = 0;
  3924. allowRedirects = true;
  3925. constructor(injector, configLoader, rootComponentType, config, urlTree, paramsInheritanceStrategy, urlSerializer) {
  3926. this.injector = injector;
  3927. this.configLoader = configLoader;
  3928. this.rootComponentType = rootComponentType;
  3929. this.config = config;
  3930. this.urlTree = urlTree;
  3931. this.paramsInheritanceStrategy = paramsInheritanceStrategy;
  3932. this.urlSerializer = urlSerializer;
  3933. this.applyRedirects = new ApplyRedirects(this.urlSerializer, this.urlTree);
  3934. }
  3935. noMatchError(e) {
  3936. return new _RuntimeError(4002 /* RuntimeErrorCode.NO_MATCH */, typeof ngDevMode === 'undefined' || ngDevMode
  3937. ? `Cannot match any routes. URL Segment: '${e.segmentGroup}'`
  3938. : `'${e.segmentGroup}'`);
  3939. }
  3940. recognize() {
  3941. const rootSegmentGroup = split(this.urlTree.root, [], [], this.config).segmentGroup;
  3942. return this.match(rootSegmentGroup).pipe(map(({ children, rootSnapshot }) => {
  3943. const rootNode = new TreeNode(rootSnapshot, children);
  3944. const routeState = new RouterStateSnapshot('', rootNode);
  3945. const tree = createUrlTreeFromSnapshot(rootSnapshot, [], this.urlTree.queryParams, this.urlTree.fragment);
  3946. // https://github.com/angular/angular/issues/47307
  3947. // Creating the tree stringifies the query params
  3948. // We don't want to do this here so reassign them to the original.
  3949. tree.queryParams = this.urlTree.queryParams;
  3950. routeState.url = this.urlSerializer.serialize(tree);
  3951. return { state: routeState, tree };
  3952. }));
  3953. }
  3954. match(rootSegmentGroup) {
  3955. // Use Object.freeze to prevent readers of the Router state from modifying it outside
  3956. // of a navigation, resulting in the router being out of sync with the browser.
  3957. const rootSnapshot = new ActivatedRouteSnapshot([], Object.freeze({}), Object.freeze({ ...this.urlTree.queryParams }), this.urlTree.fragment, Object.freeze({}), PRIMARY_OUTLET, this.rootComponentType, null, {});
  3958. return this.processSegmentGroup(this.injector, this.config, rootSegmentGroup, PRIMARY_OUTLET, rootSnapshot).pipe(map((children) => {
  3959. return { children, rootSnapshot };
  3960. }), catchError((e) => {
  3961. if (e instanceof AbsoluteRedirect) {
  3962. this.urlTree = e.urlTree;
  3963. return this.match(e.urlTree.root);
  3964. }
  3965. if (e instanceof NoMatch) {
  3966. throw this.noMatchError(e);
  3967. }
  3968. throw e;
  3969. }));
  3970. }
  3971. processSegmentGroup(injector, config, segmentGroup, outlet, parentRoute) {
  3972. if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) {
  3973. return this.processChildren(injector, config, segmentGroup, parentRoute);
  3974. }
  3975. return this.processSegment(injector, config, segmentGroup, segmentGroup.segments, outlet, true, parentRoute).pipe(map((child) => (child instanceof TreeNode ? [child] : [])));
  3976. }
  3977. /**
  3978. * Matches every child outlet in the `segmentGroup` to a `Route` in the config. Returns `null` if
  3979. * we cannot find a match for _any_ of the children.
  3980. *
  3981. * @param config - The `Routes` to match against
  3982. * @param segmentGroup - The `UrlSegmentGroup` whose children need to be matched against the
  3983. * config.
  3984. */
  3985. processChildren(injector, config, segmentGroup, parentRoute) {
  3986. // Expand outlets one at a time, starting with the primary outlet. We need to do it this way
  3987. // because an absolute redirect from the primary outlet takes precedence.
  3988. const childOutlets = [];
  3989. for (const child of Object.keys(segmentGroup.children)) {
  3990. if (child === 'primary') {
  3991. childOutlets.unshift(child);
  3992. }
  3993. else {
  3994. childOutlets.push(child);
  3995. }
  3996. }
  3997. return from(childOutlets).pipe(concatMap((childOutlet) => {
  3998. const child = segmentGroup.children[childOutlet];
  3999. // Sort the config so that routes with outlets that match the one being activated
  4000. // appear first, followed by routes for other outlets, which might match if they have
  4001. // an empty path.
  4002. const sortedConfig = sortByMatchingOutlets(config, childOutlet);
  4003. return this.processSegmentGroup(injector, sortedConfig, child, childOutlet, parentRoute);
  4004. }), scan((children, outletChildren) => {
  4005. children.push(...outletChildren);
  4006. return children;
  4007. }), defaultIfEmpty(null), last$1(), mergeMap((children) => {
  4008. if (children === null)
  4009. return noMatch$1(segmentGroup);
  4010. // Because we may have matched two outlets to the same empty path segment, we can have
  4011. // multiple activated results for the same outlet. We should merge the children of
  4012. // these results so the final return value is only one `TreeNode` per outlet.
  4013. const mergedChildren = mergeEmptyPathMatches(children);
  4014. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  4015. // This should really never happen - we are only taking the first match for each
  4016. // outlet and merge the empty path matches.
  4017. checkOutletNameUniqueness(mergedChildren);
  4018. }
  4019. sortActivatedRouteSnapshots(mergedChildren);
  4020. return of(mergedChildren);
  4021. }));
  4022. }
  4023. processSegment(injector, routes, segmentGroup, segments, outlet, allowRedirects, parentRoute) {
  4024. return from(routes).pipe(concatMap((r) => {
  4025. return this.processSegmentAgainstRoute(r._injector ?? injector, routes, r, segmentGroup, segments, outlet, allowRedirects, parentRoute).pipe(catchError((e) => {
  4026. if (e instanceof NoMatch) {
  4027. return of(null);
  4028. }
  4029. throw e;
  4030. }));
  4031. }), first((x) => !!x), catchError((e) => {
  4032. if (isEmptyError(e)) {
  4033. if (noLeftoversInUrl(segmentGroup, segments, outlet)) {
  4034. return of(new NoLeftoversInUrl());
  4035. }
  4036. return noMatch$1(segmentGroup);
  4037. }
  4038. throw e;
  4039. }));
  4040. }
  4041. processSegmentAgainstRoute(injector, routes, route, rawSegment, segments, outlet, allowRedirects, parentRoute) {
  4042. // We allow matches to empty paths when the outlets differ so we can match a url like `/(b:b)` to
  4043. // a config like
  4044. // * `{path: '', children: [{path: 'b', outlet: 'b'}]}`
  4045. // or even
  4046. // * `{path: '', outlet: 'a', children: [{path: 'b', outlet: 'b'}]`
  4047. //
  4048. // The exception here is when the segment outlet is for the primary outlet. This would
  4049. // result in a match inside the named outlet because all children there are written as primary
  4050. // outlets. So we need to prevent child named outlet matches in a url like `/b` in a config like
  4051. // * `{path: '', outlet: 'x' children: [{path: 'b'}]}`
  4052. // This should only match if the url is `/(x:b)`.
  4053. if (getOutlet(route) !== outlet &&
  4054. (outlet === PRIMARY_OUTLET || !emptyPathMatch(rawSegment, segments, route))) {
  4055. return noMatch$1(rawSegment);
  4056. }
  4057. if (route.redirectTo === undefined) {
  4058. return this.matchSegmentAgainstRoute(injector, rawSegment, route, segments, outlet, parentRoute);
  4059. }
  4060. if (this.allowRedirects && allowRedirects) {
  4061. return this.expandSegmentAgainstRouteUsingRedirect(injector, rawSegment, routes, route, segments, outlet, parentRoute);
  4062. }
  4063. return noMatch$1(rawSegment);
  4064. }
  4065. expandSegmentAgainstRouteUsingRedirect(injector, segmentGroup, routes, route, segments, outlet, parentRoute) {
  4066. const { matched, parameters, consumedSegments, positionalParamSegments, remainingSegments } = match(segmentGroup, route, segments);
  4067. if (!matched)
  4068. return noMatch$1(segmentGroup);
  4069. // TODO(atscott): Move all of this under an if(ngDevMode) as a breaking change and allow stack
  4070. // size exceeded in production
  4071. if (typeof route.redirectTo === 'string' && route.redirectTo[0] === '/') {
  4072. this.absoluteRedirectCount++;
  4073. if (this.absoluteRedirectCount > MAX_ALLOWED_REDIRECTS) {
  4074. if (ngDevMode) {
  4075. throw new _RuntimeError(4016 /* RuntimeErrorCode.INFINITE_REDIRECT */, `Detected possible infinite redirect when redirecting from '${this.urlTree}' to '${route.redirectTo}'.\n` +
  4076. `This is currently a dev mode only error but will become a` +
  4077. ` call stack size exceeded error in production in a future major version.`);
  4078. }
  4079. this.allowRedirects = false;
  4080. }
  4081. }
  4082. const currentSnapshot = new ActivatedRouteSnapshot(segments, parameters, Object.freeze({ ...this.urlTree.queryParams }), this.urlTree.fragment, getData(route), getOutlet(route), route.component ?? route._loadedComponent ?? null, route, getResolve(route));
  4083. const inherited = getInherited(currentSnapshot, parentRoute, this.paramsInheritanceStrategy);
  4084. currentSnapshot.params = Object.freeze(inherited.params);
  4085. currentSnapshot.data = Object.freeze(inherited.data);
  4086. const newTree = this.applyRedirects.applyRedirectCommands(consumedSegments, route.redirectTo, positionalParamSegments, currentSnapshot, injector);
  4087. return this.applyRedirects.lineralizeSegments(route, newTree).pipe(mergeMap((newSegments) => {
  4088. return this.processSegment(injector, routes, segmentGroup, newSegments.concat(remainingSegments), outlet, false, parentRoute);
  4089. }));
  4090. }
  4091. matchSegmentAgainstRoute(injector, rawSegment, route, segments, outlet, parentRoute) {
  4092. const matchResult = matchWithChecks(rawSegment, route, segments, injector, this.urlSerializer);
  4093. if (route.path === '**') {
  4094. // Prior versions of the route matching algorithm would stop matching at the wildcard route.
  4095. // We should investigate a better strategy for any existing children. Otherwise, these
  4096. // child segments are silently dropped from the navigation.
  4097. // https://github.com/angular/angular/issues/40089
  4098. rawSegment.children = {};
  4099. }
  4100. return matchResult.pipe(switchMap((result) => {
  4101. if (!result.matched) {
  4102. return noMatch$1(rawSegment);
  4103. }
  4104. // If the route has an injector created from providers, we should start using that.
  4105. injector = route._injector ?? injector;
  4106. return this.getChildConfig(injector, route, segments).pipe(switchMap(({ routes: childConfig }) => {
  4107. const childInjector = route._loadedInjector ?? injector;
  4108. const { parameters, consumedSegments, remainingSegments } = result;
  4109. const snapshot = new ActivatedRouteSnapshot(consumedSegments, parameters, Object.freeze({ ...this.urlTree.queryParams }), this.urlTree.fragment, getData(route), getOutlet(route), route.component ?? route._loadedComponent ?? null, route, getResolve(route));
  4110. const inherited = getInherited(snapshot, parentRoute, this.paramsInheritanceStrategy);
  4111. snapshot.params = Object.freeze(inherited.params);
  4112. snapshot.data = Object.freeze(inherited.data);
  4113. const { segmentGroup, slicedSegments } = split(rawSegment, consumedSegments, remainingSegments, childConfig);
  4114. if (slicedSegments.length === 0 && segmentGroup.hasChildren()) {
  4115. return this.processChildren(childInjector, childConfig, segmentGroup, snapshot).pipe(map((children) => {
  4116. return new TreeNode(snapshot, children);
  4117. }));
  4118. }
  4119. if (childConfig.length === 0 && slicedSegments.length === 0) {
  4120. return of(new TreeNode(snapshot, []));
  4121. }
  4122. const matchedOnOutlet = getOutlet(route) === outlet;
  4123. // If we matched a config due to empty path match on a different outlet, we need to
  4124. // continue passing the current outlet for the segment rather than switch to PRIMARY.
  4125. // Note that we switch to primary when we have a match because outlet configs look like
  4126. // this: {path: 'a', outlet: 'a', children: [
  4127. // {path: 'b', component: B},
  4128. // {path: 'c', component: C},
  4129. // ]}
  4130. // Notice that the children of the named outlet are configured with the primary outlet
  4131. return this.processSegment(childInjector, childConfig, segmentGroup, slicedSegments, matchedOnOutlet ? PRIMARY_OUTLET : outlet, true, snapshot).pipe(map((child) => {
  4132. return new TreeNode(snapshot, child instanceof TreeNode ? [child] : []);
  4133. }));
  4134. }));
  4135. }));
  4136. }
  4137. getChildConfig(injector, route, segments) {
  4138. if (route.children) {
  4139. // The children belong to the same module
  4140. return of({ routes: route.children, injector });
  4141. }
  4142. if (route.loadChildren) {
  4143. // lazy children belong to the loaded module
  4144. if (route._loadedRoutes !== undefined) {
  4145. return of({ routes: route._loadedRoutes, injector: route._loadedInjector });
  4146. }
  4147. return runCanLoadGuards(injector, route, segments, this.urlSerializer).pipe(mergeMap((shouldLoadResult) => {
  4148. if (shouldLoadResult) {
  4149. return this.configLoader.loadChildren(injector, route).pipe(tap((cfg) => {
  4150. route._loadedRoutes = cfg.routes;
  4151. route._loadedInjector = cfg.injector;
  4152. }));
  4153. }
  4154. return canLoadFails(route);
  4155. }));
  4156. }
  4157. return of({ routes: [], injector });
  4158. }
  4159. }
  4160. function sortActivatedRouteSnapshots(nodes) {
  4161. nodes.sort((a, b) => {
  4162. if (a.value.outlet === PRIMARY_OUTLET)
  4163. return -1;
  4164. if (b.value.outlet === PRIMARY_OUTLET)
  4165. return 1;
  4166. return a.value.outlet.localeCompare(b.value.outlet);
  4167. });
  4168. }
  4169. function hasEmptyPathConfig(node) {
  4170. const config = node.value.routeConfig;
  4171. return config && config.path === '';
  4172. }
  4173. /**
  4174. * Finds `TreeNode`s with matching empty path route configs and merges them into `TreeNode` with
  4175. * the children from each duplicate. This is necessary because different outlets can match a
  4176. * single empty path route config and the results need to then be merged.
  4177. */
  4178. function mergeEmptyPathMatches(nodes) {
  4179. const result = [];
  4180. // The set of nodes which contain children that were merged from two duplicate empty path nodes.
  4181. const mergedNodes = new Set();
  4182. for (const node of nodes) {
  4183. if (!hasEmptyPathConfig(node)) {
  4184. result.push(node);
  4185. continue;
  4186. }
  4187. const duplicateEmptyPathNode = result.find((resultNode) => node.value.routeConfig === resultNode.value.routeConfig);
  4188. if (duplicateEmptyPathNode !== undefined) {
  4189. duplicateEmptyPathNode.children.push(...node.children);
  4190. mergedNodes.add(duplicateEmptyPathNode);
  4191. }
  4192. else {
  4193. result.push(node);
  4194. }
  4195. }
  4196. // For each node which has children from multiple sources, we need to recompute a new `TreeNode`
  4197. // by also merging those children. This is necessary when there are multiple empty path configs
  4198. // in a row. Put another way: whenever we combine children of two nodes, we need to also check
  4199. // if any of those children can be combined into a single node as well.
  4200. for (const mergedNode of mergedNodes) {
  4201. const mergedChildren = mergeEmptyPathMatches(mergedNode.children);
  4202. result.push(new TreeNode(mergedNode.value, mergedChildren));
  4203. }
  4204. return result.filter((n) => !mergedNodes.has(n));
  4205. }
  4206. function checkOutletNameUniqueness(nodes) {
  4207. const names = {};
  4208. nodes.forEach((n) => {
  4209. const routeWithSameOutletName = names[n.value.outlet];
  4210. if (routeWithSameOutletName) {
  4211. const p = routeWithSameOutletName.url.map((s) => s.toString()).join('/');
  4212. const c = n.value.url.map((s) => s.toString()).join('/');
  4213. throw new _RuntimeError(4006 /* RuntimeErrorCode.TWO_SEGMENTS_WITH_SAME_OUTLET */, (typeof ngDevMode === 'undefined' || ngDevMode) &&
  4214. `Two segments cannot have the same outlet name: '${p}' and '${c}'.`);
  4215. }
  4216. names[n.value.outlet] = n.value;
  4217. });
  4218. }
  4219. function getData(route) {
  4220. return route.data || {};
  4221. }
  4222. function getResolve(route) {
  4223. return route.resolve || {};
  4224. }
  4225. function recognize(injector, configLoader, rootComponentType, config, serializer, paramsInheritanceStrategy) {
  4226. return mergeMap((t) => recognize$1(injector, configLoader, rootComponentType, config, t.extractedUrl, serializer, paramsInheritanceStrategy).pipe(map(({ state: targetSnapshot, tree: urlAfterRedirects }) => {
  4227. return { ...t, targetSnapshot, urlAfterRedirects };
  4228. })));
  4229. }
  4230. function resolveData(paramsInheritanceStrategy, injector) {
  4231. return mergeMap((t) => {
  4232. const { targetSnapshot, guards: { canActivateChecks }, } = t;
  4233. if (!canActivateChecks.length) {
  4234. return of(t);
  4235. }
  4236. // Iterating a Set in javascript happens in insertion order so it is safe to use a `Set` to
  4237. // preserve the correct order that the resolvers should run in.
  4238. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#description
  4239. const routesWithResolversToRun = new Set(canActivateChecks.map((check) => check.route));
  4240. const routesNeedingDataUpdates = new Set();
  4241. for (const route of routesWithResolversToRun) {
  4242. if (routesNeedingDataUpdates.has(route)) {
  4243. continue;
  4244. }
  4245. // All children under the route with a resolver to run need to recompute inherited data.
  4246. for (const newRoute of flattenRouteTree(route)) {
  4247. routesNeedingDataUpdates.add(newRoute);
  4248. }
  4249. }
  4250. let routesProcessed = 0;
  4251. return from(routesNeedingDataUpdates).pipe(concatMap((route) => {
  4252. if (routesWithResolversToRun.has(route)) {
  4253. return runResolve(route, targetSnapshot, paramsInheritanceStrategy, injector);
  4254. }
  4255. else {
  4256. route.data = getInherited(route, route.parent, paramsInheritanceStrategy).resolve;
  4257. return of(void 0);
  4258. }
  4259. }), tap(() => routesProcessed++), takeLast(1), mergeMap((_) => (routesProcessed === routesNeedingDataUpdates.size ? of(t) : EMPTY)));
  4260. });
  4261. }
  4262. /**
  4263. * Returns the `ActivatedRouteSnapshot` tree as an array, using DFS to traverse the route tree.
  4264. */
  4265. function flattenRouteTree(route) {
  4266. const descendants = route.children.map((child) => flattenRouteTree(child)).flat();
  4267. return [route, ...descendants];
  4268. }
  4269. function runResolve(futureARS, futureRSS, paramsInheritanceStrategy, injector) {
  4270. const config = futureARS.routeConfig;
  4271. const resolve = futureARS._resolve;
  4272. if (config?.title !== undefined && !hasStaticTitle(config)) {
  4273. resolve[RouteTitleKey] = config.title;
  4274. }
  4275. return resolveNode(resolve, futureARS, futureRSS, injector).pipe(map((resolvedData) => {
  4276. futureARS._resolvedData = resolvedData;
  4277. futureARS.data = getInherited(futureARS, futureARS.parent, paramsInheritanceStrategy).resolve;
  4278. return null;
  4279. }));
  4280. }
  4281. function resolveNode(resolve, futureARS, futureRSS, injector) {
  4282. const keys = getDataKeys(resolve);
  4283. if (keys.length === 0) {
  4284. return of({});
  4285. }
  4286. const data = {};
  4287. return from(keys).pipe(mergeMap((key) => getResolver(resolve[key], futureARS, futureRSS, injector).pipe(first(), tap((value) => {
  4288. if (value instanceof RedirectCommand) {
  4289. throw redirectingNavigationError(new DefaultUrlSerializer(), value);
  4290. }
  4291. data[key] = value;
  4292. }))), takeLast(1), map(() => data), catchError((e) => (isEmptyError(e) ? EMPTY : throwError(e))));
  4293. }
  4294. function getResolver(injectionToken, futureARS, futureRSS, injector) {
  4295. const closestInjector = getClosestRouteInjector(futureARS) ?? injector;
  4296. const resolver = getTokenOrFunctionIdentity(injectionToken, closestInjector);
  4297. const resolverValue = resolver.resolve
  4298. ? resolver.resolve(futureARS, futureRSS)
  4299. : runInInjectionContext(closestInjector, () => resolver(futureARS, futureRSS));
  4300. return wrapIntoObservable(resolverValue);
  4301. }
  4302. /**
  4303. * Perform a side effect through a switchMap for every emission on the source Observable,
  4304. * but return an Observable that is identical to the source. It's essentially the same as
  4305. * the `tap` operator, but if the side effectful `next` function returns an ObservableInput,
  4306. * it will wait before continuing with the original value.
  4307. */
  4308. function switchTap(next) {
  4309. return switchMap((v) => {
  4310. const nextResult = next(v);
  4311. if (nextResult) {
  4312. return from(nextResult).pipe(map(() => v));
  4313. }
  4314. return of(v);
  4315. });
  4316. }
  4317. /**
  4318. * Provides a strategy for setting the page title after a router navigation.
  4319. *
  4320. * The built-in implementation traverses the router state snapshot and finds the deepest primary
  4321. * outlet with `title` property. Given the `Routes` below, navigating to
  4322. * `/base/child(popup:aux)` would result in the document title being set to "child".
  4323. * ```ts
  4324. * [
  4325. * {path: 'base', title: 'base', children: [
  4326. * {path: 'child', title: 'child'},
  4327. * ],
  4328. * {path: 'aux', outlet: 'popup', title: 'popupTitle'}
  4329. * ]
  4330. * ```
  4331. *
  4332. * This class can be used as a base class for custom title strategies. That is, you can create your
  4333. * own class that extends the `TitleStrategy`. Note that in the above example, the `title`
  4334. * from the named outlet is never used. However, a custom strategy might be implemented to
  4335. * incorporate titles in named outlets.
  4336. *
  4337. * @publicApi
  4338. * @see [Page title guide](guide/routing/common-router-tasks#setting-the-page-title)
  4339. */
  4340. class TitleStrategy {
  4341. /**
  4342. * @returns The `title` of the deepest primary route.
  4343. */
  4344. buildTitle(snapshot) {
  4345. let pageTitle;
  4346. let route = snapshot.root;
  4347. while (route !== undefined) {
  4348. pageTitle = this.getResolvedTitleForRoute(route) ?? pageTitle;
  4349. route = route.children.find((child) => child.outlet === PRIMARY_OUTLET);
  4350. }
  4351. return pageTitle;
  4352. }
  4353. /**
  4354. * Given an `ActivatedRouteSnapshot`, returns the final value of the
  4355. * `Route.title` property, which can either be a static string or a resolved value.
  4356. */
  4357. getResolvedTitleForRoute(snapshot) {
  4358. return snapshot.data[RouteTitleKey];
  4359. }
  4360. static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: TitleStrategy, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
  4361. static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: TitleStrategy, providedIn: 'root', useFactory: () => inject(DefaultTitleStrategy) });
  4362. }
  4363. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: TitleStrategy, decorators: [{
  4364. type: Injectable,
  4365. args: [{ providedIn: 'root', useFactory: () => inject(DefaultTitleStrategy) }]
  4366. }] });
  4367. /**
  4368. * The default `TitleStrategy` used by the router that updates the title using the `Title` service.
  4369. */
  4370. class DefaultTitleStrategy extends TitleStrategy {
  4371. title;
  4372. constructor(title) {
  4373. super();
  4374. this.title = title;
  4375. }
  4376. /**
  4377. * Sets the title of the browser to the given value.
  4378. *
  4379. * @param title The `pageTitle` from the deepest primary route.
  4380. */
  4381. updateTitle(snapshot) {
  4382. const title = this.buildTitle(snapshot);
  4383. if (title !== undefined) {
  4384. this.title.setTitle(title);
  4385. }
  4386. }
  4387. static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: DefaultTitleStrategy, deps: [{ token: i1.Title }], target: i0.ɵɵFactoryTarget.Injectable });
  4388. static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: DefaultTitleStrategy, providedIn: 'root' });
  4389. }
  4390. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: DefaultTitleStrategy, decorators: [{
  4391. type: Injectable,
  4392. args: [{ providedIn: 'root' }]
  4393. }], ctorParameters: () => [{ type: i1.Title }] });
  4394. /**
  4395. * A DI token for the router service.
  4396. *
  4397. * @publicApi
  4398. */
  4399. const ROUTER_CONFIGURATION = new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'router config' : '', {
  4400. providedIn: 'root',
  4401. factory: () => ({}),
  4402. });
  4403. /**
  4404. * The DI token for a router configuration.
  4405. *
  4406. * `ROUTES` is a low level API for router configuration via dependency injection.
  4407. *
  4408. * We recommend that in almost all cases to use higher level APIs such as `RouterModule.forRoot()`,
  4409. * `provideRouter`, or `Router.resetConfig()`.
  4410. *
  4411. * @publicApi
  4412. */
  4413. const ROUTES = new InjectionToken(ngDevMode ? 'ROUTES' : '');
  4414. class RouterConfigLoader {
  4415. componentLoaders = new WeakMap();
  4416. childrenLoaders = new WeakMap();
  4417. onLoadStartListener;
  4418. onLoadEndListener;
  4419. compiler = inject(Compiler);
  4420. loadComponent(route) {
  4421. if (this.componentLoaders.get(route)) {
  4422. return this.componentLoaders.get(route);
  4423. }
  4424. else if (route._loadedComponent) {
  4425. return of(route._loadedComponent);
  4426. }
  4427. if (this.onLoadStartListener) {
  4428. this.onLoadStartListener(route);
  4429. }
  4430. const loadRunner = wrapIntoObservable(route.loadComponent()).pipe(map(maybeUnwrapDefaultExport), tap((component) => {
  4431. if (this.onLoadEndListener) {
  4432. this.onLoadEndListener(route);
  4433. }
  4434. (typeof ngDevMode === 'undefined' || ngDevMode) &&
  4435. assertStandalone(route.path ?? '', component);
  4436. route._loadedComponent = component;
  4437. }), finalize(() => {
  4438. this.componentLoaders.delete(route);
  4439. }));
  4440. // Use custom ConnectableObservable as share in runners pipe increasing the bundle size too much
  4441. const loader = new ConnectableObservable(loadRunner, () => new Subject()).pipe(refCount());
  4442. this.componentLoaders.set(route, loader);
  4443. return loader;
  4444. }
  4445. loadChildren(parentInjector, route) {
  4446. if (this.childrenLoaders.get(route)) {
  4447. return this.childrenLoaders.get(route);
  4448. }
  4449. else if (route._loadedRoutes) {
  4450. return of({ routes: route._loadedRoutes, injector: route._loadedInjector });
  4451. }
  4452. if (this.onLoadStartListener) {
  4453. this.onLoadStartListener(route);
  4454. }
  4455. const moduleFactoryOrRoutes$ = loadChildren(route, this.compiler, parentInjector, this.onLoadEndListener);
  4456. const loadRunner = moduleFactoryOrRoutes$.pipe(finalize(() => {
  4457. this.childrenLoaders.delete(route);
  4458. }));
  4459. // Use custom ConnectableObservable as share in runners pipe increasing the bundle size too much
  4460. const loader = new ConnectableObservable(loadRunner, () => new Subject()).pipe(refCount());
  4461. this.childrenLoaders.set(route, loader);
  4462. return loader;
  4463. }
  4464. static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: RouterConfigLoader, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
  4465. static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: RouterConfigLoader, providedIn: 'root' });
  4466. }
  4467. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: RouterConfigLoader, decorators: [{
  4468. type: Injectable,
  4469. args: [{ providedIn: 'root' }]
  4470. }] });
  4471. /**
  4472. * Executes a `route.loadChildren` callback and converts the result to an array of child routes and
  4473. * an injector if that callback returned a module.
  4474. *
  4475. * This function is used for the route discovery during prerendering
  4476. * in @angular-devkit/build-angular. If there are any updates to the contract here, it will require
  4477. * an update to the extractor.
  4478. */
  4479. function loadChildren(route, compiler, parentInjector, onLoadEndListener) {
  4480. return wrapIntoObservable(route.loadChildren()).pipe(map(maybeUnwrapDefaultExport), mergeMap((t) => {
  4481. if (t instanceof NgModuleFactory || Array.isArray(t)) {
  4482. return of(t);
  4483. }
  4484. else {
  4485. return from(compiler.compileModuleAsync(t));
  4486. }
  4487. }), map((factoryOrRoutes) => {
  4488. if (onLoadEndListener) {
  4489. onLoadEndListener(route);
  4490. }
  4491. // This injector comes from the `NgModuleRef` when lazy loading an `NgModule`. There is
  4492. // no injector associated with lazy loading a `Route` array.
  4493. let injector;
  4494. let rawRoutes;
  4495. let requireStandaloneComponents = false;
  4496. if (Array.isArray(factoryOrRoutes)) {
  4497. rawRoutes = factoryOrRoutes;
  4498. requireStandaloneComponents = true;
  4499. }
  4500. else {
  4501. injector = factoryOrRoutes.create(parentInjector).injector;
  4502. // When loading a module that doesn't provide `RouterModule.forChild()` preloader
  4503. // will get stuck in an infinite loop. The child module's Injector will look to
  4504. // its parent `Injector` when it doesn't find any ROUTES so it will return routes
  4505. // for it's parent module instead.
  4506. rawRoutes = injector.get(ROUTES, [], { optional: true, self: true }).flat();
  4507. }
  4508. const routes = rawRoutes.map(standardizeConfig);
  4509. (typeof ngDevMode === 'undefined' || ngDevMode) &&
  4510. validateConfig(routes, route.path, requireStandaloneComponents);
  4511. return { routes, injector };
  4512. }));
  4513. }
  4514. function isWrappedDefaultExport(value) {
  4515. // We use `in` here with a string key `'default'`, because we expect `DefaultExport` objects to be
  4516. // dynamically imported ES modules with a spec-mandated `default` key. Thus we don't expect that
  4517. // `default` will be a renamed property.
  4518. return value && typeof value === 'object' && 'default' in value;
  4519. }
  4520. function maybeUnwrapDefaultExport(input) {
  4521. // As per `isWrappedDefaultExport`, the `default` key here is generated by the browser and not
  4522. // subject to property renaming, so we reference it with bracket access.
  4523. return isWrappedDefaultExport(input) ? input['default'] : input;
  4524. }
  4525. /**
  4526. * @description
  4527. *
  4528. * Provides a way to migrate AngularJS applications to Angular.
  4529. *
  4530. * @publicApi
  4531. */
  4532. class UrlHandlingStrategy {
  4533. static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: UrlHandlingStrategy, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
  4534. static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: UrlHandlingStrategy, providedIn: 'root', useFactory: () => inject(DefaultUrlHandlingStrategy) });
  4535. }
  4536. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: UrlHandlingStrategy, decorators: [{
  4537. type: Injectable,
  4538. args: [{ providedIn: 'root', useFactory: () => inject(DefaultUrlHandlingStrategy) }]
  4539. }] });
  4540. /**
  4541. * @publicApi
  4542. */
  4543. class DefaultUrlHandlingStrategy {
  4544. shouldProcessUrl(url) {
  4545. return true;
  4546. }
  4547. extract(url) {
  4548. return url;
  4549. }
  4550. merge(newUrlPart, wholeUrl) {
  4551. return newUrlPart;
  4552. }
  4553. static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: DefaultUrlHandlingStrategy, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
  4554. static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: DefaultUrlHandlingStrategy, providedIn: 'root' });
  4555. }
  4556. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: DefaultUrlHandlingStrategy, decorators: [{
  4557. type: Injectable,
  4558. args: [{ providedIn: 'root' }]
  4559. }] });
  4560. /// <reference types="dom-view-transitions" />
  4561. const CREATE_VIEW_TRANSITION = new InjectionToken(ngDevMode ? 'view transition helper' : '');
  4562. const VIEW_TRANSITION_OPTIONS = new InjectionToken(ngDevMode ? 'view transition options' : '');
  4563. /**
  4564. * A helper function for using browser view transitions. This function skips the call to
  4565. * `startViewTransition` if the browser does not support it.
  4566. *
  4567. * @returns A Promise that resolves when the view transition callback begins.
  4568. */
  4569. function createViewTransition(injector, from, to) {
  4570. const transitionOptions = injector.get(VIEW_TRANSITION_OPTIONS);
  4571. const document = injector.get(DOCUMENT);
  4572. // Create promises outside the Angular zone to avoid causing extra change detections
  4573. return injector.get(NgZone).runOutsideAngular(() => {
  4574. if (!document.startViewTransition || transitionOptions.skipNextTransition) {
  4575. transitionOptions.skipNextTransition = false;
  4576. // The timing of `startViewTransition` is closer to a macrotask. It won't be called
  4577. // until the current event loop exits so we use a promise resolved in a timeout instead
  4578. // of Promise.resolve().
  4579. return new Promise((resolve) => setTimeout(resolve));
  4580. }
  4581. let resolveViewTransitionStarted;
  4582. const viewTransitionStarted = new Promise((resolve) => {
  4583. resolveViewTransitionStarted = resolve;
  4584. });
  4585. const transition = document.startViewTransition(() => {
  4586. resolveViewTransitionStarted();
  4587. // We don't actually update dom within the transition callback. The resolving of the above
  4588. // promise unblocks the Router navigation, which synchronously activates and deactivates
  4589. // routes (the DOM update). This view transition waits for the next change detection to
  4590. // complete (below), which includes the update phase of the routed components.
  4591. return createRenderPromise(injector);
  4592. // TODO(atscott): Types in DefinitelyTyped are not up-to-date
  4593. });
  4594. const { onViewTransitionCreated } = transitionOptions;
  4595. if (onViewTransitionCreated) {
  4596. runInInjectionContext(injector, () => onViewTransitionCreated({ transition, from, to }));
  4597. }
  4598. return viewTransitionStarted;
  4599. });
  4600. }
  4601. /**
  4602. * Creates a promise that resolves after next render.
  4603. */
  4604. function createRenderPromise(injector) {
  4605. return new Promise((resolve) => {
  4606. // Wait for the microtask queue to empty after the next render happens (by waiting a macrotask).
  4607. // This ensures any follow-up renders in the microtask queue are completed before the
  4608. // view transition starts animating.
  4609. afterNextRender({ read: () => setTimeout(resolve) }, { injector });
  4610. });
  4611. }
  4612. const NAVIGATION_ERROR_HANDLER = new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'navigation error handler' : '');
  4613. class NavigationTransitions {
  4614. currentNavigation = null;
  4615. currentTransition = null;
  4616. lastSuccessfulNavigation = null;
  4617. /**
  4618. * These events are used to communicate back to the Router about the state of the transition. The
  4619. * Router wants to respond to these events in various ways. Because the `NavigationTransition`
  4620. * class is not public, this event subject is not publicly exposed.
  4621. */
  4622. events = new Subject();
  4623. /**
  4624. * Used to abort the current transition with an error.
  4625. */
  4626. transitionAbortSubject = new Subject();
  4627. configLoader = inject(RouterConfigLoader);
  4628. environmentInjector = inject(EnvironmentInjector);
  4629. destroyRef = inject(DestroyRef);
  4630. urlSerializer = inject(UrlSerializer);
  4631. rootContexts = inject(ChildrenOutletContexts);
  4632. location = inject(Location);
  4633. inputBindingEnabled = inject(INPUT_BINDER, { optional: true }) !== null;
  4634. titleStrategy = inject(TitleStrategy);
  4635. options = inject(ROUTER_CONFIGURATION, { optional: true }) || {};
  4636. paramsInheritanceStrategy = this.options.paramsInheritanceStrategy || 'emptyOnly';
  4637. urlHandlingStrategy = inject(UrlHandlingStrategy);
  4638. createViewTransition = inject(CREATE_VIEW_TRANSITION, { optional: true });
  4639. navigationErrorHandler = inject(NAVIGATION_ERROR_HANDLER, { optional: true });
  4640. navigationId = 0;
  4641. get hasRequestedNavigation() {
  4642. return this.navigationId !== 0;
  4643. }
  4644. transitions;
  4645. /**
  4646. * Hook that enables you to pause navigation after the preactivation phase.
  4647. * Used by `RouterModule`.
  4648. *
  4649. * @internal
  4650. */
  4651. afterPreactivation = () => of(void 0);
  4652. /** @internal */
  4653. rootComponentType = null;
  4654. destroyed = false;
  4655. constructor() {
  4656. const onLoadStart = (r) => this.events.next(new RouteConfigLoadStart(r));
  4657. const onLoadEnd = (r) => this.events.next(new RouteConfigLoadEnd(r));
  4658. this.configLoader.onLoadEndListener = onLoadEnd;
  4659. this.configLoader.onLoadStartListener = onLoadStart;
  4660. this.destroyRef.onDestroy(() => {
  4661. this.destroyed = true;
  4662. });
  4663. }
  4664. complete() {
  4665. this.transitions?.complete();
  4666. }
  4667. handleNavigationRequest(request) {
  4668. const id = ++this.navigationId;
  4669. this.transitions?.next({
  4670. ...request,
  4671. extractedUrl: this.urlHandlingStrategy.extract(request.rawUrl),
  4672. targetSnapshot: null,
  4673. targetRouterState: null,
  4674. guards: { canActivateChecks: [], canDeactivateChecks: [] },
  4675. guardsResult: null,
  4676. id,
  4677. });
  4678. }
  4679. setupNavigations(router) {
  4680. this.transitions = new BehaviorSubject(null);
  4681. return this.transitions.pipe(filter((t) => t !== null),
  4682. // Using switchMap so we cancel executing navigations when a new one comes in
  4683. switchMap((overallTransitionState) => {
  4684. let completed = false;
  4685. let errored = false;
  4686. return of(overallTransitionState).pipe(switchMap((t) => {
  4687. // It is possible that `switchMap` fails to cancel previous navigations if a new one happens synchronously while the operator
  4688. // is processing the `next` notification of that previous navigation. This can happen when a new navigation (say 2) cancels a
  4689. // previous one (1) and yet another navigation (3) happens synchronously in response to the `NavigationCancel` event for (1).
  4690. // https://github.com/ReactiveX/rxjs/issues/7455
  4691. if (this.navigationId > overallTransitionState.id) {
  4692. const cancellationReason = typeof ngDevMode === 'undefined' || ngDevMode
  4693. ? `Navigation ID ${overallTransitionState.id} is not equal to the current navigation id ${this.navigationId}`
  4694. : '';
  4695. this.cancelNavigationTransition(overallTransitionState, cancellationReason, NavigationCancellationCode.SupersededByNewNavigation);
  4696. return EMPTY;
  4697. }
  4698. this.currentTransition = overallTransitionState;
  4699. // Store the Navigation object
  4700. this.currentNavigation = {
  4701. id: t.id,
  4702. initialUrl: t.rawUrl,
  4703. extractedUrl: t.extractedUrl,
  4704. targetBrowserUrl: typeof t.extras.browserUrl === 'string'
  4705. ? this.urlSerializer.parse(t.extras.browserUrl)
  4706. : t.extras.browserUrl,
  4707. trigger: t.source,
  4708. extras: t.extras,
  4709. previousNavigation: !this.lastSuccessfulNavigation
  4710. ? null
  4711. : {
  4712. ...this.lastSuccessfulNavigation,
  4713. previousNavigation: null,
  4714. },
  4715. };
  4716. const urlTransition = !router.navigated || this.isUpdatingInternalState() || this.isUpdatedBrowserUrl();
  4717. const onSameUrlNavigation = t.extras.onSameUrlNavigation ?? router.onSameUrlNavigation;
  4718. if (!urlTransition && onSameUrlNavigation !== 'reload') {
  4719. const reason = typeof ngDevMode === 'undefined' || ngDevMode
  4720. ? `Navigation to ${t.rawUrl} was ignored because it is the same as the current Router URL.`
  4721. : '';
  4722. this.events.next(new NavigationSkipped(t.id, this.urlSerializer.serialize(t.rawUrl), reason, NavigationSkippedCode.IgnoredSameUrlNavigation));
  4723. t.resolve(false);
  4724. return EMPTY;
  4725. }
  4726. if (this.urlHandlingStrategy.shouldProcessUrl(t.rawUrl)) {
  4727. return of(t).pipe(
  4728. // Fire NavigationStart event
  4729. switchMap((t) => {
  4730. this.events.next(new NavigationStart(t.id, this.urlSerializer.serialize(t.extractedUrl), t.source, t.restoredState));
  4731. if (t.id !== this.navigationId) {
  4732. return EMPTY;
  4733. }
  4734. // This delay is required to match old behavior that forced
  4735. // navigation to always be async
  4736. return Promise.resolve(t);
  4737. }),
  4738. // Recognize
  4739. recognize(this.environmentInjector, this.configLoader, this.rootComponentType, router.config, this.urlSerializer, this.paramsInheritanceStrategy),
  4740. // Update URL if in `eager` update mode
  4741. tap((t) => {
  4742. overallTransitionState.targetSnapshot = t.targetSnapshot;
  4743. overallTransitionState.urlAfterRedirects = t.urlAfterRedirects;
  4744. this.currentNavigation = {
  4745. ...this.currentNavigation,
  4746. finalUrl: t.urlAfterRedirects,
  4747. };
  4748. // Fire RoutesRecognized
  4749. const routesRecognized = new RoutesRecognized(t.id, this.urlSerializer.serialize(t.extractedUrl), this.urlSerializer.serialize(t.urlAfterRedirects), t.targetSnapshot);
  4750. this.events.next(routesRecognized);
  4751. }));
  4752. }
  4753. else if (urlTransition &&
  4754. this.urlHandlingStrategy.shouldProcessUrl(t.currentRawUrl)) {
  4755. /* When the current URL shouldn't be processed, but the previous one
  4756. * was, we handle this "error condition" by navigating to the
  4757. * previously successful URL, but leaving the URL intact.*/
  4758. const { id, extractedUrl, source, restoredState, extras } = t;
  4759. const navStart = new NavigationStart(id, this.urlSerializer.serialize(extractedUrl), source, restoredState);
  4760. this.events.next(navStart);
  4761. const targetSnapshot = createEmptyState(this.rootComponentType).snapshot;
  4762. this.currentTransition = overallTransitionState = {
  4763. ...t,
  4764. targetSnapshot,
  4765. urlAfterRedirects: extractedUrl,
  4766. extras: { ...extras, skipLocationChange: false, replaceUrl: false },
  4767. };
  4768. this.currentNavigation.finalUrl = extractedUrl;
  4769. return of(overallTransitionState);
  4770. }
  4771. else {
  4772. /* When neither the current or previous URL can be processed, do
  4773. * nothing other than update router's internal reference to the
  4774. * current "settled" URL. This way the next navigation will be coming
  4775. * from the current URL in the browser.
  4776. */
  4777. const reason = typeof ngDevMode === 'undefined' || ngDevMode
  4778. ? `Navigation was ignored because the UrlHandlingStrategy` +
  4779. ` indicated neither the current URL ${t.currentRawUrl} nor target URL ${t.rawUrl} should be processed.`
  4780. : '';
  4781. this.events.next(new NavigationSkipped(t.id, this.urlSerializer.serialize(t.extractedUrl), reason, NavigationSkippedCode.IgnoredByUrlHandlingStrategy));
  4782. t.resolve(false);
  4783. return EMPTY;
  4784. }
  4785. }),
  4786. // --- GUARDS ---
  4787. tap((t) => {
  4788. const guardsStart = new GuardsCheckStart(t.id, this.urlSerializer.serialize(t.extractedUrl), this.urlSerializer.serialize(t.urlAfterRedirects), t.targetSnapshot);
  4789. this.events.next(guardsStart);
  4790. }), map((t) => {
  4791. this.currentTransition = overallTransitionState = {
  4792. ...t,
  4793. guards: getAllRouteGuards(t.targetSnapshot, t.currentSnapshot, this.rootContexts),
  4794. };
  4795. return overallTransitionState;
  4796. }), checkGuards(this.environmentInjector, (evt) => this.events.next(evt)), tap((t) => {
  4797. overallTransitionState.guardsResult = t.guardsResult;
  4798. if (t.guardsResult && typeof t.guardsResult !== 'boolean') {
  4799. throw redirectingNavigationError(this.urlSerializer, t.guardsResult);
  4800. }
  4801. const guardsEnd = new GuardsCheckEnd(t.id, this.urlSerializer.serialize(t.extractedUrl), this.urlSerializer.serialize(t.urlAfterRedirects), t.targetSnapshot, !!t.guardsResult);
  4802. this.events.next(guardsEnd);
  4803. }), filter((t) => {
  4804. if (!t.guardsResult) {
  4805. this.cancelNavigationTransition(t, '', NavigationCancellationCode.GuardRejected);
  4806. return false;
  4807. }
  4808. return true;
  4809. }),
  4810. // --- RESOLVE ---
  4811. switchTap((t) => {
  4812. if (t.guards.canActivateChecks.length === 0) {
  4813. return undefined;
  4814. }
  4815. return of(t).pipe(tap((t) => {
  4816. const resolveStart = new ResolveStart(t.id, this.urlSerializer.serialize(t.extractedUrl), this.urlSerializer.serialize(t.urlAfterRedirects), t.targetSnapshot);
  4817. this.events.next(resolveStart);
  4818. }), switchMap((t) => {
  4819. let dataResolved = false;
  4820. return of(t).pipe(resolveData(this.paramsInheritanceStrategy, this.environmentInjector), tap({
  4821. next: () => (dataResolved = true),
  4822. complete: () => {
  4823. if (!dataResolved) {
  4824. this.cancelNavigationTransition(t, typeof ngDevMode === 'undefined' || ngDevMode
  4825. ? `At least one route resolver didn't emit any value.`
  4826. : '', NavigationCancellationCode.NoDataFromResolver);
  4827. }
  4828. },
  4829. }));
  4830. }), tap((t) => {
  4831. const resolveEnd = new ResolveEnd(t.id, this.urlSerializer.serialize(t.extractedUrl), this.urlSerializer.serialize(t.urlAfterRedirects), t.targetSnapshot);
  4832. this.events.next(resolveEnd);
  4833. }));
  4834. }),
  4835. // --- LOAD COMPONENTS ---
  4836. switchTap((t) => {
  4837. const loadComponents = (route) => {
  4838. const loaders = [];
  4839. if (route.routeConfig?.loadComponent && !route.routeConfig._loadedComponent) {
  4840. loaders.push(this.configLoader.loadComponent(route.routeConfig).pipe(tap((loadedComponent) => {
  4841. route.component = loadedComponent;
  4842. }), map(() => void 0)));
  4843. }
  4844. for (const child of route.children) {
  4845. loaders.push(...loadComponents(child));
  4846. }
  4847. return loaders;
  4848. };
  4849. return combineLatest(loadComponents(t.targetSnapshot.root)).pipe(defaultIfEmpty(null), take(1));
  4850. }), switchTap(() => this.afterPreactivation()), switchMap(() => {
  4851. const { currentSnapshot, targetSnapshot } = overallTransitionState;
  4852. const viewTransitionStarted = this.createViewTransition?.(this.environmentInjector, currentSnapshot.root, targetSnapshot.root);
  4853. // If view transitions are enabled, block the navigation until the view
  4854. // transition callback starts. Otherwise, continue immediately.
  4855. return viewTransitionStarted
  4856. ? from(viewTransitionStarted).pipe(map(() => overallTransitionState))
  4857. : of(overallTransitionState);
  4858. }), map((t) => {
  4859. const targetRouterState = createRouterState(router.routeReuseStrategy, t.targetSnapshot, t.currentRouterState);
  4860. this.currentTransition = overallTransitionState = { ...t, targetRouterState };
  4861. this.currentNavigation.targetRouterState = targetRouterState;
  4862. return overallTransitionState;
  4863. }), tap(() => {
  4864. this.events.next(new BeforeActivateRoutes());
  4865. }), activateRoutes(this.rootContexts, router.routeReuseStrategy, (evt) => this.events.next(evt), this.inputBindingEnabled),
  4866. // Ensure that if some observable used to drive the transition doesn't
  4867. // complete, the navigation still finalizes This should never happen, but
  4868. // this is done as a safety measure to avoid surfacing this error (#49567).
  4869. take(1), tap({
  4870. next: (t) => {
  4871. completed = true;
  4872. this.lastSuccessfulNavigation = this.currentNavigation;
  4873. this.events.next(new NavigationEnd(t.id, this.urlSerializer.serialize(t.extractedUrl), this.urlSerializer.serialize(t.urlAfterRedirects)));
  4874. this.titleStrategy?.updateTitle(t.targetRouterState.snapshot);
  4875. t.resolve(true);
  4876. },
  4877. complete: () => {
  4878. completed = true;
  4879. },
  4880. }),
  4881. // There used to be a lot more logic happening directly within the
  4882. // transition Observable. Some of this logic has been refactored out to
  4883. // other places but there may still be errors that happen there. This gives
  4884. // us a way to cancel the transition from the outside. This may also be
  4885. // required in the future to support something like the abort signal of the
  4886. // Navigation API where the navigation gets aborted from outside the
  4887. // transition.
  4888. takeUntil(this.transitionAbortSubject.pipe(tap((err) => {
  4889. throw err;
  4890. }))), finalize(() => {
  4891. /* When the navigation stream finishes either through error or success,
  4892. * we set the `completed` or `errored` flag. However, there are some
  4893. * situations where we could get here without either of those being set.
  4894. * For instance, a redirect during NavigationStart. Therefore, this is a
  4895. * catch-all to make sure the NavigationCancel event is fired when a
  4896. * navigation gets cancelled but not caught by other means. */
  4897. if (!completed && !errored) {
  4898. const cancelationReason = typeof ngDevMode === 'undefined' || ngDevMode
  4899. ? `Navigation ID ${overallTransitionState.id} is not equal to the current navigation id ${this.navigationId}`
  4900. : '';
  4901. this.cancelNavigationTransition(overallTransitionState, cancelationReason, NavigationCancellationCode.SupersededByNewNavigation);
  4902. }
  4903. // Only clear current navigation if it is still set to the one that
  4904. // finalized.
  4905. if (this.currentTransition?.id === overallTransitionState.id) {
  4906. this.currentNavigation = null;
  4907. this.currentTransition = null;
  4908. }
  4909. }), catchError((e) => {
  4910. // If the application is already destroyed, the catch block should not
  4911. // execute anything in practice because other resources have already
  4912. // been released and destroyed.
  4913. if (this.destroyed) {
  4914. overallTransitionState.resolve(false);
  4915. return EMPTY;
  4916. }
  4917. errored = true;
  4918. /* This error type is issued during Redirect, and is handled as a
  4919. * cancellation rather than an error. */
  4920. if (isNavigationCancelingError(e)) {
  4921. this.events.next(new NavigationCancel(overallTransitionState.id, this.urlSerializer.serialize(overallTransitionState.extractedUrl), e.message, e.cancellationCode));
  4922. // When redirecting, we need to delay resolving the navigation
  4923. // promise and push it to the redirect navigation
  4924. if (!isRedirectingNavigationCancelingError(e)) {
  4925. overallTransitionState.resolve(false);
  4926. }
  4927. else {
  4928. this.events.next(new RedirectRequest(e.url, e.navigationBehaviorOptions));
  4929. }
  4930. /* All other errors should reset to the router's internal URL reference
  4931. * to the pre-error state. */
  4932. }
  4933. else {
  4934. const navigationError = new NavigationError(overallTransitionState.id, this.urlSerializer.serialize(overallTransitionState.extractedUrl), e, overallTransitionState.targetSnapshot ?? undefined);
  4935. try {
  4936. const navigationErrorHandlerResult = runInInjectionContext(this.environmentInjector, () => this.navigationErrorHandler?.(navigationError));
  4937. if (navigationErrorHandlerResult instanceof RedirectCommand) {
  4938. const { message, cancellationCode } = redirectingNavigationError(this.urlSerializer, navigationErrorHandlerResult);
  4939. this.events.next(new NavigationCancel(overallTransitionState.id, this.urlSerializer.serialize(overallTransitionState.extractedUrl), message, cancellationCode));
  4940. this.events.next(new RedirectRequest(navigationErrorHandlerResult.redirectTo, navigationErrorHandlerResult.navigationBehaviorOptions));
  4941. }
  4942. else {
  4943. this.events.next(navigationError);
  4944. throw e;
  4945. }
  4946. }
  4947. catch (ee) {
  4948. // TODO(atscott): consider flipping the default behavior of
  4949. // resolveNavigationPromiseOnError to be `resolve(false)` when
  4950. // undefined. This is the most sane thing to do given that
  4951. // applications very rarely handle the promise rejection and, as a
  4952. // result, would get "unhandled promise rejection" console logs.
  4953. // The vast majority of applications would not be affected by this
  4954. // change so omitting a migration seems reasonable. Instead,
  4955. // applications that rely on rejection can specifically opt-in to the
  4956. // old behavior.
  4957. if (this.options.resolveNavigationPromiseOnError) {
  4958. overallTransitionState.resolve(false);
  4959. }
  4960. else {
  4961. overallTransitionState.reject(ee);
  4962. }
  4963. }
  4964. }
  4965. return EMPTY;
  4966. }));
  4967. // casting because `pipe` returns observable({}) when called with 8+ arguments
  4968. }));
  4969. }
  4970. cancelNavigationTransition(t, reason, code) {
  4971. const navCancel = new NavigationCancel(t.id, this.urlSerializer.serialize(t.extractedUrl), reason, code);
  4972. this.events.next(navCancel);
  4973. t.resolve(false);
  4974. }
  4975. /**
  4976. * @returns Whether we're navigating to somewhere that is not what the Router is
  4977. * currently set to.
  4978. */
  4979. isUpdatingInternalState() {
  4980. // TODO(atscott): The serializer should likely be used instead of
  4981. // `UrlTree.toString()`. Custom serializers are often written to handle
  4982. // things better than the default one (objects, for example will be
  4983. // [Object object] with the custom serializer and be "the same" when they
  4984. // aren't).
  4985. // (Same for isUpdatedBrowserUrl)
  4986. return (this.currentTransition?.extractedUrl.toString() !==
  4987. this.currentTransition?.currentUrlTree.toString());
  4988. }
  4989. /**
  4990. * @returns Whether we're updating the browser URL to something new (navigation is going
  4991. * to somewhere not displayed in the URL bar and we will update the URL
  4992. * bar if navigation succeeds).
  4993. */
  4994. isUpdatedBrowserUrl() {
  4995. // The extracted URL is the part of the URL that this application cares about. `extract` may
  4996. // return only part of the browser URL and that part may have not changed even if some other
  4997. // portion of the URL did.
  4998. const currentBrowserUrl = this.urlHandlingStrategy.extract(this.urlSerializer.parse(this.location.path(true)));
  4999. const targetBrowserUrl = this.currentNavigation?.targetBrowserUrl ?? this.currentNavigation?.extractedUrl;
  5000. return (currentBrowserUrl.toString() !== targetBrowserUrl?.toString() &&
  5001. !this.currentNavigation?.extras.skipLocationChange);
  5002. }
  5003. static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: NavigationTransitions, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
  5004. static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: NavigationTransitions, providedIn: 'root' });
  5005. }
  5006. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: NavigationTransitions, decorators: [{
  5007. type: Injectable,
  5008. args: [{ providedIn: 'root' }]
  5009. }], ctorParameters: () => [] });
  5010. function isBrowserTriggeredNavigation(source) {
  5011. return source !== IMPERATIVE_NAVIGATION;
  5012. }
  5013. /**
  5014. * @description
  5015. *
  5016. * Provides a way to customize when activated routes get reused.
  5017. *
  5018. * @publicApi
  5019. */
  5020. class RouteReuseStrategy {
  5021. static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: RouteReuseStrategy, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
  5022. static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: RouteReuseStrategy, providedIn: 'root', useFactory: () => inject(DefaultRouteReuseStrategy) });
  5023. }
  5024. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: RouteReuseStrategy, decorators: [{
  5025. type: Injectable,
  5026. args: [{ providedIn: 'root', useFactory: () => inject(DefaultRouteReuseStrategy) }]
  5027. }] });
  5028. /**
  5029. * @description
  5030. *
  5031. * This base route reuse strategy only reuses routes when the matched router configs are
  5032. * identical. This prevents components from being destroyed and recreated
  5033. * when just the route parameters, query parameters or fragment change
  5034. * (that is, the existing component is _reused_).
  5035. *
  5036. * This strategy does not store any routes for later reuse.
  5037. *
  5038. * Angular uses this strategy by default.
  5039. *
  5040. *
  5041. * It can be used as a base class for custom route reuse strategies, i.e. you can create your own
  5042. * class that extends the `BaseRouteReuseStrategy` one.
  5043. * @publicApi
  5044. */
  5045. class BaseRouteReuseStrategy {
  5046. /**
  5047. * Whether the given route should detach for later reuse.
  5048. * Always returns false for `BaseRouteReuseStrategy`.
  5049. * */
  5050. shouldDetach(route) {
  5051. return false;
  5052. }
  5053. /**
  5054. * A no-op; the route is never stored since this strategy never detaches routes for later re-use.
  5055. */
  5056. store(route, detachedTree) { }
  5057. /** Returns `false`, meaning the route (and its subtree) is never reattached */
  5058. shouldAttach(route) {
  5059. return false;
  5060. }
  5061. /** Returns `null` because this strategy does not store routes for later re-use. */
  5062. retrieve(route) {
  5063. return null;
  5064. }
  5065. /**
  5066. * Determines if a route should be reused.
  5067. * This strategy returns `true` when the future route config and current route config are
  5068. * identical.
  5069. */
  5070. shouldReuseRoute(future, curr) {
  5071. return future.routeConfig === curr.routeConfig;
  5072. }
  5073. }
  5074. class DefaultRouteReuseStrategy extends BaseRouteReuseStrategy {
  5075. static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: DefaultRouteReuseStrategy, deps: null, target: i0.ɵɵFactoryTarget.Injectable });
  5076. static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: DefaultRouteReuseStrategy, providedIn: 'root' });
  5077. }
  5078. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: DefaultRouteReuseStrategy, decorators: [{
  5079. type: Injectable,
  5080. args: [{ providedIn: 'root' }]
  5081. }] });
  5082. class StateManager {
  5083. urlSerializer = inject(UrlSerializer);
  5084. options = inject(ROUTER_CONFIGURATION, { optional: true }) || {};
  5085. canceledNavigationResolution = this.options.canceledNavigationResolution || 'replace';
  5086. location = inject(Location);
  5087. urlHandlingStrategy = inject(UrlHandlingStrategy);
  5088. urlUpdateStrategy = this.options.urlUpdateStrategy || 'deferred';
  5089. currentUrlTree = new UrlTree();
  5090. /**
  5091. * Returns the currently activated `UrlTree`.
  5092. *
  5093. * This `UrlTree` shows only URLs that the `Router` is configured to handle (through
  5094. * `UrlHandlingStrategy`).
  5095. *
  5096. * The value is set after finding the route config tree to activate but before activating the
  5097. * route.
  5098. */
  5099. getCurrentUrlTree() {
  5100. return this.currentUrlTree;
  5101. }
  5102. rawUrlTree = this.currentUrlTree;
  5103. /**
  5104. * Returns a `UrlTree` that is represents what the browser is actually showing.
  5105. *
  5106. * In the life of a navigation transition:
  5107. * 1. When a navigation begins, the raw `UrlTree` is updated to the full URL that's being
  5108. * navigated to.
  5109. * 2. During a navigation, redirects are applied, which might only apply to _part_ of the URL (due
  5110. * to `UrlHandlingStrategy`).
  5111. * 3. Just before activation, the raw `UrlTree` is updated to include the redirects on top of the
  5112. * original raw URL.
  5113. *
  5114. * Note that this is _only_ here to support `UrlHandlingStrategy.extract` and
  5115. * `UrlHandlingStrategy.shouldProcessUrl`. Without those APIs, the current `UrlTree` would not
  5116. * deviated from the raw `UrlTree`.
  5117. *
  5118. * For `extract`, a raw `UrlTree` is needed because `extract` may only return part
  5119. * of the navigation URL. Thus, the current `UrlTree` may only represent _part_ of the browser
  5120. * URL. When a navigation gets cancelled and the router needs to reset the URL or a new navigation
  5121. * occurs, it needs to know the _whole_ browser URL, not just the part handled by
  5122. * `UrlHandlingStrategy`.
  5123. * For `shouldProcessUrl`, when the return is `false`, the router ignores the navigation but
  5124. * still updates the raw `UrlTree` with the assumption that the navigation was caused by the
  5125. * location change listener due to a URL update by the AngularJS router. In this case, the router
  5126. * still need to know what the browser's URL is for future navigations.
  5127. */
  5128. getRawUrlTree() {
  5129. return this.rawUrlTree;
  5130. }
  5131. createBrowserPath({ finalUrl, initialUrl, targetBrowserUrl }) {
  5132. const rawUrl = finalUrl !== undefined ? this.urlHandlingStrategy.merge(finalUrl, initialUrl) : initialUrl;
  5133. const url = targetBrowserUrl ?? rawUrl;
  5134. const path = url instanceof UrlTree ? this.urlSerializer.serialize(url) : url;
  5135. return path;
  5136. }
  5137. commitTransition({ targetRouterState, finalUrl, initialUrl }) {
  5138. // If we are committing the transition after having a final URL and target state, we're updating
  5139. // all pieces of the state. Otherwise, we likely skipped the transition (due to URL handling strategy)
  5140. // and only want to update the rawUrlTree, which represents the browser URL (and doesn't necessarily match router state).
  5141. if (finalUrl && targetRouterState) {
  5142. this.currentUrlTree = finalUrl;
  5143. this.rawUrlTree = this.urlHandlingStrategy.merge(finalUrl, initialUrl);
  5144. this.routerState = targetRouterState;
  5145. }
  5146. else {
  5147. this.rawUrlTree = initialUrl;
  5148. }
  5149. }
  5150. routerState = createEmptyState(null);
  5151. /** Returns the current RouterState. */
  5152. getRouterState() {
  5153. return this.routerState;
  5154. }
  5155. stateMemento = this.createStateMemento();
  5156. updateStateMemento() {
  5157. this.stateMemento = this.createStateMemento();
  5158. }
  5159. createStateMemento() {
  5160. return {
  5161. rawUrlTree: this.rawUrlTree,
  5162. currentUrlTree: this.currentUrlTree,
  5163. routerState: this.routerState,
  5164. };
  5165. }
  5166. resetInternalState({ finalUrl }) {
  5167. this.routerState = this.stateMemento.routerState;
  5168. this.currentUrlTree = this.stateMemento.currentUrlTree;
  5169. // Note here that we use the urlHandlingStrategy to get the reset `rawUrlTree` because it may be
  5170. // configured to handle only part of the navigation URL. This means we would only want to reset
  5171. // the part of the navigation handled by the Angular router rather than the whole URL. In
  5172. // addition, the URLHandlingStrategy may be configured to specifically preserve parts of the URL
  5173. // when merging, such as the query params so they are not lost on a refresh.
  5174. this.rawUrlTree = this.urlHandlingStrategy.merge(this.currentUrlTree, finalUrl ?? this.rawUrlTree);
  5175. }
  5176. static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: StateManager, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
  5177. static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: StateManager, providedIn: 'root', useFactory: () => inject(HistoryStateManager) });
  5178. }
  5179. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: StateManager, decorators: [{
  5180. type: Injectable,
  5181. args: [{ providedIn: 'root', useFactory: () => inject(HistoryStateManager) }]
  5182. }] });
  5183. class HistoryStateManager extends StateManager {
  5184. /**
  5185. * The id of the currently active page in the router.
  5186. * Updated to the transition's target id on a successful navigation.
  5187. *
  5188. * This is used to track what page the router last activated. When an attempted navigation fails,
  5189. * the router can then use this to compute how to restore the state back to the previously active
  5190. * page.
  5191. */
  5192. currentPageId = 0;
  5193. lastSuccessfulId = -1;
  5194. restoredState() {
  5195. return this.location.getState();
  5196. }
  5197. /**
  5198. * The ɵrouterPageId of whatever page is currently active in the browser history. This is
  5199. * important for computing the target page id for new navigations because we need to ensure each
  5200. * page id in the browser history is 1 more than the previous entry.
  5201. */
  5202. get browserPageId() {
  5203. if (this.canceledNavigationResolution !== 'computed') {
  5204. return this.currentPageId;
  5205. }
  5206. return this.restoredState()?.ɵrouterPageId ?? this.currentPageId;
  5207. }
  5208. registerNonRouterCurrentEntryChangeListener(listener) {
  5209. return this.location.subscribe((event) => {
  5210. if (event['type'] === 'popstate') {
  5211. // The `setTimeout` was added in #12160 and is likely to support Angular/AngularJS
  5212. // hybrid apps.
  5213. setTimeout(() => {
  5214. listener(event['url'], event.state, 'popstate');
  5215. });
  5216. }
  5217. });
  5218. }
  5219. handleRouterEvent(e, currentTransition) {
  5220. if (e instanceof NavigationStart) {
  5221. this.updateStateMemento();
  5222. }
  5223. else if (e instanceof NavigationSkipped) {
  5224. this.commitTransition(currentTransition);
  5225. }
  5226. else if (e instanceof RoutesRecognized) {
  5227. if (this.urlUpdateStrategy === 'eager') {
  5228. if (!currentTransition.extras.skipLocationChange) {
  5229. this.setBrowserUrl(this.createBrowserPath(currentTransition), currentTransition);
  5230. }
  5231. }
  5232. }
  5233. else if (e instanceof BeforeActivateRoutes) {
  5234. this.commitTransition(currentTransition);
  5235. if (this.urlUpdateStrategy === 'deferred' && !currentTransition.extras.skipLocationChange) {
  5236. this.setBrowserUrl(this.createBrowserPath(currentTransition), currentTransition);
  5237. }
  5238. }
  5239. else if (e instanceof NavigationCancel &&
  5240. (e.code === NavigationCancellationCode.GuardRejected ||
  5241. e.code === NavigationCancellationCode.NoDataFromResolver)) {
  5242. this.restoreHistory(currentTransition);
  5243. }
  5244. else if (e instanceof NavigationError) {
  5245. this.restoreHistory(currentTransition, true);
  5246. }
  5247. else if (e instanceof NavigationEnd) {
  5248. this.lastSuccessfulId = e.id;
  5249. this.currentPageId = this.browserPageId;
  5250. }
  5251. }
  5252. setBrowserUrl(path, { extras, id }) {
  5253. const { replaceUrl, state } = extras;
  5254. if (this.location.isCurrentPathEqualTo(path) || !!replaceUrl) {
  5255. // replacements do not update the target page
  5256. const currentBrowserPageId = this.browserPageId;
  5257. const newState = {
  5258. ...state,
  5259. ...this.generateNgRouterState(id, currentBrowserPageId),
  5260. };
  5261. this.location.replaceState(path, '', newState);
  5262. }
  5263. else {
  5264. const newState = {
  5265. ...state,
  5266. ...this.generateNgRouterState(id, this.browserPageId + 1),
  5267. };
  5268. this.location.go(path, '', newState);
  5269. }
  5270. }
  5271. /**
  5272. * Performs the necessary rollback action to restore the browser URL to the
  5273. * state before the transition.
  5274. */
  5275. restoreHistory(navigation, restoringFromCaughtError = false) {
  5276. if (this.canceledNavigationResolution === 'computed') {
  5277. const currentBrowserPageId = this.browserPageId;
  5278. const targetPagePosition = this.currentPageId - currentBrowserPageId;
  5279. if (targetPagePosition !== 0) {
  5280. this.location.historyGo(targetPagePosition);
  5281. }
  5282. else if (this.getCurrentUrlTree() === navigation.finalUrl && targetPagePosition === 0) {
  5283. // We got to the activation stage (where currentUrlTree is set to the navigation's
  5284. // finalUrl), but we weren't moving anywhere in history (skipLocationChange or replaceUrl).
  5285. // We still need to reset the router state back to what it was when the navigation started.
  5286. this.resetInternalState(navigation);
  5287. this.resetUrlToCurrentUrlTree();
  5288. }
  5289. else ;
  5290. }
  5291. else if (this.canceledNavigationResolution === 'replace') {
  5292. // TODO(atscott): It seems like we should _always_ reset the state here. It would be a no-op
  5293. // for `deferred` navigations that haven't change the internal state yet because guards
  5294. // reject. For 'eager' navigations, it seems like we also really should reset the state
  5295. // because the navigation was cancelled. Investigate if this can be done by running TGP.
  5296. if (restoringFromCaughtError) {
  5297. this.resetInternalState(navigation);
  5298. }
  5299. this.resetUrlToCurrentUrlTree();
  5300. }
  5301. }
  5302. resetUrlToCurrentUrlTree() {
  5303. this.location.replaceState(this.urlSerializer.serialize(this.getRawUrlTree()), '', this.generateNgRouterState(this.lastSuccessfulId, this.currentPageId));
  5304. }
  5305. generateNgRouterState(navigationId, routerPageId) {
  5306. if (this.canceledNavigationResolution === 'computed') {
  5307. return { navigationId, ɵrouterPageId: routerPageId };
  5308. }
  5309. return { navigationId };
  5310. }
  5311. static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: HistoryStateManager, deps: null, target: i0.ɵɵFactoryTarget.Injectable });
  5312. static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: HistoryStateManager, providedIn: 'root' });
  5313. }
  5314. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: HistoryStateManager, decorators: [{
  5315. type: Injectable,
  5316. args: [{ providedIn: 'root' }]
  5317. }] });
  5318. /**
  5319. * Performs the given action once the router finishes its next/current navigation.
  5320. *
  5321. * The navigation is considered complete under the following conditions:
  5322. * - `NavigationCancel` event emits and the code is not `NavigationCancellationCode.Redirect` or
  5323. * `NavigationCancellationCode.SupersededByNewNavigation`. In these cases, the
  5324. * redirecting/superseding navigation must finish.
  5325. * - `NavigationError`, `NavigationEnd`, or `NavigationSkipped` event emits
  5326. */
  5327. function afterNextNavigation(router, action) {
  5328. router.events
  5329. .pipe(filter((e) => e instanceof NavigationEnd ||
  5330. e instanceof NavigationCancel ||
  5331. e instanceof NavigationError ||
  5332. e instanceof NavigationSkipped), map((e) => {
  5333. if (e instanceof NavigationEnd || e instanceof NavigationSkipped) {
  5334. return 0 /* NavigationResult.COMPLETE */;
  5335. }
  5336. const redirecting = e instanceof NavigationCancel
  5337. ? e.code === NavigationCancellationCode.Redirect ||
  5338. e.code === NavigationCancellationCode.SupersededByNewNavigation
  5339. : false;
  5340. return redirecting ? 2 /* NavigationResult.REDIRECTING */ : 1 /* NavigationResult.FAILED */;
  5341. }), filter((result) => result !== 2 /* NavigationResult.REDIRECTING */), take(1))
  5342. .subscribe(() => {
  5343. action();
  5344. });
  5345. }
  5346. /**
  5347. * The equivalent `IsActiveMatchOptions` options for `Router.isActive` is called with `true`
  5348. * (exact = true).
  5349. */
  5350. const exactMatchOptions = {
  5351. paths: 'exact',
  5352. fragment: 'ignored',
  5353. matrixParams: 'ignored',
  5354. queryParams: 'exact',
  5355. };
  5356. /**
  5357. * The equivalent `IsActiveMatchOptions` options for `Router.isActive` is called with `false`
  5358. * (exact = false).
  5359. */
  5360. const subsetMatchOptions = {
  5361. paths: 'subset',
  5362. fragment: 'ignored',
  5363. matrixParams: 'ignored',
  5364. queryParams: 'subset',
  5365. };
  5366. /**
  5367. * @description
  5368. *
  5369. * A service that facilitates navigation among views and URL manipulation capabilities.
  5370. * This service is provided in the root scope and configured with [provideRouter](api/router/provideRouter).
  5371. *
  5372. * @see {@link Route}
  5373. * @see {@link provideRouter}
  5374. * @see [Routing and Navigation Guide](guide/routing/common-router-tasks).
  5375. *
  5376. * @ngModule RouterModule
  5377. *
  5378. * @publicApi
  5379. */
  5380. class Router {
  5381. get currentUrlTree() {
  5382. return this.stateManager.getCurrentUrlTree();
  5383. }
  5384. get rawUrlTree() {
  5385. return this.stateManager.getRawUrlTree();
  5386. }
  5387. disposed = false;
  5388. nonRouterCurrentEntryChangeSubscription;
  5389. console = inject(_Console);
  5390. stateManager = inject(StateManager);
  5391. options = inject(ROUTER_CONFIGURATION, { optional: true }) || {};
  5392. pendingTasks = inject(_PendingTasksInternal);
  5393. urlUpdateStrategy = this.options.urlUpdateStrategy || 'deferred';
  5394. navigationTransitions = inject(NavigationTransitions);
  5395. urlSerializer = inject(UrlSerializer);
  5396. location = inject(Location);
  5397. urlHandlingStrategy = inject(UrlHandlingStrategy);
  5398. /**
  5399. * The private `Subject` type for the public events exposed in the getter. This is used internally
  5400. * to push events to. The separate field allows us to expose separate types in the public API
  5401. * (i.e., an Observable rather than the Subject).
  5402. */
  5403. _events = new Subject();
  5404. /**
  5405. * An event stream for routing events.
  5406. */
  5407. get events() {
  5408. // TODO(atscott): This _should_ be events.asObservable(). However, this change requires internal
  5409. // cleanup: tests are doing `(route.events as Subject<Event>).next(...)`. This isn't
  5410. // allowed/supported but we still have to fix these or file bugs against the teams before making
  5411. // the change.
  5412. return this._events;
  5413. }
  5414. /**
  5415. * The current state of routing in this NgModule.
  5416. */
  5417. get routerState() {
  5418. return this.stateManager.getRouterState();
  5419. }
  5420. /**
  5421. * True if at least one navigation event has occurred,
  5422. * false otherwise.
  5423. */
  5424. navigated = false;
  5425. /**
  5426. * A strategy for re-using routes.
  5427. *
  5428. * @deprecated Configure using `providers` instead:
  5429. * `{provide: RouteReuseStrategy, useClass: MyStrategy}`.
  5430. */
  5431. routeReuseStrategy = inject(RouteReuseStrategy);
  5432. /**
  5433. * How to handle a navigation request to the current URL.
  5434. *
  5435. *
  5436. * @deprecated Configure this through `provideRouter` or `RouterModule.forRoot` instead.
  5437. * @see {@link withRouterConfig}
  5438. * @see {@link provideRouter}
  5439. * @see {@link RouterModule}
  5440. */
  5441. onSameUrlNavigation = this.options.onSameUrlNavigation || 'ignore';
  5442. config = inject(ROUTES, { optional: true })?.flat() ?? [];
  5443. /**
  5444. * Indicates whether the application has opted in to binding Router data to component inputs.
  5445. *
  5446. * This option is enabled by the `withComponentInputBinding` feature of `provideRouter` or
  5447. * `bindToComponentInputs` in the `ExtraOptions` of `RouterModule.forRoot`.
  5448. */
  5449. componentInputBindingEnabled = !!inject(INPUT_BINDER, { optional: true });
  5450. constructor() {
  5451. this.resetConfig(this.config);
  5452. this.navigationTransitions.setupNavigations(this).subscribe({
  5453. error: (e) => {
  5454. this.console.warn(ngDevMode ? `Unhandled Navigation Error: ${e}` : e);
  5455. },
  5456. });
  5457. this.subscribeToNavigationEvents();
  5458. }
  5459. eventsSubscription = new Subscription();
  5460. subscribeToNavigationEvents() {
  5461. const subscription = this.navigationTransitions.events.subscribe((e) => {
  5462. try {
  5463. const currentTransition = this.navigationTransitions.currentTransition;
  5464. const currentNavigation = this.navigationTransitions.currentNavigation;
  5465. if (currentTransition !== null && currentNavigation !== null) {
  5466. this.stateManager.handleRouterEvent(e, currentNavigation);
  5467. if (e instanceof NavigationCancel &&
  5468. e.code !== NavigationCancellationCode.Redirect &&
  5469. e.code !== NavigationCancellationCode.SupersededByNewNavigation) {
  5470. // It seems weird that `navigated` is set to `true` when the navigation is rejected,
  5471. // however it's how things were written initially. Investigation would need to be done
  5472. // to determine if this can be removed.
  5473. this.navigated = true;
  5474. }
  5475. else if (e instanceof NavigationEnd) {
  5476. this.navigated = true;
  5477. }
  5478. else if (e instanceof RedirectRequest) {
  5479. const opts = e.navigationBehaviorOptions;
  5480. const mergedTree = this.urlHandlingStrategy.merge(e.url, currentTransition.currentRawUrl);
  5481. const extras = {
  5482. browserUrl: currentTransition.extras.browserUrl,
  5483. info: currentTransition.extras.info,
  5484. skipLocationChange: currentTransition.extras.skipLocationChange,
  5485. // The URL is already updated at this point if we have 'eager' URL
  5486. // updates or if the navigation was triggered by the browser (back
  5487. // button, URL bar, etc). We want to replace that item in history
  5488. // if the navigation is rejected.
  5489. replaceUrl: currentTransition.extras.replaceUrl ||
  5490. this.urlUpdateStrategy === 'eager' ||
  5491. isBrowserTriggeredNavigation(currentTransition.source),
  5492. // allow developer to override default options with RedirectCommand
  5493. ...opts,
  5494. };
  5495. this.scheduleNavigation(mergedTree, IMPERATIVE_NAVIGATION, null, extras, {
  5496. resolve: currentTransition.resolve,
  5497. reject: currentTransition.reject,
  5498. promise: currentTransition.promise,
  5499. });
  5500. }
  5501. }
  5502. // Note that it's important to have the Router process the events _before_ the event is
  5503. // pushed through the public observable. This ensures the correct router state is in place
  5504. // before applications observe the events.
  5505. if (isPublicRouterEvent(e)) {
  5506. this._events.next(e);
  5507. }
  5508. }
  5509. catch (e) {
  5510. this.navigationTransitions.transitionAbortSubject.next(e);
  5511. }
  5512. });
  5513. this.eventsSubscription.add(subscription);
  5514. }
  5515. /** @internal */
  5516. resetRootComponentType(rootComponentType) {
  5517. // TODO: vsavkin router 4.0 should make the root component set to null
  5518. // this will simplify the lifecycle of the router.
  5519. this.routerState.root.component = rootComponentType;
  5520. this.navigationTransitions.rootComponentType = rootComponentType;
  5521. }
  5522. /**
  5523. * Sets up the location change listener and performs the initial navigation.
  5524. */
  5525. initialNavigation() {
  5526. this.setUpLocationChangeListener();
  5527. if (!this.navigationTransitions.hasRequestedNavigation) {
  5528. this.navigateToSyncWithBrowser(this.location.path(true), IMPERATIVE_NAVIGATION, this.stateManager.restoredState());
  5529. }
  5530. }
  5531. /**
  5532. * Sets up the location change listener. This listener detects navigations triggered from outside
  5533. * the Router (the browser back/forward buttons, for example) and schedules a corresponding Router
  5534. * navigation so that the correct events, guards, etc. are triggered.
  5535. */
  5536. setUpLocationChangeListener() {
  5537. // Don't need to use Zone.wrap any more, because zone.js
  5538. // already patch onPopState, so location change callback will
  5539. // run into ngZone
  5540. this.nonRouterCurrentEntryChangeSubscription ??=
  5541. this.stateManager.registerNonRouterCurrentEntryChangeListener((url, state, source) => {
  5542. this.navigateToSyncWithBrowser(url, source, state);
  5543. });
  5544. }
  5545. /**
  5546. * Schedules a router navigation to synchronize Router state with the browser state.
  5547. *
  5548. * This is done as a response to a popstate event and the initial navigation. These
  5549. * two scenarios represent times when the browser URL/state has been updated and
  5550. * the Router needs to respond to ensure its internal state matches.
  5551. */
  5552. navigateToSyncWithBrowser(url, source, state) {
  5553. const extras = { replaceUrl: true };
  5554. // TODO: restoredState should always include the entire state, regardless
  5555. // of navigationId. This requires a breaking change to update the type on
  5556. // NavigationStart’s restoredState, which currently requires navigationId
  5557. // to always be present. The Router used to only restore history state if
  5558. // a navigationId was present.
  5559. // The stored navigationId is used by the RouterScroller to retrieve the scroll
  5560. // position for the page.
  5561. const restoredState = state?.navigationId ? state : null;
  5562. // Separate to NavigationStart.restoredState, we must also restore the state to
  5563. // history.state and generate a new navigationId, since it will be overwritten
  5564. if (state) {
  5565. const stateCopy = { ...state };
  5566. delete stateCopy.navigationId;
  5567. delete stateCopy.ɵrouterPageId;
  5568. if (Object.keys(stateCopy).length !== 0) {
  5569. extras.state = stateCopy;
  5570. }
  5571. }
  5572. const urlTree = this.parseUrl(url);
  5573. this.scheduleNavigation(urlTree, source, restoredState, extras);
  5574. }
  5575. /** The current URL. */
  5576. get url() {
  5577. return this.serializeUrl(this.currentUrlTree);
  5578. }
  5579. /**
  5580. * Returns the current `Navigation` object when the router is navigating,
  5581. * and `null` when idle.
  5582. */
  5583. getCurrentNavigation() {
  5584. return this.navigationTransitions.currentNavigation;
  5585. }
  5586. /**
  5587. * The `Navigation` object of the most recent navigation to succeed and `null` if there
  5588. * has not been a successful navigation yet.
  5589. */
  5590. get lastSuccessfulNavigation() {
  5591. return this.navigationTransitions.lastSuccessfulNavigation;
  5592. }
  5593. /**
  5594. * Resets the route configuration used for navigation and generating links.
  5595. *
  5596. * @param config The route array for the new configuration.
  5597. *
  5598. * @usageNotes
  5599. *
  5600. * ```ts
  5601. * router.resetConfig([
  5602. * { path: 'team/:id', component: TeamCmp, children: [
  5603. * { path: 'simple', component: SimpleCmp },
  5604. * { path: 'user/:name', component: UserCmp }
  5605. * ]}
  5606. * ]);
  5607. * ```
  5608. */
  5609. resetConfig(config) {
  5610. (typeof ngDevMode === 'undefined' || ngDevMode) && validateConfig(config);
  5611. this.config = config.map(standardizeConfig);
  5612. this.navigated = false;
  5613. }
  5614. /** @docs-private */
  5615. ngOnDestroy() {
  5616. this.dispose();
  5617. }
  5618. /** Disposes of the router. */
  5619. dispose() {
  5620. // We call `unsubscribe()` to release observers, as users may forget to
  5621. // unsubscribe manually when subscribing to `router.events`. We do not call
  5622. // `complete()` because it is unsafe; if someone subscribes using the `first`
  5623. // operator and the observable completes before emitting a value,
  5624. // RxJS will throw an error.
  5625. this._events.unsubscribe();
  5626. this.navigationTransitions.complete();
  5627. if (this.nonRouterCurrentEntryChangeSubscription) {
  5628. this.nonRouterCurrentEntryChangeSubscription.unsubscribe();
  5629. this.nonRouterCurrentEntryChangeSubscription = undefined;
  5630. }
  5631. this.disposed = true;
  5632. this.eventsSubscription.unsubscribe();
  5633. }
  5634. /**
  5635. * Appends URL segments to the current URL tree to create a new URL tree.
  5636. *
  5637. * @param commands An array of URL fragments with which to construct the new URL tree.
  5638. * If the path is static, can be the literal URL string. For a dynamic path, pass an array of path
  5639. * segments, followed by the parameters for each segment.
  5640. * The fragments are applied to the current URL tree or the one provided in the `relativeTo`
  5641. * property of the options object, if supplied.
  5642. * @param navigationExtras Options that control the navigation strategy.
  5643. * @returns The new URL tree.
  5644. *
  5645. * @usageNotes
  5646. *
  5647. * ```
  5648. * // create /team/33/user/11
  5649. * router.createUrlTree(['/team', 33, 'user', 11]);
  5650. *
  5651. * // create /team/33;expand=true/user/11
  5652. * router.createUrlTree(['/team', 33, {expand: true}, 'user', 11]);
  5653. *
  5654. * // you can collapse static segments like this (this works only with the first passed-in value):
  5655. * router.createUrlTree(['/team/33/user', userId]);
  5656. *
  5657. * // If the first segment can contain slashes, and you do not want the router to split it,
  5658. * // you can do the following:
  5659. * router.createUrlTree([{segmentPath: '/one/two'}]);
  5660. *
  5661. * // create /team/33/(user/11//right:chat)
  5662. * router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: 'chat'}}]);
  5663. *
  5664. * // remove the right secondary node
  5665. * router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: null}}]);
  5666. *
  5667. * // assuming the current url is `/team/33/user/11` and the route points to `user/11`
  5668. *
  5669. * // navigate to /team/33/user/11/details
  5670. * router.createUrlTree(['details'], {relativeTo: route});
  5671. *
  5672. * // navigate to /team/33/user/22
  5673. * router.createUrlTree(['../22'], {relativeTo: route});
  5674. *
  5675. * // navigate to /team/44/user/22
  5676. * router.createUrlTree(['../../team/44/user/22'], {relativeTo: route});
  5677. *
  5678. * Note that a value of `null` or `undefined` for `relativeTo` indicates that the
  5679. * tree should be created relative to the root.
  5680. * ```
  5681. */
  5682. createUrlTree(commands, navigationExtras = {}) {
  5683. const { relativeTo, queryParams, fragment, queryParamsHandling, preserveFragment } = navigationExtras;
  5684. const f = preserveFragment ? this.currentUrlTree.fragment : fragment;
  5685. let q = null;
  5686. switch (queryParamsHandling ?? this.options.defaultQueryParamsHandling) {
  5687. case 'merge':
  5688. q = { ...this.currentUrlTree.queryParams, ...queryParams };
  5689. break;
  5690. case 'preserve':
  5691. q = this.currentUrlTree.queryParams;
  5692. break;
  5693. default:
  5694. q = queryParams || null;
  5695. }
  5696. if (q !== null) {
  5697. q = this.removeEmptyProps(q);
  5698. }
  5699. let relativeToUrlSegmentGroup;
  5700. try {
  5701. const relativeToSnapshot = relativeTo ? relativeTo.snapshot : this.routerState.snapshot.root;
  5702. relativeToUrlSegmentGroup = createSegmentGroupFromRoute(relativeToSnapshot);
  5703. }
  5704. catch (e) {
  5705. // This is strictly for backwards compatibility with tests that create
  5706. // invalid `ActivatedRoute` mocks.
  5707. // Note: the difference between having this fallback for invalid `ActivatedRoute` setups and
  5708. // just throwing is ~500 test failures. Fixing all of those tests by hand is not feasible at
  5709. // the moment.
  5710. if (typeof commands[0] !== 'string' || commands[0][0] !== '/') {
  5711. // Navigations that were absolute in the old way of creating UrlTrees
  5712. // would still work because they wouldn't attempt to match the
  5713. // segments in the `ActivatedRoute` to the `currentUrlTree` but
  5714. // instead just replace the root segment with the navigation result.
  5715. // Non-absolute navigations would fail to apply the commands because
  5716. // the logic could not find the segment to replace (so they'd act like there were no
  5717. // commands).
  5718. commands = [];
  5719. }
  5720. relativeToUrlSegmentGroup = this.currentUrlTree.root;
  5721. }
  5722. return createUrlTreeFromSegmentGroup(relativeToUrlSegmentGroup, commands, q, f ?? null);
  5723. }
  5724. /**
  5725. * Navigates to a view using an absolute route path.
  5726. *
  5727. * @param url An absolute path for a defined route. The function does not apply any delta to the
  5728. * current URL.
  5729. * @param extras An object containing properties that modify the navigation strategy.
  5730. *
  5731. * @returns A Promise that resolves to 'true' when navigation succeeds,
  5732. * to 'false' when navigation fails, or is rejected on error.
  5733. *
  5734. * @usageNotes
  5735. *
  5736. * The following calls request navigation to an absolute path.
  5737. *
  5738. * ```ts
  5739. * router.navigateByUrl("/team/33/user/11");
  5740. *
  5741. * // Navigate without updating the URL
  5742. * router.navigateByUrl("/team/33/user/11", { skipLocationChange: true });
  5743. * ```
  5744. *
  5745. * @see [Routing and Navigation guide](guide/routing/common-router-tasks)
  5746. *
  5747. */
  5748. navigateByUrl(url, extras = {
  5749. skipLocationChange: false,
  5750. }) {
  5751. const urlTree = isUrlTree(url) ? url : this.parseUrl(url);
  5752. const mergedTree = this.urlHandlingStrategy.merge(urlTree, this.rawUrlTree);
  5753. return this.scheduleNavigation(mergedTree, IMPERATIVE_NAVIGATION, null, extras);
  5754. }
  5755. /**
  5756. * Navigate based on the provided array of commands and a starting point.
  5757. * If no starting route is provided, the navigation is absolute.
  5758. *
  5759. * @param commands An array of URL fragments with which to construct the target URL.
  5760. * If the path is static, can be the literal URL string. For a dynamic path, pass an array of path
  5761. * segments, followed by the parameters for each segment.
  5762. * The fragments are applied to the current URL or the one provided in the `relativeTo` property
  5763. * of the options object, if supplied.
  5764. * @param extras An options object that determines how the URL should be constructed or
  5765. * interpreted.
  5766. *
  5767. * @returns A Promise that resolves to `true` when navigation succeeds, or `false` when navigation
  5768. * fails. The Promise is rejected when an error occurs if `resolveNavigationPromiseOnError` is
  5769. * not `true`.
  5770. *
  5771. * @usageNotes
  5772. *
  5773. * The following calls request navigation to a dynamic route path relative to the current URL.
  5774. *
  5775. * ```ts
  5776. * router.navigate(['team', 33, 'user', 11], {relativeTo: route});
  5777. *
  5778. * // Navigate without updating the URL, overriding the default behavior
  5779. * router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true});
  5780. * ```
  5781. *
  5782. * @see [Routing and Navigation guide](guide/routing/common-router-tasks)
  5783. *
  5784. */
  5785. navigate(commands, extras = { skipLocationChange: false }) {
  5786. validateCommands(commands);
  5787. return this.navigateByUrl(this.createUrlTree(commands, extras), extras);
  5788. }
  5789. /** Serializes a `UrlTree` into a string */
  5790. serializeUrl(url) {
  5791. return this.urlSerializer.serialize(url);
  5792. }
  5793. /** Parses a string into a `UrlTree` */
  5794. parseUrl(url) {
  5795. try {
  5796. return this.urlSerializer.parse(url);
  5797. }
  5798. catch {
  5799. return this.urlSerializer.parse('/');
  5800. }
  5801. }
  5802. isActive(url, matchOptions) {
  5803. let options;
  5804. if (matchOptions === true) {
  5805. options = { ...exactMatchOptions };
  5806. }
  5807. else if (matchOptions === false) {
  5808. options = { ...subsetMatchOptions };
  5809. }
  5810. else {
  5811. options = matchOptions;
  5812. }
  5813. if (isUrlTree(url)) {
  5814. return containsTree(this.currentUrlTree, url, options);
  5815. }
  5816. const urlTree = this.parseUrl(url);
  5817. return containsTree(this.currentUrlTree, urlTree, options);
  5818. }
  5819. removeEmptyProps(params) {
  5820. return Object.entries(params).reduce((result, [key, value]) => {
  5821. if (value !== null && value !== undefined) {
  5822. result[key] = value;
  5823. }
  5824. return result;
  5825. }, {});
  5826. }
  5827. scheduleNavigation(rawUrl, source, restoredState, extras, priorPromise) {
  5828. if (this.disposed) {
  5829. return Promise.resolve(false);
  5830. }
  5831. let resolve;
  5832. let reject;
  5833. let promise;
  5834. if (priorPromise) {
  5835. resolve = priorPromise.resolve;
  5836. reject = priorPromise.reject;
  5837. promise = priorPromise.promise;
  5838. }
  5839. else {
  5840. promise = new Promise((res, rej) => {
  5841. resolve = res;
  5842. reject = rej;
  5843. });
  5844. }
  5845. // Indicate that the navigation is happening.
  5846. const taskId = this.pendingTasks.add();
  5847. afterNextNavigation(this, () => {
  5848. // Remove pending task in a microtask to allow for cancelled
  5849. // initial navigations and redirects within the same task.
  5850. queueMicrotask(() => this.pendingTasks.remove(taskId));
  5851. });
  5852. this.navigationTransitions.handleNavigationRequest({
  5853. source,
  5854. restoredState,
  5855. currentUrlTree: this.currentUrlTree,
  5856. currentRawUrl: this.currentUrlTree,
  5857. rawUrl,
  5858. extras,
  5859. resolve: resolve,
  5860. reject: reject,
  5861. promise,
  5862. currentSnapshot: this.routerState.snapshot,
  5863. currentRouterState: this.routerState,
  5864. });
  5865. // Make sure that the error is propagated even though `processNavigations` catch
  5866. // handler does not rethrow
  5867. return promise.catch((e) => {
  5868. return Promise.reject(e);
  5869. });
  5870. }
  5871. static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: Router, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
  5872. static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: Router, providedIn: 'root' });
  5873. }
  5874. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: Router, decorators: [{
  5875. type: Injectable,
  5876. args: [{ providedIn: 'root' }]
  5877. }], ctorParameters: () => [] });
  5878. function validateCommands(commands) {
  5879. for (let i = 0; i < commands.length; i++) {
  5880. const cmd = commands[i];
  5881. if (cmd == null) {
  5882. throw new _RuntimeError(4008 /* RuntimeErrorCode.NULLISH_COMMAND */, (typeof ngDevMode === 'undefined' || ngDevMode) &&
  5883. `The requested path contains ${cmd} segment at index ${i}`);
  5884. }
  5885. }
  5886. }
  5887. function isPublicRouterEvent(e) {
  5888. return !(e instanceof BeforeActivateRoutes) && !(e instanceof RedirectRequest);
  5889. }
  5890. export { ActivatedRoute, ActivatedRouteSnapshot, ActivationEnd, ActivationStart, BaseRouteReuseStrategy, CREATE_VIEW_TRANSITION, ChildActivationEnd, ChildActivationStart, ChildrenOutletContexts, DefaultTitleStrategy, DefaultUrlSerializer, EventType, GuardsCheckEnd, GuardsCheckStart, INPUT_BINDER, NAVIGATION_ERROR_HANDLER, NavigationCancel, NavigationCancellationCode, NavigationEnd, NavigationError, NavigationSkipped, NavigationSkippedCode, NavigationStart, NavigationTransitions, OutletContext, PRIMARY_OUTLET, ROUTER_CONFIGURATION, ROUTER_OUTLET_DATA, ROUTES, RedirectCommand, ResolveEnd, ResolveStart, RouteConfigLoadEnd, RouteConfigLoadStart, RouteReuseStrategy, RoutedComponentInputBinder, Router, RouterConfigLoader, RouterEvent, RouterOutlet, RouterState, RouterStateSnapshot, RoutesRecognized, Scroll, TitleStrategy, UrlHandlingStrategy, UrlSegment, UrlSegmentGroup, UrlSerializer, UrlTree, VIEW_TRANSITION_OPTIONS, afterNextNavigation, convertToParamMap, createUrlTreeFromSnapshot, createViewTransition, defaultUrlMatcher, isUrlTree, loadChildren, stringifyEvent, ɵEmptyOutletComponent };
  5891. //# sourceMappingURL=router-Dwfin5Au.mjs.map