core.mjs 1.6 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551
  1. /**
  2. * @license Angular v19.2.4
  3. * (c) 2010-2025 Google LLC. https://angular.io/
  4. * License: MIT
  5. */
  6. import { v as SIGNAL_NODE, z as signalSetFn, S as SIGNAL, p as producerAccessed, k as getActiveConsumer, u as setActiveConsumer$1, w as createSignal, A as signalUpdateFn, a as consumerDestroy, R as REACTIVE_NODE, b as consumerPollProducersForChange, d as consumerBeforeComputation, e as consumerAfterComputation, f as createComputed, s as setThrowInvalidWriteToSignalError, C as untracked$1, i as isInNotificationPhase, g as createLinkedSignal, l as linkedSignalSetFn, h as linkedSignalUpdateFn } from './untracked-CS7WUAzb.mjs';
  7. export { B as ɵsetAlternateWeakRefImpl } from './untracked-CS7WUAzb.mjs';
  8. import { getCurrentInjector, NOT_FOUND as NOT_FOUND$1, setCurrentInjector } from './primitives/di.mjs';
  9. import { setActiveConsumer, createWatch } from '@angular/core/primitives/signals';
  10. import { NOT_FOUND as NOT_FOUND$2 } from '@angular/core/primitives/di';
  11. import { BehaviorSubject, Subject, Subscription } from 'rxjs';
  12. import { Attribute as Attribute$1, clearAppScopedEarlyEventContract, EventContract, EventContractContainer, getAppScopedQueuedEventInfos, EventDispatcher, registerDispatcher, EventPhase, isEarlyEventType, isCaptureEventType } from './primitives/event-dispatch.mjs';
  13. import { map } from 'rxjs/operators';
  14. /**
  15. * Base URL for the error details page.
  16. *
  17. * Keep this constant in sync across:
  18. * - packages/compiler-cli/src/ngtsc/diagnostics/src/error_details_base_url.ts
  19. * - packages/core/src/error_details_base_url.ts
  20. */
  21. const ERROR_DETAILS_PAGE_BASE_URL = 'https://angular.dev/errors';
  22. /**
  23. * URL for the XSS security documentation.
  24. */
  25. const XSS_SECURITY_URL = 'https://angular.dev/best-practices/security#preventing-cross-site-scripting-xss';
  26. /**
  27. * Class that represents a runtime error.
  28. * Formats and outputs the error message in a consistent way.
  29. *
  30. * Example:
  31. * ```ts
  32. * throw new RuntimeError(
  33. * RuntimeErrorCode.INJECTOR_ALREADY_DESTROYED,
  34. * ngDevMode && 'Injector has already been destroyed.');
  35. * ```
  36. *
  37. * Note: the `message` argument contains a descriptive error message as a string in development
  38. * mode (when the `ngDevMode` is defined). In production mode (after tree-shaking pass), the
  39. * `message` argument becomes `false`, thus we account for it in the typings and the runtime
  40. * logic.
  41. */
  42. class RuntimeError extends Error {
  43. code;
  44. constructor(code, message) {
  45. super(formatRuntimeError(code, message));
  46. this.code = code;
  47. }
  48. }
  49. /**
  50. * Called to format a runtime error.
  51. * See additional info on the `message` argument type in the `RuntimeError` class description.
  52. */
  53. function formatRuntimeError(code, message) {
  54. // Error code might be a negative number, which is a special marker that instructs the logic to
  55. // generate a link to the error details page on angular.io.
  56. // We also prepend `0` to non-compile-time errors.
  57. const fullCode = `NG0${Math.abs(code)}`;
  58. let errorMessage = `${fullCode}${message ? ': ' + message : ''}`;
  59. if (ngDevMode && code < 0) {
  60. const addPeriodSeparator = !errorMessage.match(/[.,;!?\n]$/);
  61. const separator = addPeriodSeparator ? '.' : '';
  62. errorMessage = `${errorMessage}${separator} Find more at ${ERROR_DETAILS_PAGE_BASE_URL}/${fullCode}`;
  63. }
  64. return errorMessage;
  65. }
  66. const REQUIRED_UNSET_VALUE = /* @__PURE__ */ Symbol('InputSignalNode#UNSET');
  67. // Note: Using an IIFE here to ensure that the spread assignment is not considered
  68. // a side-effect, ending up preserving `COMPUTED_NODE` and `REACTIVE_NODE`.
  69. // TODO: remove when https://github.com/evanw/esbuild/issues/3392 is resolved.
  70. const INPUT_SIGNAL_NODE = /* @__PURE__ */ (() => {
  71. return {
  72. ...SIGNAL_NODE,
  73. transformFn: undefined,
  74. applyValueToInputSignal(node, value) {
  75. signalSetFn(node, value);
  76. },
  77. };
  78. })();
  79. const ɵINPUT_SIGNAL_BRAND_WRITE_TYPE = /* @__PURE__ */ Symbol();
  80. /**
  81. * Creates an input signal.
  82. *
  83. * @param initialValue The initial value.
  84. * Can be set to {@link REQUIRED_UNSET_VALUE} for required inputs.
  85. * @param options Additional options for the input. e.g. a transform, or an alias.
  86. */
  87. function createInputSignal(initialValue, options) {
  88. const node = Object.create(INPUT_SIGNAL_NODE);
  89. node.value = initialValue;
  90. // Perf note: Always set `transformFn` here to ensure that `node` always
  91. // has the same v8 class shape, allowing monomorphic reads on input signals.
  92. node.transformFn = options?.transform;
  93. function inputValueFn() {
  94. // Record that someone looked at this signal.
  95. producerAccessed(node);
  96. if (node.value === REQUIRED_UNSET_VALUE) {
  97. let message = null;
  98. if (ngDevMode) {
  99. const name = options?.debugName ?? options?.alias;
  100. message = `Input${name ? ` "${name}"` : ''} is required but no value is available yet.`;
  101. }
  102. throw new RuntimeError(-950 /* RuntimeErrorCode.REQUIRED_INPUT_NO_VALUE */, message);
  103. }
  104. return node.value;
  105. }
  106. inputValueFn[SIGNAL] = node;
  107. if (ngDevMode) {
  108. inputValueFn.toString = () => `[Input Signal: ${inputValueFn()}]`;
  109. node.debugName = options?.debugName;
  110. }
  111. return inputValueFn;
  112. }
  113. /**
  114. * Convince closure compiler that the wrapped function has no side-effects.
  115. *
  116. * Closure compiler always assumes that `toString` has no side-effects. We use this quirk to
  117. * allow us to execute a function but have closure compiler mark the call as no-side-effects.
  118. * It is important that the return value for the `noSideEffects` function be assigned
  119. * to something which is retained otherwise the call to `noSideEffects` will be removed by closure
  120. * compiler.
  121. */
  122. function noSideEffects(fn) {
  123. return { toString: fn }.toString();
  124. }
  125. const ANNOTATIONS = '__annotations__';
  126. const PARAMETERS = '__parameters__';
  127. const PROP_METADATA = '__prop__metadata__';
  128. /**
  129. * @suppress {globalThis}
  130. */
  131. function makeDecorator(name, props, parentClass, additionalProcessing, typeFn) {
  132. return noSideEffects(() => {
  133. const metaCtor = makeMetadataCtor(props);
  134. function DecoratorFactory(...args) {
  135. if (this instanceof DecoratorFactory) {
  136. metaCtor.call(this, ...args);
  137. return this;
  138. }
  139. const annotationInstance = new DecoratorFactory(...args);
  140. return function TypeDecorator(cls) {
  141. if (typeFn)
  142. typeFn(cls, ...args);
  143. // Use of Object.defineProperty is important since it creates non-enumerable property which
  144. // prevents the property is copied during subclassing.
  145. const annotations = cls.hasOwnProperty(ANNOTATIONS)
  146. ? cls[ANNOTATIONS]
  147. : Object.defineProperty(cls, ANNOTATIONS, { value: [] })[ANNOTATIONS];
  148. annotations.push(annotationInstance);
  149. return cls;
  150. };
  151. }
  152. if (parentClass) {
  153. DecoratorFactory.prototype = Object.create(parentClass.prototype);
  154. }
  155. DecoratorFactory.prototype.ngMetadataName = name;
  156. DecoratorFactory.annotationCls = DecoratorFactory;
  157. return DecoratorFactory;
  158. });
  159. }
  160. function makeMetadataCtor(props) {
  161. return function ctor(...args) {
  162. if (props) {
  163. const values = props(...args);
  164. for (const propName in values) {
  165. this[propName] = values[propName];
  166. }
  167. }
  168. };
  169. }
  170. function makeParamDecorator(name, props, parentClass) {
  171. return noSideEffects(() => {
  172. const metaCtor = makeMetadataCtor(props);
  173. function ParamDecoratorFactory(...args) {
  174. if (this instanceof ParamDecoratorFactory) {
  175. metaCtor.apply(this, args);
  176. return this;
  177. }
  178. const annotationInstance = new ParamDecoratorFactory(...args);
  179. ParamDecorator.annotation = annotationInstance;
  180. return ParamDecorator;
  181. function ParamDecorator(cls, unusedKey, index) {
  182. // Use of Object.defineProperty is important since it creates non-enumerable property which
  183. // prevents the property is copied during subclassing.
  184. const parameters = cls.hasOwnProperty(PARAMETERS)
  185. ? cls[PARAMETERS]
  186. : Object.defineProperty(cls, PARAMETERS, { value: [] })[PARAMETERS];
  187. // there might be gaps if some in between parameters do not have annotations.
  188. // we pad with nulls.
  189. while (parameters.length <= index) {
  190. parameters.push(null);
  191. }
  192. (parameters[index] = parameters[index] || []).push(annotationInstance);
  193. return cls;
  194. }
  195. }
  196. ParamDecoratorFactory.prototype.ngMetadataName = name;
  197. ParamDecoratorFactory.annotationCls = ParamDecoratorFactory;
  198. return ParamDecoratorFactory;
  199. });
  200. }
  201. function makePropDecorator(name, props, parentClass, additionalProcessing) {
  202. return noSideEffects(() => {
  203. const metaCtor = makeMetadataCtor(props);
  204. function PropDecoratorFactory(...args) {
  205. if (this instanceof PropDecoratorFactory) {
  206. metaCtor.apply(this, args);
  207. return this;
  208. }
  209. const decoratorInstance = new PropDecoratorFactory(...args);
  210. function PropDecorator(target, name) {
  211. // target is undefined with standard decorators. This case is not supported and will throw
  212. // if this decorator is used in JIT mode with standard decorators.
  213. if (target === undefined) {
  214. throw new Error('Standard Angular field decorators are not supported in JIT mode.');
  215. }
  216. const constructor = target.constructor;
  217. // Use of Object.defineProperty is important because it creates a non-enumerable property
  218. // which prevents the property from being copied during subclassing.
  219. const meta = constructor.hasOwnProperty(PROP_METADATA)
  220. ? constructor[PROP_METADATA]
  221. : Object.defineProperty(constructor, PROP_METADATA, { value: {} })[PROP_METADATA];
  222. meta[name] = (meta.hasOwnProperty(name) && meta[name]) || [];
  223. meta[name].unshift(decoratorInstance);
  224. }
  225. return PropDecorator;
  226. }
  227. if (parentClass) {
  228. PropDecoratorFactory.prototype = Object.create(parentClass.prototype);
  229. }
  230. PropDecoratorFactory.prototype.ngMetadataName = name;
  231. PropDecoratorFactory.annotationCls = PropDecoratorFactory;
  232. return PropDecoratorFactory;
  233. });
  234. }
  235. const _global = globalThis;
  236. function ngDevModeResetPerfCounters() {
  237. const locationString = typeof location !== 'undefined' ? location.toString() : '';
  238. const newCounters = {
  239. namedConstructors: locationString.indexOf('ngDevMode=namedConstructors') != -1,
  240. firstCreatePass: 0,
  241. tNode: 0,
  242. tView: 0,
  243. rendererCreateTextNode: 0,
  244. rendererSetText: 0,
  245. rendererCreateElement: 0,
  246. rendererAddEventListener: 0,
  247. rendererSetAttribute: 0,
  248. rendererRemoveAttribute: 0,
  249. rendererSetProperty: 0,
  250. rendererSetClassName: 0,
  251. rendererAddClass: 0,
  252. rendererRemoveClass: 0,
  253. rendererSetStyle: 0,
  254. rendererRemoveStyle: 0,
  255. rendererDestroy: 0,
  256. rendererDestroyNode: 0,
  257. rendererMoveNode: 0,
  258. rendererRemoveNode: 0,
  259. rendererAppendChild: 0,
  260. rendererInsertBefore: 0,
  261. rendererCreateComment: 0,
  262. hydratedNodes: 0,
  263. hydratedComponents: 0,
  264. dehydratedViewsRemoved: 0,
  265. dehydratedViewsCleanupRuns: 0,
  266. componentsSkippedHydration: 0,
  267. deferBlocksWithIncrementalHydration: 0,
  268. };
  269. // Make sure to refer to ngDevMode as ['ngDevMode'] for closure.
  270. const allowNgDevModeTrue = locationString.indexOf('ngDevMode=false') === -1;
  271. if (!allowNgDevModeTrue) {
  272. _global['ngDevMode'] = false;
  273. }
  274. else {
  275. if (typeof _global['ngDevMode'] !== 'object') {
  276. _global['ngDevMode'] = {};
  277. }
  278. Object.assign(_global['ngDevMode'], newCounters);
  279. }
  280. return newCounters;
  281. }
  282. /**
  283. * This function checks to see if the `ngDevMode` has been set. If yes,
  284. * then we honor it, otherwise we default to dev mode with additional checks.
  285. *
  286. * The idea is that unless we are doing production build where we explicitly
  287. * set `ngDevMode == false` we should be helping the developer by providing
  288. * as much early warning and errors as possible.
  289. *
  290. * `ɵɵdefineComponent` is guaranteed to have been called before any component template functions
  291. * (and thus Ivy instructions), so a single initialization there is sufficient to ensure ngDevMode
  292. * is defined for the entire instruction set.
  293. *
  294. * When checking `ngDevMode` on toplevel, always init it before referencing it
  295. * (e.g. `((typeof ngDevMode === 'undefined' || ngDevMode) && initNgDevMode())`), otherwise you can
  296. * get a `ReferenceError` like in https://github.com/angular/angular/issues/31595.
  297. *
  298. * Details on possible values for `ngDevMode` can be found on its docstring.
  299. *
  300. * NOTE:
  301. * - changes to the `ngDevMode` name must be synced with `compiler-cli/src/tooling.ts`.
  302. */
  303. function initNgDevMode() {
  304. // The below checks are to ensure that calling `initNgDevMode` multiple times does not
  305. // reset the counters.
  306. // If the `ngDevMode` is not an object, then it means we have not created the perf counters
  307. // yet.
  308. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  309. if (typeof ngDevMode !== 'object' || Object.keys(ngDevMode).length === 0) {
  310. ngDevModeResetPerfCounters();
  311. }
  312. return typeof ngDevMode !== 'undefined' && !!ngDevMode;
  313. }
  314. return false;
  315. }
  316. function getClosureSafeProperty(objWithPropertyToExtract) {
  317. for (let key in objWithPropertyToExtract) {
  318. if (objWithPropertyToExtract[key] === getClosureSafeProperty) {
  319. return key;
  320. }
  321. }
  322. throw Error('Could not find renamed property on target object.');
  323. }
  324. /**
  325. * Sets properties on a target object from a source object, but only if
  326. * the property doesn't already exist on the target object.
  327. * @param target The target to set properties on
  328. * @param source The source of the property keys and values to set
  329. */
  330. function fillProperties(target, source) {
  331. for (const key in source) {
  332. if (source.hasOwnProperty(key) && !target.hasOwnProperty(key)) {
  333. target[key] = source[key];
  334. }
  335. }
  336. }
  337. function stringify(token) {
  338. if (typeof token === 'string') {
  339. return token;
  340. }
  341. if (Array.isArray(token)) {
  342. return `[${token.map(stringify).join(', ')}]`;
  343. }
  344. if (token == null) {
  345. return '' + token;
  346. }
  347. const name = token.overriddenName || token.name;
  348. if (name) {
  349. return `${name}`;
  350. }
  351. const result = token.toString();
  352. if (result == null) {
  353. return '' + result;
  354. }
  355. const newLineIndex = result.indexOf('\n');
  356. return newLineIndex >= 0 ? result.slice(0, newLineIndex) : result;
  357. }
  358. /**
  359. * Concatenates two strings with separator, allocating new strings only when necessary.
  360. *
  361. * @param before before string.
  362. * @param separator separator string.
  363. * @param after after string.
  364. * @returns concatenated string.
  365. */
  366. function concatStringsWithSpace(before, after) {
  367. if (!before)
  368. return after || '';
  369. if (!after)
  370. return before;
  371. return `${before} ${after}`;
  372. }
  373. /**
  374. * Ellipses the string in the middle when longer than the max length
  375. *
  376. * @param string
  377. * @param maxLength of the output string
  378. * @returns ellipsed string with ... in the middle
  379. */
  380. function truncateMiddle(str, maxLength = 100) {
  381. if (!str || maxLength < 1 || str.length <= maxLength)
  382. return str;
  383. if (maxLength == 1)
  384. return str.substring(0, 1) + '...';
  385. const halfLimit = Math.round(maxLength / 2);
  386. return str.substring(0, halfLimit) + '...' + str.substring(str.length - halfLimit);
  387. }
  388. const __forward_ref__ = getClosureSafeProperty({ __forward_ref__: getClosureSafeProperty });
  389. /**
  390. * Allows to refer to references which are not yet defined.
  391. *
  392. * For instance, `forwardRef` is used when the `token` which we need to refer to for the purposes of
  393. * DI is declared, but not yet defined. It is also used when the `token` which we use when creating
  394. * a query is not yet defined.
  395. *
  396. * `forwardRef` is also used to break circularities in standalone components imports.
  397. *
  398. * @usageNotes
  399. * ### Circular dependency example
  400. * {@example core/di/ts/forward_ref/forward_ref_spec.ts region='forward_ref'}
  401. *
  402. * ### Circular standalone reference import example
  403. * ```angular-ts
  404. * @Component({
  405. * standalone: true,
  406. * imports: [ChildComponent],
  407. * selector: 'app-parent',
  408. * template: `<app-child [hideParent]="hideParent"></app-child>`,
  409. * })
  410. * export class ParentComponent {
  411. * @Input() hideParent: boolean;
  412. * }
  413. *
  414. *
  415. * @Component({
  416. * standalone: true,
  417. * imports: [CommonModule, forwardRef(() => ParentComponent)],
  418. * selector: 'app-child',
  419. * template: `<app-parent *ngIf="!hideParent"></app-parent>`,
  420. * })
  421. * export class ChildComponent {
  422. * @Input() hideParent: boolean;
  423. * }
  424. * ```
  425. *
  426. * @publicApi
  427. */
  428. function forwardRef(forwardRefFn) {
  429. forwardRefFn.__forward_ref__ = forwardRef;
  430. forwardRefFn.toString = function () {
  431. return stringify(this());
  432. };
  433. return forwardRefFn;
  434. }
  435. /**
  436. * Lazily retrieves the reference value from a forwardRef.
  437. *
  438. * Acts as the identity function when given a non-forward-ref value.
  439. *
  440. * @usageNotes
  441. * ### Example
  442. *
  443. * {@example core/di/ts/forward_ref/forward_ref_spec.ts region='resolve_forward_ref'}
  444. *
  445. * @see {@link forwardRef}
  446. * @publicApi
  447. */
  448. function resolveForwardRef(type) {
  449. return isForwardRef(type) ? type() : type;
  450. }
  451. /** Checks whether a function is wrapped by a `forwardRef`. */
  452. function isForwardRef(fn) {
  453. return (typeof fn === 'function' &&
  454. fn.hasOwnProperty(__forward_ref__) &&
  455. fn.__forward_ref__ === forwardRef);
  456. }
  457. // The functions in this file verify that the assumptions we are making
  458. // about state in an instruction are correct before implementing any logic.
  459. // They are meant only to be called in dev mode as sanity checks.
  460. function assertNumber(actual, msg) {
  461. if (!(typeof actual === 'number')) {
  462. throwError(msg, typeof actual, 'number', '===');
  463. }
  464. }
  465. function assertNumberInRange(actual, minInclusive, maxInclusive) {
  466. assertNumber(actual, 'Expected a number');
  467. assertLessThanOrEqual(actual, maxInclusive, 'Expected number to be less than or equal to');
  468. assertGreaterThanOrEqual(actual, minInclusive, 'Expected number to be greater than or equal to');
  469. }
  470. function assertString(actual, msg) {
  471. if (!(typeof actual === 'string')) {
  472. throwError(msg, actual === null ? 'null' : typeof actual, 'string', '===');
  473. }
  474. }
  475. function assertFunction(actual, msg) {
  476. if (!(typeof actual === 'function')) {
  477. throwError(msg, actual === null ? 'null' : typeof actual, 'function', '===');
  478. }
  479. }
  480. function assertEqual(actual, expected, msg) {
  481. if (!(actual == expected)) {
  482. throwError(msg, actual, expected, '==');
  483. }
  484. }
  485. function assertNotEqual(actual, expected, msg) {
  486. if (!(actual != expected)) {
  487. throwError(msg, actual, expected, '!=');
  488. }
  489. }
  490. function assertSame(actual, expected, msg) {
  491. if (!(actual === expected)) {
  492. throwError(msg, actual, expected, '===');
  493. }
  494. }
  495. function assertNotSame(actual, expected, msg) {
  496. if (!(actual !== expected)) {
  497. throwError(msg, actual, expected, '!==');
  498. }
  499. }
  500. function assertLessThan(actual, expected, msg) {
  501. if (!(actual < expected)) {
  502. throwError(msg, actual, expected, '<');
  503. }
  504. }
  505. function assertLessThanOrEqual(actual, expected, msg) {
  506. if (!(actual <= expected)) {
  507. throwError(msg, actual, expected, '<=');
  508. }
  509. }
  510. function assertGreaterThan(actual, expected, msg) {
  511. if (!(actual > expected)) {
  512. throwError(msg, actual, expected, '>');
  513. }
  514. }
  515. function assertGreaterThanOrEqual(actual, expected, msg) {
  516. if (!(actual >= expected)) {
  517. throwError(msg, actual, expected, '>=');
  518. }
  519. }
  520. function assertDefined(actual, msg) {
  521. if (actual == null) {
  522. throwError(msg, actual, null, '!=');
  523. }
  524. }
  525. function throwError(msg, actual, expected, comparison) {
  526. throw new Error(`ASSERTION ERROR: ${msg}` +
  527. (comparison == null ? '' : ` [Expected=> ${expected} ${comparison} ${actual} <=Actual]`));
  528. }
  529. function assertDomNode(node) {
  530. if (!(node instanceof Node)) {
  531. throwError(`The provided value must be an instance of a DOM Node but got ${stringify(node)}`);
  532. }
  533. }
  534. function assertElement(node) {
  535. if (!(node instanceof Element)) {
  536. throwError(`The provided value must be an element but got ${stringify(node)}`);
  537. }
  538. }
  539. function assertIndexInRange(arr, index) {
  540. assertDefined(arr, 'Array must be defined.');
  541. const maxLen = arr.length;
  542. if (index < 0 || index >= maxLen) {
  543. throwError(`Index expected to be less than ${maxLen} but got ${index}`);
  544. }
  545. }
  546. function assertOneOf(value, ...validValues) {
  547. if (validValues.indexOf(value) !== -1)
  548. return true;
  549. throwError(`Expected value to be one of ${JSON.stringify(validValues)} but was ${JSON.stringify(value)}.`);
  550. }
  551. function assertNotReactive(fn) {
  552. if (getActiveConsumer() !== null) {
  553. throwError(`${fn}() should never be called in a reactive context.`);
  554. }
  555. }
  556. /**
  557. * Construct an injectable definition which defines how a token will be constructed by the DI
  558. * system, and in which injectors (if any) it will be available.
  559. *
  560. * This should be assigned to a static `ɵprov` field on a type, which will then be an
  561. * `InjectableType`.
  562. *
  563. * Options:
  564. * * `providedIn` determines which injectors will include the injectable, by either associating it
  565. * with an `@NgModule` or other `InjectorType`, or by specifying that this injectable should be
  566. * provided in the `'root'` injector, which will be the application-level injector in most apps.
  567. * * `factory` gives the zero argument function which will create an instance of the injectable.
  568. * The factory can call [`inject`](api/core/inject) to access the `Injector` and request injection
  569. * of dependencies.
  570. *
  571. * @codeGenApi
  572. * @publicApi This instruction has been emitted by ViewEngine for some time and is deployed to npm.
  573. */
  574. function ɵɵdefineInjectable(opts) {
  575. return {
  576. token: opts.token,
  577. providedIn: opts.providedIn || null,
  578. factory: opts.factory,
  579. value: undefined,
  580. };
  581. }
  582. /**
  583. * @deprecated in v8, delete after v10. This API should be used only by generated code, and that
  584. * code should now use ɵɵdefineInjectable instead.
  585. * @publicApi
  586. */
  587. const defineInjectable = ɵɵdefineInjectable;
  588. /**
  589. * Construct an `InjectorDef` which configures an injector.
  590. *
  591. * This should be assigned to a static injector def (`ɵinj`) field on a type, which will then be an
  592. * `InjectorType`.
  593. *
  594. * Options:
  595. *
  596. * * `providers`: an optional array of providers to add to the injector. Each provider must
  597. * either have a factory or point to a type which has a `ɵprov` static property (the
  598. * type must be an `InjectableType`).
  599. * * `imports`: an optional array of imports of other `InjectorType`s or `InjectorTypeWithModule`s
  600. * whose providers will also be added to the injector. Locally provided types will override
  601. * providers from imports.
  602. *
  603. * @codeGenApi
  604. */
  605. function ɵɵdefineInjector(options) {
  606. return { providers: options.providers || [], imports: options.imports || [] };
  607. }
  608. /**
  609. * Read the injectable def (`ɵprov`) for `type` in a way which is immune to accidentally reading
  610. * inherited value.
  611. *
  612. * @param type A type which may have its own (non-inherited) `ɵprov`.
  613. */
  614. function getInjectableDef(type) {
  615. return getOwnDefinition(type, NG_PROV_DEF) || getOwnDefinition(type, NG_INJECTABLE_DEF);
  616. }
  617. function isInjectable(type) {
  618. return getInjectableDef(type) !== null;
  619. }
  620. /**
  621. * Return definition only if it is defined directly on `type` and is not inherited from a base
  622. * class of `type`.
  623. */
  624. function getOwnDefinition(type, field) {
  625. return type.hasOwnProperty(field) ? type[field] : null;
  626. }
  627. /**
  628. * Read the injectable def (`ɵprov`) for `type` or read the `ɵprov` from one of its ancestors.
  629. *
  630. * @param type A type which may have `ɵprov`, via inheritance.
  631. *
  632. * @deprecated Will be removed in a future version of Angular, where an error will occur in the
  633. * scenario if we find the `ɵprov` on an ancestor only.
  634. */
  635. function getInheritedInjectableDef(type) {
  636. const def = type && (type[NG_PROV_DEF] || type[NG_INJECTABLE_DEF]);
  637. if (def) {
  638. ngDevMode &&
  639. console.warn(`DEPRECATED: DI is instantiating a token "${type.name}" that inherits its @Injectable decorator but does not provide one itself.\n` +
  640. `This will become an error in a future version of Angular. Please add @Injectable() to the "${type.name}" class.`);
  641. return def;
  642. }
  643. else {
  644. return null;
  645. }
  646. }
  647. /**
  648. * Read the injector def type in a way which is immune to accidentally reading inherited value.
  649. *
  650. * @param type type which may have an injector def (`ɵinj`)
  651. */
  652. function getInjectorDef(type) {
  653. return type && (type.hasOwnProperty(NG_INJ_DEF) || type.hasOwnProperty(NG_INJECTOR_DEF))
  654. ? type[NG_INJ_DEF]
  655. : null;
  656. }
  657. const NG_PROV_DEF = getClosureSafeProperty({ ɵprov: getClosureSafeProperty });
  658. const NG_INJ_DEF = getClosureSafeProperty({ ɵinj: getClosureSafeProperty });
  659. // We need to keep these around so we can read off old defs if new defs are unavailable
  660. const NG_INJECTABLE_DEF = getClosureSafeProperty({ ngInjectableDef: getClosureSafeProperty });
  661. const NG_INJECTOR_DEF = getClosureSafeProperty({ ngInjectorDef: getClosureSafeProperty });
  662. /**
  663. * Creates a token that can be used in a DI Provider.
  664. *
  665. * Use an `InjectionToken` whenever the type you are injecting is not reified (does not have a
  666. * runtime representation) such as when injecting an interface, callable type, array or
  667. * parameterized type.
  668. *
  669. * `InjectionToken` is parameterized on `T` which is the type of object which will be returned by
  670. * the `Injector`. This provides an additional level of type safety.
  671. *
  672. * <div class="docs-alert docs-alert-helpful">
  673. *
  674. * **Important Note**: Ensure that you use the same instance of the `InjectionToken` in both the
  675. * provider and the injection call. Creating a new instance of `InjectionToken` in different places,
  676. * even with the same description, will be treated as different tokens by Angular's DI system,
  677. * leading to a `NullInjectorError`.
  678. *
  679. * </div>
  680. *
  681. * {@example injection-token/src/main.ts region='InjectionToken'}
  682. *
  683. * When creating an `InjectionToken`, you can optionally specify a factory function which returns
  684. * (possibly by creating) a default value of the parameterized type `T`. This sets up the
  685. * `InjectionToken` using this factory as a provider as if it was defined explicitly in the
  686. * application's root injector. If the factory function, which takes zero arguments, needs to inject
  687. * dependencies, it can do so using the [`inject`](api/core/inject) function.
  688. * As you can see in the Tree-shakable InjectionToken example below.
  689. *
  690. * Additionally, if a `factory` is specified you can also specify the `providedIn` option, which
  691. * overrides the above behavior and marks the token as belonging to a particular `@NgModule` (note:
  692. * this option is now deprecated). As mentioned above, `'root'` is the default value for
  693. * `providedIn`.
  694. *
  695. * The `providedIn: NgModule` and `providedIn: 'any'` options are deprecated.
  696. *
  697. * @usageNotes
  698. * ### Basic Examples
  699. *
  700. * ### Plain InjectionToken
  701. *
  702. * {@example core/di/ts/injector_spec.ts region='InjectionToken'}
  703. *
  704. * ### Tree-shakable InjectionToken
  705. *
  706. * {@example core/di/ts/injector_spec.ts region='ShakableInjectionToken'}
  707. *
  708. * @publicApi
  709. */
  710. class InjectionToken {
  711. _desc;
  712. /** @internal */
  713. ngMetadataName = 'InjectionToken';
  714. ɵprov;
  715. /**
  716. * @param _desc Description for the token,
  717. * used only for debugging purposes,
  718. * it should but does not need to be unique
  719. * @param options Options for the token's usage, as described above
  720. */
  721. constructor(_desc, options) {
  722. this._desc = _desc;
  723. this.ɵprov = undefined;
  724. if (typeof options == 'number') {
  725. (typeof ngDevMode === 'undefined' || ngDevMode) &&
  726. assertLessThan(options, 0, 'Only negative numbers are supported here');
  727. // This is a special hack to assign __NG_ELEMENT_ID__ to this instance.
  728. // See `InjectorMarkers`
  729. this.__NG_ELEMENT_ID__ = options;
  730. }
  731. else if (options !== undefined) {
  732. this.ɵprov = ɵɵdefineInjectable({
  733. token: this,
  734. providedIn: options.providedIn || 'root',
  735. factory: options.factory,
  736. });
  737. }
  738. }
  739. /**
  740. * @internal
  741. */
  742. get multi() {
  743. return this;
  744. }
  745. toString() {
  746. return `InjectionToken ${this._desc}`;
  747. }
  748. }
  749. let _injectorProfilerContext;
  750. function getInjectorProfilerContext() {
  751. !ngDevMode && throwError('getInjectorProfilerContext should never be called in production mode');
  752. return _injectorProfilerContext;
  753. }
  754. function setInjectorProfilerContext(context) {
  755. !ngDevMode && throwError('setInjectorProfilerContext should never be called in production mode');
  756. const previous = _injectorProfilerContext;
  757. _injectorProfilerContext = context;
  758. return previous;
  759. }
  760. let injectorProfilerCallback = null;
  761. /**
  762. * Sets the callback function which will be invoked during certain DI events within the
  763. * runtime (for example: injecting services, creating injectable instances, configuring providers)
  764. *
  765. * Warning: this function is *INTERNAL* and should not be relied upon in application's code.
  766. * The contract of the function might be changed in any release and/or the function can be removed
  767. * completely.
  768. *
  769. * @param profiler function provided by the caller or null value to disable profiling.
  770. */
  771. const setInjectorProfiler = (injectorProfiler) => {
  772. !ngDevMode && throwError('setInjectorProfiler should never be called in production mode');
  773. injectorProfilerCallback = injectorProfiler;
  774. };
  775. /**
  776. * Injector profiler function which emits on DI events executed by the runtime.
  777. *
  778. * @param event InjectorProfilerEvent corresponding to the DI event being emitted
  779. */
  780. function injectorProfiler(event) {
  781. !ngDevMode && throwError('Injector profiler should never be called in production mode');
  782. if (injectorProfilerCallback != null /* both `null` and `undefined` */) {
  783. injectorProfilerCallback(event);
  784. }
  785. }
  786. /**
  787. * Emits an InjectorProfilerEventType.ProviderConfigured to the injector profiler. The data in the
  788. * emitted event includes the raw provider, as well as the token that provider is providing.
  789. *
  790. * @param eventProvider A provider object
  791. */
  792. function emitProviderConfiguredEvent(eventProvider, isViewProvider = false) {
  793. !ngDevMode && throwError('Injector profiler should never be called in production mode');
  794. let token;
  795. // if the provider is a TypeProvider (typeof provider is function) then the token is the
  796. // provider itself
  797. if (typeof eventProvider === 'function') {
  798. token = eventProvider;
  799. }
  800. // if the provider is an injection token, then the token is the injection token.
  801. else if (eventProvider instanceof InjectionToken) {
  802. token = eventProvider;
  803. }
  804. // in all other cases we can access the token via the `provide` property of the provider
  805. else {
  806. token = resolveForwardRef(eventProvider.provide);
  807. }
  808. let provider = eventProvider;
  809. // Injection tokens may define their own default provider which gets attached to the token itself
  810. // as `ɵprov`. In this case, we want to emit the provider that is attached to the token, not the
  811. // token itself.
  812. if (eventProvider instanceof InjectionToken) {
  813. provider = eventProvider.ɵprov || eventProvider;
  814. }
  815. injectorProfiler({
  816. type: 2 /* InjectorProfilerEventType.ProviderConfigured */,
  817. context: getInjectorProfilerContext(),
  818. providerRecord: { token, provider, isViewProvider },
  819. });
  820. }
  821. /**
  822. * Emits an event to the injector profiler with the instance that was created. Note that
  823. * the injector associated with this emission can be accessed by using getDebugInjectContext()
  824. *
  825. * @param instance an object created by an injector
  826. */
  827. function emitInstanceCreatedByInjectorEvent(instance) {
  828. !ngDevMode && throwError('Injector profiler should never be called in production mode');
  829. injectorProfiler({
  830. type: 1 /* InjectorProfilerEventType.InstanceCreatedByInjector */,
  831. context: getInjectorProfilerContext(),
  832. instance: { value: instance },
  833. });
  834. }
  835. /**
  836. * @param token DI token associated with injected service
  837. * @param value the instance of the injected service (i.e the result of `inject(token)`)
  838. * @param flags the flags that the token was injected with
  839. */
  840. function emitInjectEvent(token, value, flags) {
  841. !ngDevMode && throwError('Injector profiler should never be called in production mode');
  842. injectorProfiler({
  843. type: 0 /* InjectorProfilerEventType.Inject */,
  844. context: getInjectorProfilerContext(),
  845. service: { token, value, flags },
  846. });
  847. }
  848. function emitEffectCreatedEvent(effect) {
  849. !ngDevMode && throwError('Injector profiler should never be called in production mode');
  850. injectorProfiler({
  851. type: 3 /* InjectorProfilerEventType.EffectCreated */,
  852. context: getInjectorProfilerContext(),
  853. effect,
  854. });
  855. }
  856. function runInInjectorProfilerContext(injector, token, callback) {
  857. !ngDevMode &&
  858. throwError('runInInjectorProfilerContext should never be called in production mode');
  859. const prevInjectContext = setInjectorProfilerContext({ injector, token });
  860. try {
  861. callback();
  862. }
  863. finally {
  864. setInjectorProfilerContext(prevInjectContext);
  865. }
  866. }
  867. function isEnvironmentProviders(value) {
  868. return value && !!value.ɵproviders;
  869. }
  870. const NG_COMP_DEF = getClosureSafeProperty({ ɵcmp: getClosureSafeProperty });
  871. const NG_DIR_DEF = getClosureSafeProperty({ ɵdir: getClosureSafeProperty });
  872. const NG_PIPE_DEF = getClosureSafeProperty({ ɵpipe: getClosureSafeProperty });
  873. const NG_MOD_DEF = getClosureSafeProperty({ ɵmod: getClosureSafeProperty });
  874. const NG_FACTORY_DEF = getClosureSafeProperty({ ɵfac: getClosureSafeProperty });
  875. /**
  876. * If a directive is diPublic, bloomAdd sets a property on the type with this constant as
  877. * the key and the directive's unique ID as the value. This allows us to map directives to their
  878. * bloom filter bit for DI.
  879. */
  880. // TODO(misko): This is wrong. The NG_ELEMENT_ID should never be minified.
  881. const NG_ELEMENT_ID = getClosureSafeProperty({ __NG_ELEMENT_ID__: getClosureSafeProperty });
  882. /**
  883. * The `NG_ENV_ID` field on a DI token indicates special processing in the `EnvironmentInjector`:
  884. * getting such tokens from the `EnvironmentInjector` will bypass the standard DI resolution
  885. * strategy and instead will return implementation produced by the `NG_ENV_ID` factory function.
  886. *
  887. * This particular retrieval of DI tokens is mostly done to eliminate circular dependencies and
  888. * improve tree-shaking.
  889. */
  890. const NG_ENV_ID = getClosureSafeProperty({ __NG_ENV_ID__: getClosureSafeProperty });
  891. /**
  892. * Used for stringify render output in Ivy.
  893. * Important! This function is very performance-sensitive and we should
  894. * be extra careful not to introduce megamorphic reads in it.
  895. * Check `core/test/render3/perf/render_stringify` for benchmarks and alternate implementations.
  896. */
  897. function renderStringify(value) {
  898. if (typeof value === 'string')
  899. return value;
  900. if (value == null)
  901. return '';
  902. // Use `String` so that it invokes the `toString` method of the value. Note that this
  903. // appears to be faster than calling `value.toString` (see `render_stringify` benchmark).
  904. return String(value);
  905. }
  906. /**
  907. * Used to stringify a value so that it can be displayed in an error message.
  908. *
  909. * Important! This function contains a megamorphic read and should only be
  910. * used for error messages.
  911. */
  912. function stringifyForError(value) {
  913. if (typeof value === 'function')
  914. return value.name || value.toString();
  915. if (typeof value === 'object' && value != null && typeof value.type === 'function') {
  916. return value.type.name || value.type.toString();
  917. }
  918. return renderStringify(value);
  919. }
  920. /**
  921. * Used to stringify a `Type` and including the file path and line number in which it is defined, if
  922. * possible, for better debugging experience.
  923. *
  924. * Important! This function contains a megamorphic read and should only be used for error messages.
  925. */
  926. function debugStringifyTypeForError(type) {
  927. // TODO(pmvald): Do some refactoring so that we can use getComponentDef here without creating
  928. // circular deps.
  929. let componentDef = type[NG_COMP_DEF] || null;
  930. if (componentDef !== null && componentDef.debugInfo) {
  931. return stringifyTypeFromDebugInfo(componentDef.debugInfo);
  932. }
  933. return stringifyForError(type);
  934. }
  935. // TODO(pmvald): Do some refactoring so that we can use the type ClassDebugInfo for the param
  936. // debugInfo here without creating circular deps.
  937. function stringifyTypeFromDebugInfo(debugInfo) {
  938. if (!debugInfo.filePath || !debugInfo.lineNumber) {
  939. return debugInfo.className;
  940. }
  941. else {
  942. return `${debugInfo.className} (at ${debugInfo.filePath}:${debugInfo.lineNumber})`;
  943. }
  944. }
  945. /** Called when directives inject each other (creating a circular dependency) */
  946. function throwCyclicDependencyError(token, path) {
  947. throw new RuntimeError(-200 /* RuntimeErrorCode.CYCLIC_DI_DEPENDENCY */, ngDevMode
  948. ? `Circular dependency in DI detected for ${token}${path ? `. Dependency path: ${path.join(' > ')} > ${token}` : ''}`
  949. : token);
  950. }
  951. function throwMixedMultiProviderError() {
  952. throw new Error(`Cannot mix multi providers and regular providers`);
  953. }
  954. function throwInvalidProviderError(ngModuleType, providers, provider) {
  955. if (ngModuleType && providers) {
  956. const providerDetail = providers.map((v) => (v == provider ? '?' + provider + '?' : '...'));
  957. throw new Error(`Invalid provider for the NgModule '${stringify(ngModuleType)}' - only instances of Provider and Type are allowed, got: [${providerDetail.join(', ')}]`);
  958. }
  959. else if (isEnvironmentProviders(provider)) {
  960. if (provider.ɵfromNgModule) {
  961. throw new RuntimeError(207 /* RuntimeErrorCode.PROVIDER_IN_WRONG_CONTEXT */, `Invalid providers from 'importProvidersFrom' present in a non-environment injector. 'importProvidersFrom' can't be used for component providers.`);
  962. }
  963. else {
  964. throw new RuntimeError(207 /* RuntimeErrorCode.PROVIDER_IN_WRONG_CONTEXT */, `Invalid providers present in a non-environment injector. 'EnvironmentProviders' can't be used for component providers.`);
  965. }
  966. }
  967. else {
  968. throw new Error('Invalid provider');
  969. }
  970. }
  971. /** Throws an error when a token is not found in DI. */
  972. function throwProviderNotFoundError(token, injectorName) {
  973. const errorMessage = ngDevMode &&
  974. `No provider for ${stringifyForError(token)} found${injectorName ? ` in ${injectorName}` : ''}`;
  975. throw new RuntimeError(-201 /* RuntimeErrorCode.PROVIDER_NOT_FOUND */, errorMessage);
  976. }
  977. /**
  978. * Injection flags for DI.
  979. *
  980. * @publicApi
  981. * @deprecated use an options object for [`inject`](api/core/inject) instead.
  982. */
  983. var InjectFlags;
  984. (function (InjectFlags) {
  985. // TODO(alxhub): make this 'const' (and remove `InternalInjectFlags` enum) when ngc no longer
  986. // writes exports of it into ngfactory files.
  987. /** Check self and check parent injector if needed */
  988. InjectFlags[InjectFlags["Default"] = 0] = "Default";
  989. /**
  990. * Specifies that an injector should retrieve a dependency from any injector until reaching the
  991. * host element of the current component. (Only used with Element Injector)
  992. */
  993. InjectFlags[InjectFlags["Host"] = 1] = "Host";
  994. /** Don't ascend to ancestors of the node requesting injection. */
  995. InjectFlags[InjectFlags["Self"] = 2] = "Self";
  996. /** Skip the node that is requesting injection. */
  997. InjectFlags[InjectFlags["SkipSelf"] = 4] = "SkipSelf";
  998. /** Inject `defaultValue` instead if token not found. */
  999. InjectFlags[InjectFlags["Optional"] = 8] = "Optional";
  1000. })(InjectFlags || (InjectFlags = {}));
  1001. /**
  1002. * Current implementation of inject.
  1003. *
  1004. * By default, it is `injectInjectorOnly`, which makes it `Injector`-only aware. It can be changed
  1005. * to `directiveInject`, which brings in the `NodeInjector` system of ivy. It is designed this
  1006. * way for two reasons:
  1007. * 1. `Injector` should not depend on ivy logic.
  1008. * 2. To maintain tree shake-ability we don't want to bring in unnecessary code.
  1009. */
  1010. let _injectImplementation;
  1011. function getInjectImplementation() {
  1012. return _injectImplementation;
  1013. }
  1014. /**
  1015. * Sets the current inject implementation.
  1016. */
  1017. function setInjectImplementation(impl) {
  1018. const previous = _injectImplementation;
  1019. _injectImplementation = impl;
  1020. return previous;
  1021. }
  1022. /**
  1023. * Injects `root` tokens in limp mode.
  1024. *
  1025. * If no injector exists, we can still inject tree-shakable providers which have `providedIn` set to
  1026. * `"root"`. This is known as the limp mode injection. In such case the value is stored in the
  1027. * injectable definition.
  1028. */
  1029. function injectRootLimpMode(token, notFoundValue, flags) {
  1030. const injectableDef = getInjectableDef(token);
  1031. if (injectableDef && injectableDef.providedIn == 'root') {
  1032. return injectableDef.value === undefined
  1033. ? (injectableDef.value = injectableDef.factory())
  1034. : injectableDef.value;
  1035. }
  1036. if (flags & InjectFlags.Optional)
  1037. return null;
  1038. if (notFoundValue !== undefined)
  1039. return notFoundValue;
  1040. throwProviderNotFoundError(token, 'Injector');
  1041. }
  1042. /**
  1043. * Assert that `_injectImplementation` is not `fn`.
  1044. *
  1045. * This is useful, to prevent infinite recursion.
  1046. *
  1047. * @param fn Function which it should not equal to
  1048. */
  1049. function assertInjectImplementationNotEqual(fn) {
  1050. ngDevMode &&
  1051. assertNotEqual(_injectImplementation, fn, 'Calling ɵɵinject would cause infinite recursion');
  1052. }
  1053. const _THROW_IF_NOT_FOUND = {};
  1054. const THROW_IF_NOT_FOUND = _THROW_IF_NOT_FOUND;
  1055. /*
  1056. * Name of a property (that we patch onto DI decorator), which is used as an annotation of which
  1057. * InjectFlag this decorator represents. This allows to avoid direct references to the DI decorators
  1058. * in the code, thus making them tree-shakable.
  1059. */
  1060. const DI_DECORATOR_FLAG = '__NG_DI_FLAG__';
  1061. class RetrievingInjector {
  1062. injector;
  1063. constructor(injector) {
  1064. this.injector = injector;
  1065. }
  1066. retrieve(token, options) {
  1067. const ngOptions = options;
  1068. return this.injector.get(token, ngOptions.optional ? NOT_FOUND$1 : THROW_IF_NOT_FOUND, ngOptions);
  1069. }
  1070. }
  1071. const NG_TEMP_TOKEN_PATH = 'ngTempTokenPath';
  1072. const NG_TOKEN_PATH = 'ngTokenPath';
  1073. const NEW_LINE = /\n/gm;
  1074. const NO_NEW_LINE = 'ɵ';
  1075. const SOURCE = '__source';
  1076. function injectInjectorOnly(token, flags = InjectFlags.Default) {
  1077. if (getCurrentInjector() === undefined) {
  1078. throw new RuntimeError(-203 /* RuntimeErrorCode.MISSING_INJECTION_CONTEXT */, ngDevMode &&
  1079. `The \`${stringify(token)}\` token injection failed. \`inject()\` function must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with \`runInInjectionContext\`.`);
  1080. }
  1081. else if (getCurrentInjector() === null) {
  1082. return injectRootLimpMode(token, undefined, flags);
  1083. }
  1084. else {
  1085. const currentInjector = getCurrentInjector();
  1086. let injector;
  1087. if (currentInjector instanceof RetrievingInjector) {
  1088. injector = currentInjector.injector;
  1089. }
  1090. else {
  1091. injector = currentInjector;
  1092. }
  1093. const value = injector.get(token, flags & InjectFlags.Optional ? null : undefined, flags);
  1094. ngDevMode && emitInjectEvent(token, value, flags);
  1095. return value;
  1096. }
  1097. }
  1098. function ɵɵinject(token, flags = InjectFlags.Default) {
  1099. return (getInjectImplementation() || injectInjectorOnly)(resolveForwardRef(token), flags);
  1100. }
  1101. /**
  1102. * Throws an error indicating that a factory function could not be generated by the compiler for a
  1103. * particular class.
  1104. *
  1105. * The name of the class is not mentioned here, but will be in the generated factory function name
  1106. * and thus in the stack trace.
  1107. *
  1108. * @codeGenApi
  1109. */
  1110. function ɵɵinvalidFactoryDep(index) {
  1111. throw new RuntimeError(202 /* RuntimeErrorCode.INVALID_FACTORY_DEPENDENCY */, ngDevMode &&
  1112. `This constructor is not compatible with Angular Dependency Injection because its dependency at index ${index} of the parameter list is invalid.
  1113. This can happen if the dependency type is a primitive like a string or if an ancestor of this class is missing an Angular decorator.
  1114. Please check that 1) the type for the parameter at index ${index} is correct and 2) the correct Angular decorators are defined for this class and its ancestors.`);
  1115. }
  1116. /**
  1117. * Injects a token from the currently active injector.
  1118. * `inject` is only supported in an [injection context](guide/di/dependency-injection-context). It
  1119. * can be used during:
  1120. * - Construction (via the `constructor`) of a class being instantiated by the DI system, such
  1121. * as an `@Injectable` or `@Component`.
  1122. * - In the initializer for fields of such classes.
  1123. * - In the factory function specified for `useFactory` of a `Provider` or an `@Injectable`.
  1124. * - In the `factory` function specified for an `InjectionToken`.
  1125. * - In a stackframe of a function call in a DI context
  1126. *
  1127. * @param token A token that represents a dependency that should be injected.
  1128. * @param flags Optional flags that control how injection is executed.
  1129. * The flags correspond to injection strategies that can be specified with
  1130. * parameter decorators `@Host`, `@Self`, `@SkipSelf`, and `@Optional`.
  1131. * @returns the injected value if operation is successful, `null` otherwise.
  1132. * @throws if called outside of a supported context.
  1133. *
  1134. * @usageNotes
  1135. * In practice the `inject()` calls are allowed in a constructor, a constructor parameter and a
  1136. * field initializer:
  1137. *
  1138. * ```ts
  1139. * @Injectable({providedIn: 'root'})
  1140. * export class Car {
  1141. * radio: Radio|undefined;
  1142. * // OK: field initializer
  1143. * spareTyre = inject(Tyre);
  1144. *
  1145. * constructor() {
  1146. * // OK: constructor body
  1147. * this.radio = inject(Radio);
  1148. * }
  1149. * }
  1150. * ```
  1151. *
  1152. * It is also legal to call `inject` from a provider's factory:
  1153. *
  1154. * ```ts
  1155. * providers: [
  1156. * {provide: Car, useFactory: () => {
  1157. * // OK: a class factory
  1158. * const engine = inject(Engine);
  1159. * return new Car(engine);
  1160. * }}
  1161. * ]
  1162. * ```
  1163. *
  1164. * Calls to the `inject()` function outside of the class creation context will result in error. Most
  1165. * notably, calls to `inject()` are disallowed after a class instance was created, in methods
  1166. * (including lifecycle hooks):
  1167. *
  1168. * ```ts
  1169. * @Component({ ... })
  1170. * export class CarComponent {
  1171. * ngOnInit() {
  1172. * // ERROR: too late, the component instance was already created
  1173. * const engine = inject(Engine);
  1174. * engine.start();
  1175. * }
  1176. * }
  1177. * ```
  1178. *
  1179. * @publicApi
  1180. */
  1181. function inject(token, flags = InjectFlags.Default) {
  1182. // The `as any` here _shouldn't_ be necessary, but without it JSCompiler
  1183. // throws a disambiguation error due to the multiple signatures.
  1184. return ɵɵinject(token, convertToBitFlags(flags));
  1185. }
  1186. // Converts object-based DI flags (`InjectOptions`) to bit flags (`InjectFlags`).
  1187. function convertToBitFlags(flags) {
  1188. if (typeof flags === 'undefined' || typeof flags === 'number') {
  1189. return flags;
  1190. }
  1191. // While TypeScript doesn't accept it without a cast, bitwise OR with false-y values in
  1192. // JavaScript is a no-op. We can use that for a very codesize-efficient conversion from
  1193. // `InjectOptions` to `InjectFlags`.
  1194. return (0 /* InternalInjectFlags.Default */ | // comment to force a line break in the formatter
  1195. (flags.optional && 8 /* InternalInjectFlags.Optional */) |
  1196. (flags.host && 1 /* InternalInjectFlags.Host */) |
  1197. (flags.self && 2 /* InternalInjectFlags.Self */) |
  1198. (flags.skipSelf && 4 /* InternalInjectFlags.SkipSelf */));
  1199. }
  1200. function injectArgs(types) {
  1201. const args = [];
  1202. for (let i = 0; i < types.length; i++) {
  1203. const arg = resolveForwardRef(types[i]);
  1204. if (Array.isArray(arg)) {
  1205. if (arg.length === 0) {
  1206. throw new RuntimeError(900 /* RuntimeErrorCode.INVALID_DIFFER_INPUT */, ngDevMode && 'Arguments array must have arguments.');
  1207. }
  1208. let type = undefined;
  1209. let flags = InjectFlags.Default;
  1210. for (let j = 0; j < arg.length; j++) {
  1211. const meta = arg[j];
  1212. const flag = getInjectFlag(meta);
  1213. if (typeof flag === 'number') {
  1214. // Special case when we handle @Inject decorator.
  1215. if (flag === -1 /* DecoratorFlags.Inject */) {
  1216. type = meta.token;
  1217. }
  1218. else {
  1219. flags |= flag;
  1220. }
  1221. }
  1222. else {
  1223. type = meta;
  1224. }
  1225. }
  1226. args.push(ɵɵinject(type, flags));
  1227. }
  1228. else {
  1229. args.push(ɵɵinject(arg));
  1230. }
  1231. }
  1232. return args;
  1233. }
  1234. /**
  1235. * Attaches a given InjectFlag to a given decorator using monkey-patching.
  1236. * Since DI decorators can be used in providers `deps` array (when provider is configured using
  1237. * `useFactory`) without initialization (e.g. `Host`) and as an instance (e.g. `new Host()`), we
  1238. * attach the flag to make it available both as a static property and as a field on decorator
  1239. * instance.
  1240. *
  1241. * @param decorator Provided DI decorator.
  1242. * @param flag InjectFlag that should be applied.
  1243. */
  1244. function attachInjectFlag(decorator, flag) {
  1245. decorator[DI_DECORATOR_FLAG] = flag;
  1246. decorator.prototype[DI_DECORATOR_FLAG] = flag;
  1247. return decorator;
  1248. }
  1249. /**
  1250. * Reads monkey-patched property that contains InjectFlag attached to a decorator.
  1251. *
  1252. * @param token Token that may contain monkey-patched DI flags property.
  1253. */
  1254. function getInjectFlag(token) {
  1255. return token[DI_DECORATOR_FLAG];
  1256. }
  1257. function catchInjectorError(e, token, injectorErrorName, source) {
  1258. const tokenPath = e[NG_TEMP_TOKEN_PATH];
  1259. if (token[SOURCE]) {
  1260. tokenPath.unshift(token[SOURCE]);
  1261. }
  1262. e.message = formatError('\n' + e.message, tokenPath, injectorErrorName, source);
  1263. e[NG_TOKEN_PATH] = tokenPath;
  1264. e[NG_TEMP_TOKEN_PATH] = null;
  1265. throw e;
  1266. }
  1267. function formatError(text, obj, injectorErrorName, source = null) {
  1268. text = text && text.charAt(0) === '\n' && text.charAt(1) == NO_NEW_LINE ? text.slice(2) : text;
  1269. let context = stringify(obj);
  1270. if (Array.isArray(obj)) {
  1271. context = obj.map(stringify).join(' -> ');
  1272. }
  1273. else if (typeof obj === 'object') {
  1274. let parts = [];
  1275. for (let key in obj) {
  1276. if (obj.hasOwnProperty(key)) {
  1277. let value = obj[key];
  1278. parts.push(key + ':' + (typeof value === 'string' ? JSON.stringify(value) : stringify(value)));
  1279. }
  1280. }
  1281. context = `{${parts.join(', ')}}`;
  1282. }
  1283. return `${injectorErrorName}${source ? '(' + source + ')' : ''}[${context}]: ${text.replace(NEW_LINE, '\n ')}`;
  1284. }
  1285. /**
  1286. * Inject decorator and metadata.
  1287. *
  1288. * @Annotation
  1289. * @publicApi
  1290. */
  1291. const Inject = attachInjectFlag(
  1292. // Disable tslint because `DecoratorFlags` is a const enum which gets inlined.
  1293. makeParamDecorator('Inject', (token) => ({ token })), -1 /* DecoratorFlags.Inject */);
  1294. /**
  1295. * Optional decorator and metadata.
  1296. *
  1297. * @Annotation
  1298. * @publicApi
  1299. */
  1300. const Optional =
  1301. // Disable tslint because `InternalInjectFlags` is a const enum which gets inlined.
  1302. // tslint:disable-next-line: no-toplevel-property-access
  1303. attachInjectFlag(makeParamDecorator('Optional'), 8 /* InternalInjectFlags.Optional */);
  1304. /**
  1305. * Self decorator and metadata.
  1306. *
  1307. * @Annotation
  1308. * @publicApi
  1309. */
  1310. const Self =
  1311. // Disable tslint because `InternalInjectFlags` is a const enum which gets inlined.
  1312. // tslint:disable-next-line: no-toplevel-property-access
  1313. attachInjectFlag(makeParamDecorator('Self'), 2 /* InternalInjectFlags.Self */);
  1314. /**
  1315. * `SkipSelf` decorator and metadata.
  1316. *
  1317. * @Annotation
  1318. * @publicApi
  1319. */
  1320. const SkipSelf =
  1321. // Disable tslint because `InternalInjectFlags` is a const enum which gets inlined.
  1322. // tslint:disable-next-line: no-toplevel-property-access
  1323. attachInjectFlag(makeParamDecorator('SkipSelf'), 4 /* InternalInjectFlags.SkipSelf */);
  1324. /**
  1325. * Host decorator and metadata.
  1326. *
  1327. * @Annotation
  1328. * @publicApi
  1329. */
  1330. const Host =
  1331. // Disable tslint because `InternalInjectFlags` is a const enum which gets inlined.
  1332. // tslint:disable-next-line: no-toplevel-property-access
  1333. attachInjectFlag(makeParamDecorator('Host'), 1 /* InternalInjectFlags.Host */);
  1334. function getFactoryDef(type, throwNotFound) {
  1335. const hasFactoryDef = type.hasOwnProperty(NG_FACTORY_DEF);
  1336. if (!hasFactoryDef && throwNotFound === true && ngDevMode) {
  1337. throw new Error(`Type ${stringify(type)} does not have 'ɵfac' property.`);
  1338. }
  1339. return hasFactoryDef ? type[NG_FACTORY_DEF] : null;
  1340. }
  1341. /**
  1342. * Determines if the contents of two arrays is identical
  1343. *
  1344. * @param a first array
  1345. * @param b second array
  1346. * @param identityAccessor Optional function for extracting stable object identity from a value in
  1347. * the array.
  1348. */
  1349. function arrayEquals(a, b, identityAccessor) {
  1350. if (a.length !== b.length)
  1351. return false;
  1352. for (let i = 0; i < a.length; i++) {
  1353. let valueA = a[i];
  1354. let valueB = b[i];
  1355. if (identityAccessor) {
  1356. valueA = identityAccessor(valueA);
  1357. valueB = identityAccessor(valueB);
  1358. }
  1359. if (valueB !== valueA) {
  1360. return false;
  1361. }
  1362. }
  1363. return true;
  1364. }
  1365. /**
  1366. * Flattens an array.
  1367. */
  1368. function flatten(list) {
  1369. return list.flat(Number.POSITIVE_INFINITY);
  1370. }
  1371. function deepForEach(input, fn) {
  1372. input.forEach((value) => (Array.isArray(value) ? deepForEach(value, fn) : fn(value)));
  1373. }
  1374. function addToArray(arr, index, value) {
  1375. // perf: array.push is faster than array.splice!
  1376. if (index >= arr.length) {
  1377. arr.push(value);
  1378. }
  1379. else {
  1380. arr.splice(index, 0, value);
  1381. }
  1382. }
  1383. function removeFromArray(arr, index) {
  1384. // perf: array.pop is faster than array.splice!
  1385. if (index >= arr.length - 1) {
  1386. return arr.pop();
  1387. }
  1388. else {
  1389. return arr.splice(index, 1)[0];
  1390. }
  1391. }
  1392. function newArray(size, value) {
  1393. const list = [];
  1394. for (let i = 0; i < size; i++) {
  1395. list.push(value);
  1396. }
  1397. return list;
  1398. }
  1399. /**
  1400. * Remove item from array (Same as `Array.splice()` but faster.)
  1401. *
  1402. * `Array.splice()` is not as fast because it has to allocate an array for the elements which were
  1403. * removed. This causes memory pressure and slows down code when most of the time we don't
  1404. * care about the deleted items array.
  1405. *
  1406. * https://jsperf.com/fast-array-splice (About 20x faster)
  1407. *
  1408. * @param array Array to splice
  1409. * @param index Index of element in array to remove.
  1410. * @param count Number of items to remove.
  1411. */
  1412. function arraySplice(array, index, count) {
  1413. const length = array.length - count;
  1414. while (index < length) {
  1415. array[index] = array[index + count];
  1416. index++;
  1417. }
  1418. while (count--) {
  1419. array.pop(); // shrink the array
  1420. }
  1421. }
  1422. /**
  1423. * Same as `Array.splice2(index, 0, value1, value2)` but faster.
  1424. *
  1425. * `Array.splice()` is not fast because it has to allocate an array for the elements which were
  1426. * removed. This causes memory pressure and slows down code when most of the time we don't
  1427. * care about the deleted items array.
  1428. *
  1429. * @param array Array to splice.
  1430. * @param index Index in array where the `value` should be added.
  1431. * @param value1 Value to add to array.
  1432. * @param value2 Value to add to array.
  1433. */
  1434. function arrayInsert2(array, index, value1, value2) {
  1435. ngDevMode && assertLessThanOrEqual(index, array.length, "Can't insert past array end.");
  1436. let end = array.length;
  1437. if (end == index) {
  1438. // inserting at the end.
  1439. array.push(value1, value2);
  1440. }
  1441. else if (end === 1) {
  1442. // corner case when we have less items in array than we have items to insert.
  1443. array.push(value2, array[0]);
  1444. array[0] = value1;
  1445. }
  1446. else {
  1447. end--;
  1448. array.push(array[end - 1], array[end]);
  1449. while (end > index) {
  1450. const previousEnd = end - 2;
  1451. array[end] = array[previousEnd];
  1452. end--;
  1453. }
  1454. array[index] = value1;
  1455. array[index + 1] = value2;
  1456. }
  1457. }
  1458. /**
  1459. * Set a `value` for a `key`.
  1460. *
  1461. * @param keyValueArray to modify.
  1462. * @param key The key to locate or create.
  1463. * @param value The value to set for a `key`.
  1464. * @returns index (always even) of where the value vas set.
  1465. */
  1466. function keyValueArraySet(keyValueArray, key, value) {
  1467. let index = keyValueArrayIndexOf(keyValueArray, key);
  1468. if (index >= 0) {
  1469. // if we found it set it.
  1470. keyValueArray[index | 1] = value;
  1471. }
  1472. else {
  1473. index = ~index;
  1474. arrayInsert2(keyValueArray, index, key, value);
  1475. }
  1476. return index;
  1477. }
  1478. /**
  1479. * Retrieve a `value` for a `key` (on `undefined` if not found.)
  1480. *
  1481. * @param keyValueArray to search.
  1482. * @param key The key to locate.
  1483. * @return The `value` stored at the `key` location or `undefined if not found.
  1484. */
  1485. function keyValueArrayGet(keyValueArray, key) {
  1486. const index = keyValueArrayIndexOf(keyValueArray, key);
  1487. if (index >= 0) {
  1488. // if we found it retrieve it.
  1489. return keyValueArray[index | 1];
  1490. }
  1491. return undefined;
  1492. }
  1493. /**
  1494. * Retrieve a `key` index value in the array or `-1` if not found.
  1495. *
  1496. * @param keyValueArray to search.
  1497. * @param key The key to locate.
  1498. * @returns index of where the key is (or should have been.)
  1499. * - positive (even) index if key found.
  1500. * - negative index if key not found. (`~index` (even) to get the index where it should have
  1501. * been inserted.)
  1502. */
  1503. function keyValueArrayIndexOf(keyValueArray, key) {
  1504. return _arrayIndexOfSorted(keyValueArray, key, 1);
  1505. }
  1506. /**
  1507. * INTERNAL: Get an index of an `value` in a sorted `array` by grouping search by `shift`.
  1508. *
  1509. * NOTE:
  1510. * - This uses binary search algorithm for fast removals.
  1511. *
  1512. * @param array A sorted array to binary search.
  1513. * @param value The value to look for.
  1514. * @param shift grouping shift.
  1515. * - `0` means look at every location
  1516. * - `1` means only look at every other (even) location (the odd locations are to be ignored as
  1517. * they are values.)
  1518. * @returns index of the value.
  1519. * - positive index if value found.
  1520. * - negative index if value not found. (`~index` to get the value where it should have been
  1521. * inserted)
  1522. */
  1523. function _arrayIndexOfSorted(array, value, shift) {
  1524. ngDevMode && assertEqual(Array.isArray(array), true, 'Expecting an array');
  1525. let start = 0;
  1526. let end = array.length >> shift;
  1527. while (end !== start) {
  1528. const middle = start + ((end - start) >> 1); // find the middle.
  1529. const current = array[middle << shift];
  1530. if (value === current) {
  1531. return middle << shift;
  1532. }
  1533. else if (current > value) {
  1534. end = middle;
  1535. }
  1536. else {
  1537. start = middle + 1; // We already searched middle so make it non-inclusive by adding 1
  1538. }
  1539. }
  1540. return ~(end << shift);
  1541. }
  1542. /**
  1543. * This file contains reuseable "empty" symbols that can be used as default return values
  1544. * in different parts of the rendering code. Because the same symbols are returned, this
  1545. * allows for identity checks against these values to be consistently used by the framework
  1546. * code.
  1547. */
  1548. const EMPTY_OBJ = {};
  1549. const EMPTY_ARRAY = [];
  1550. // freezing the values prevents any code from accidentally inserting new values in
  1551. if ((typeof ngDevMode === 'undefined' || ngDevMode) && initNgDevMode()) {
  1552. // These property accesses can be ignored because ngDevMode will be set to false
  1553. // when optimizing code and the whole if statement will be dropped.
  1554. // tslint:disable-next-line:no-toplevel-property-access
  1555. Object.freeze(EMPTY_OBJ);
  1556. // tslint:disable-next-line:no-toplevel-property-access
  1557. Object.freeze(EMPTY_ARRAY);
  1558. }
  1559. /**
  1560. * A multi-provider token for initialization functions that will run upon construction of an
  1561. * environment injector.
  1562. *
  1563. * @deprecated from v19.0.0, use provideEnvironmentInitializer instead
  1564. *
  1565. * @see {@link provideEnvironmentInitializer}
  1566. *
  1567. * Note: As opposed to the `APP_INITIALIZER` token, the `ENVIRONMENT_INITIALIZER` functions are not awaited,
  1568. * hence they should not be `async`.
  1569. *
  1570. * @publicApi
  1571. */
  1572. const ENVIRONMENT_INITIALIZER = new InjectionToken(ngDevMode ? 'ENVIRONMENT_INITIALIZER' : '');
  1573. /**
  1574. * An InjectionToken that gets the current `Injector` for `createInjector()`-style injectors.
  1575. *
  1576. * Requesting this token instead of `Injector` allows `StaticInjector` to be tree-shaken from a
  1577. * project.
  1578. *
  1579. * @publicApi
  1580. */
  1581. const INJECTOR$1 = new InjectionToken(ngDevMode ? 'INJECTOR' : '',
  1582. // Disable tslint because this is const enum which gets inlined not top level prop access.
  1583. // tslint:disable-next-line: no-toplevel-property-access
  1584. -1 /* InjectorMarkers.Injector */);
  1585. const INJECTOR_DEF_TYPES = new InjectionToken(ngDevMode ? 'INJECTOR_DEF_TYPES' : '');
  1586. class NullInjector {
  1587. get(token, notFoundValue = THROW_IF_NOT_FOUND) {
  1588. if (notFoundValue === THROW_IF_NOT_FOUND) {
  1589. const error = new Error(`NullInjectorError: No provider for ${stringify(token)}!`);
  1590. error.name = 'NullInjectorError';
  1591. throw error;
  1592. }
  1593. return notFoundValue;
  1594. }
  1595. }
  1596. function getNgModuleDef(type, throwNotFound) {
  1597. const ngModuleDef = type[NG_MOD_DEF] || null;
  1598. if (!ngModuleDef && throwNotFound === true) {
  1599. throw new Error(`Type ${stringify(type)} does not have 'ɵmod' property.`);
  1600. }
  1601. return ngModuleDef;
  1602. }
  1603. /**
  1604. * The following getter methods retrieve the definition from the type. Currently the retrieval
  1605. * honors inheritance, but in the future we may change the rule to require that definitions are
  1606. * explicit. This would require some sort of migration strategy.
  1607. */
  1608. function getComponentDef(type) {
  1609. return type[NG_COMP_DEF] || null;
  1610. }
  1611. function getDirectiveDef(type) {
  1612. return type[NG_DIR_DEF] || null;
  1613. }
  1614. function getPipeDef$1(type) {
  1615. return type[NG_PIPE_DEF] || null;
  1616. }
  1617. /**
  1618. * Checks whether a given Component, Directive or Pipe is marked as standalone.
  1619. * This will return false if passed anything other than a Component, Directive, or Pipe class
  1620. * See [this guide](guide/components/importing) for additional information:
  1621. *
  1622. * @param type A reference to a Component, Directive or Pipe.
  1623. * @publicApi
  1624. */
  1625. function isStandalone(type) {
  1626. const def = getComponentDef(type) || getDirectiveDef(type) || getPipeDef$1(type);
  1627. return def !== null && def.standalone;
  1628. }
  1629. /**
  1630. * Wrap an array of `Provider`s into `EnvironmentProviders`, preventing them from being accidentally
  1631. * referenced in `@Component` in a component injector.
  1632. */
  1633. function makeEnvironmentProviders(providers) {
  1634. return {
  1635. ɵproviders: providers,
  1636. };
  1637. }
  1638. /**
  1639. * @description
  1640. * This function is used to provide initialization functions that will be executed upon construction
  1641. * of an environment injector.
  1642. *
  1643. * Note that the provided initializer is run in the injection context.
  1644. *
  1645. * Previously, this was achieved using the `ENVIRONMENT_INITIALIZER` token which is now deprecated.
  1646. *
  1647. * @see {@link ENVIRONMENT_INITIALIZER}
  1648. *
  1649. * @usageNotes
  1650. * The following example illustrates how to configure an initialization function using
  1651. * `provideEnvironmentInitializer()`
  1652. * ```ts
  1653. * createEnvironmentInjector(
  1654. * [
  1655. * provideEnvironmentInitializer(() => {
  1656. * console.log('environment initialized');
  1657. * }),
  1658. * ],
  1659. * parentInjector
  1660. * );
  1661. * ```
  1662. *
  1663. * @publicApi
  1664. */
  1665. function provideEnvironmentInitializer(initializerFn) {
  1666. return makeEnvironmentProviders([
  1667. {
  1668. provide: ENVIRONMENT_INITIALIZER,
  1669. multi: true,
  1670. useValue: initializerFn,
  1671. },
  1672. ]);
  1673. }
  1674. /**
  1675. * Collects providers from all NgModules and standalone components, including transitively imported
  1676. * ones.
  1677. *
  1678. * Providers extracted via `importProvidersFrom` are only usable in an application injector or
  1679. * another environment injector (such as a route injector). They should not be used in component
  1680. * providers.
  1681. *
  1682. * More information about standalone components can be found in [this
  1683. * guide](guide/components/importing).
  1684. *
  1685. * @usageNotes
  1686. * The results of the `importProvidersFrom` call can be used in the `bootstrapApplication` call:
  1687. *
  1688. * ```ts
  1689. * await bootstrapApplication(RootComponent, {
  1690. * providers: [
  1691. * importProvidersFrom(NgModuleOne, NgModuleTwo)
  1692. * ]
  1693. * });
  1694. * ```
  1695. *
  1696. * You can also use the `importProvidersFrom` results in the `providers` field of a route, when a
  1697. * standalone component is used:
  1698. *
  1699. * ```ts
  1700. * export const ROUTES: Route[] = [
  1701. * {
  1702. * path: 'foo',
  1703. * providers: [
  1704. * importProvidersFrom(NgModuleOne, NgModuleTwo)
  1705. * ],
  1706. * component: YourStandaloneComponent
  1707. * }
  1708. * ];
  1709. * ```
  1710. *
  1711. * @returns Collected providers from the specified list of types.
  1712. * @publicApi
  1713. */
  1714. function importProvidersFrom(...sources) {
  1715. return {
  1716. ɵproviders: internalImportProvidersFrom(true, sources),
  1717. ɵfromNgModule: true,
  1718. };
  1719. }
  1720. function internalImportProvidersFrom(checkForStandaloneCmp, ...sources) {
  1721. const providersOut = [];
  1722. const dedup = new Set(); // already seen types
  1723. let injectorTypesWithProviders;
  1724. const collectProviders = (provider) => {
  1725. providersOut.push(provider);
  1726. };
  1727. deepForEach(sources, (source) => {
  1728. if ((typeof ngDevMode === 'undefined' || ngDevMode) && checkForStandaloneCmp) {
  1729. const cmpDef = getComponentDef(source);
  1730. if (cmpDef?.standalone) {
  1731. throw new RuntimeError(800 /* RuntimeErrorCode.IMPORT_PROVIDERS_FROM_STANDALONE */, `Importing providers supports NgModule or ModuleWithProviders but got a standalone component "${stringifyForError(source)}"`);
  1732. }
  1733. }
  1734. // Narrow `source` to access the internal type analogue for `ModuleWithProviders`.
  1735. const internalSource = source;
  1736. if (walkProviderTree(internalSource, collectProviders, [], dedup)) {
  1737. injectorTypesWithProviders ||= [];
  1738. injectorTypesWithProviders.push(internalSource);
  1739. }
  1740. });
  1741. // Collect all providers from `ModuleWithProviders` types.
  1742. if (injectorTypesWithProviders !== undefined) {
  1743. processInjectorTypesWithProviders(injectorTypesWithProviders, collectProviders);
  1744. }
  1745. return providersOut;
  1746. }
  1747. /**
  1748. * Collects all providers from the list of `ModuleWithProviders` and appends them to the provided
  1749. * array.
  1750. */
  1751. function processInjectorTypesWithProviders(typesWithProviders, visitor) {
  1752. for (let i = 0; i < typesWithProviders.length; i++) {
  1753. const { ngModule, providers } = typesWithProviders[i];
  1754. deepForEachProvider(providers, (provider) => {
  1755. ngDevMode && validateProvider(provider, providers || EMPTY_ARRAY, ngModule);
  1756. visitor(provider, ngModule);
  1757. });
  1758. }
  1759. }
  1760. /**
  1761. * The logic visits an `InjectorType`, an `InjectorTypeWithProviders`, or a standalone
  1762. * `ComponentType`, and all of its transitive providers and collects providers.
  1763. *
  1764. * If an `InjectorTypeWithProviders` that declares providers besides the type is specified,
  1765. * the function will return "true" to indicate that the providers of the type definition need
  1766. * to be processed. This allows us to process providers of injector types after all imports of
  1767. * an injector definition are processed. (following View Engine semantics: see FW-1349)
  1768. */
  1769. function walkProviderTree(container, visitor, parents, dedup) {
  1770. container = resolveForwardRef(container);
  1771. if (!container)
  1772. return false;
  1773. // The actual type which had the definition. Usually `container`, but may be an unwrapped type
  1774. // from `InjectorTypeWithProviders`.
  1775. let defType = null;
  1776. let injDef = getInjectorDef(container);
  1777. const cmpDef = !injDef && getComponentDef(container);
  1778. if (!injDef && !cmpDef) {
  1779. // `container` is not an injector type or a component type. It might be:
  1780. // * An `InjectorTypeWithProviders` that wraps an injector type.
  1781. // * A standalone directive or pipe that got pulled in from a standalone component's
  1782. // dependencies.
  1783. // Try to unwrap it as an `InjectorTypeWithProviders` first.
  1784. const ngModule = container
  1785. .ngModule;
  1786. injDef = getInjectorDef(ngModule);
  1787. if (injDef) {
  1788. defType = ngModule;
  1789. }
  1790. else {
  1791. // Not a component or injector type, so ignore it.
  1792. return false;
  1793. }
  1794. }
  1795. else if (cmpDef && !cmpDef.standalone) {
  1796. return false;
  1797. }
  1798. else {
  1799. defType = container;
  1800. }
  1801. // Check for circular dependencies.
  1802. if (ngDevMode && parents.indexOf(defType) !== -1) {
  1803. const defName = stringify(defType);
  1804. const path = parents.map(stringify);
  1805. throwCyclicDependencyError(defName, path);
  1806. }
  1807. // Check for multiple imports of the same module
  1808. const isDuplicate = dedup.has(defType);
  1809. if (cmpDef) {
  1810. if (isDuplicate) {
  1811. // This component definition has already been processed.
  1812. return false;
  1813. }
  1814. dedup.add(defType);
  1815. if (cmpDef.dependencies) {
  1816. const deps = typeof cmpDef.dependencies === 'function' ? cmpDef.dependencies() : cmpDef.dependencies;
  1817. for (const dep of deps) {
  1818. walkProviderTree(dep, visitor, parents, dedup);
  1819. }
  1820. }
  1821. }
  1822. else if (injDef) {
  1823. // First, include providers from any imports.
  1824. if (injDef.imports != null && !isDuplicate) {
  1825. // Before processing defType's imports, add it to the set of parents. This way, if it ends
  1826. // up deeply importing itself, this can be detected.
  1827. ngDevMode && parents.push(defType);
  1828. // Add it to the set of dedups. This way we can detect multiple imports of the same module
  1829. dedup.add(defType);
  1830. let importTypesWithProviders;
  1831. try {
  1832. deepForEach(injDef.imports, (imported) => {
  1833. if (walkProviderTree(imported, visitor, parents, dedup)) {
  1834. importTypesWithProviders ||= [];
  1835. // If the processed import is an injector type with providers, we store it in the
  1836. // list of import types with providers, so that we can process those afterwards.
  1837. importTypesWithProviders.push(imported);
  1838. }
  1839. });
  1840. }
  1841. finally {
  1842. // Remove it from the parents set when finished.
  1843. ngDevMode && parents.pop();
  1844. }
  1845. // Imports which are declared with providers (TypeWithProviders) need to be processed
  1846. // after all imported modules are processed. This is similar to how View Engine
  1847. // processes/merges module imports in the metadata resolver. See: FW-1349.
  1848. if (importTypesWithProviders !== undefined) {
  1849. processInjectorTypesWithProviders(importTypesWithProviders, visitor);
  1850. }
  1851. }
  1852. if (!isDuplicate) {
  1853. // Track the InjectorType and add a provider for it.
  1854. // It's important that this is done after the def's imports.
  1855. const factory = getFactoryDef(defType) || (() => new defType());
  1856. // Append extra providers to make more info available for consumers (to retrieve an injector
  1857. // type), as well as internally (to calculate an injection scope correctly and eagerly
  1858. // instantiate a `defType` when an injector is created).
  1859. // Provider to create `defType` using its factory.
  1860. visitor({ provide: defType, useFactory: factory, deps: EMPTY_ARRAY }, defType);
  1861. // Make this `defType` available to an internal logic that calculates injector scope.
  1862. visitor({ provide: INJECTOR_DEF_TYPES, useValue: defType, multi: true }, defType);
  1863. // Provider to eagerly instantiate `defType` via `INJECTOR_INITIALIZER`.
  1864. visitor({ provide: ENVIRONMENT_INITIALIZER, useValue: () => ɵɵinject(defType), multi: true }, defType);
  1865. }
  1866. // Next, include providers listed on the definition itself.
  1867. const defProviders = injDef.providers;
  1868. if (defProviders != null && !isDuplicate) {
  1869. const injectorType = container;
  1870. deepForEachProvider(defProviders, (provider) => {
  1871. ngDevMode && validateProvider(provider, defProviders, injectorType);
  1872. visitor(provider, injectorType);
  1873. });
  1874. }
  1875. }
  1876. else {
  1877. // Should not happen, but just in case.
  1878. return false;
  1879. }
  1880. return (defType !== container && container.providers !== undefined);
  1881. }
  1882. function validateProvider(provider, providers, containerType) {
  1883. if (isTypeProvider(provider) ||
  1884. isValueProvider(provider) ||
  1885. isFactoryProvider(provider) ||
  1886. isExistingProvider(provider)) {
  1887. return;
  1888. }
  1889. // Here we expect the provider to be a `useClass` provider (by elimination).
  1890. const classRef = resolveForwardRef(provider && (provider.useClass || provider.provide));
  1891. if (!classRef) {
  1892. throwInvalidProviderError(containerType, providers, provider);
  1893. }
  1894. }
  1895. function deepForEachProvider(providers, fn) {
  1896. for (let provider of providers) {
  1897. if (isEnvironmentProviders(provider)) {
  1898. provider = provider.ɵproviders;
  1899. }
  1900. if (Array.isArray(provider)) {
  1901. deepForEachProvider(provider, fn);
  1902. }
  1903. else {
  1904. fn(provider);
  1905. }
  1906. }
  1907. }
  1908. const USE_VALUE$1 = getClosureSafeProperty({
  1909. provide: String,
  1910. useValue: getClosureSafeProperty,
  1911. });
  1912. function isValueProvider(value) {
  1913. return value !== null && typeof value == 'object' && USE_VALUE$1 in value;
  1914. }
  1915. function isExistingProvider(value) {
  1916. return !!(value && value.useExisting);
  1917. }
  1918. function isFactoryProvider(value) {
  1919. return !!(value && value.useFactory);
  1920. }
  1921. function isTypeProvider(value) {
  1922. return typeof value === 'function';
  1923. }
  1924. function isClassProvider(value) {
  1925. return !!value.useClass;
  1926. }
  1927. /**
  1928. * An internal token whose presence in an injector indicates that the injector should treat itself
  1929. * as a root scoped injector when processing requests for unknown tokens which may indicate
  1930. * they are provided in the root scope.
  1931. */
  1932. const INJECTOR_SCOPE = new InjectionToken(ngDevMode ? 'Set Injector scope.' : '');
  1933. /**
  1934. * Marker which indicates that a value has not yet been created from the factory function.
  1935. */
  1936. const NOT_YET = {};
  1937. /**
  1938. * Marker which indicates that the factory function for a token is in the process of being called.
  1939. *
  1940. * If the injector is asked to inject a token with its value set to CIRCULAR, that indicates
  1941. * injection of a dependency has recursively attempted to inject the original token, and there is
  1942. * a circular dependency among the providers.
  1943. */
  1944. const CIRCULAR = {};
  1945. /**
  1946. * A lazily initialized NullInjector.
  1947. */
  1948. let NULL_INJECTOR = undefined;
  1949. function getNullInjector() {
  1950. if (NULL_INJECTOR === undefined) {
  1951. NULL_INJECTOR = new NullInjector();
  1952. }
  1953. return NULL_INJECTOR;
  1954. }
  1955. /**
  1956. * An `Injector` that's part of the environment injector hierarchy, which exists outside of the
  1957. * component tree.
  1958. */
  1959. class EnvironmentInjector {
  1960. }
  1961. class R3Injector extends EnvironmentInjector {
  1962. parent;
  1963. source;
  1964. scopes;
  1965. /**
  1966. * Map of tokens to records which contain the instances of those tokens.
  1967. * - `null` value implies that we don't have the record. Used by tree-shakable injectors
  1968. * to prevent further searches.
  1969. */
  1970. records = new Map();
  1971. /**
  1972. * Set of values instantiated by this injector which contain `ngOnDestroy` lifecycle hooks.
  1973. */
  1974. _ngOnDestroyHooks = new Set();
  1975. _onDestroyHooks = [];
  1976. /**
  1977. * Flag indicating that this injector was previously destroyed.
  1978. */
  1979. get destroyed() {
  1980. return this._destroyed;
  1981. }
  1982. _destroyed = false;
  1983. injectorDefTypes;
  1984. constructor(providers, parent, source, scopes) {
  1985. super();
  1986. this.parent = parent;
  1987. this.source = source;
  1988. this.scopes = scopes;
  1989. // Start off by creating Records for every provider.
  1990. forEachSingleProvider(providers, (provider) => this.processProvider(provider));
  1991. // Make sure the INJECTOR token provides this injector.
  1992. this.records.set(INJECTOR$1, makeRecord(undefined, this));
  1993. // And `EnvironmentInjector` if the current injector is supposed to be env-scoped.
  1994. if (scopes.has('environment')) {
  1995. this.records.set(EnvironmentInjector, makeRecord(undefined, this));
  1996. }
  1997. // Detect whether this injector has the APP_ROOT_SCOPE token and thus should provide
  1998. // any injectable scoped to APP_ROOT_SCOPE.
  1999. const record = this.records.get(INJECTOR_SCOPE);
  2000. if (record != null && typeof record.value === 'string') {
  2001. this.scopes.add(record.value);
  2002. }
  2003. this.injectorDefTypes = new Set(this.get(INJECTOR_DEF_TYPES, EMPTY_ARRAY, InjectFlags.Self));
  2004. }
  2005. retrieve(token, options) {
  2006. const ngOptions = options;
  2007. return this.get(token, ngOptions.optional ? NOT_FOUND$2 : THROW_IF_NOT_FOUND, ngOptions);
  2008. }
  2009. /**
  2010. * Destroy the injector and release references to every instance or provider associated with it.
  2011. *
  2012. * Also calls the `OnDestroy` lifecycle hooks of every instance that was created for which a
  2013. * hook was found.
  2014. */
  2015. destroy() {
  2016. assertNotDestroyed(this);
  2017. // Set destroyed = true first, in case lifecycle hooks re-enter destroy().
  2018. this._destroyed = true;
  2019. const prevConsumer = setActiveConsumer(null);
  2020. try {
  2021. // Call all the lifecycle hooks.
  2022. for (const service of this._ngOnDestroyHooks) {
  2023. service.ngOnDestroy();
  2024. }
  2025. const onDestroyHooks = this._onDestroyHooks;
  2026. // Reset the _onDestroyHooks array before iterating over it to prevent hooks that unregister
  2027. // themselves from mutating the array during iteration.
  2028. this._onDestroyHooks = [];
  2029. for (const hook of onDestroyHooks) {
  2030. hook();
  2031. }
  2032. }
  2033. finally {
  2034. // Release all references.
  2035. this.records.clear();
  2036. this._ngOnDestroyHooks.clear();
  2037. this.injectorDefTypes.clear();
  2038. setActiveConsumer(prevConsumer);
  2039. }
  2040. }
  2041. onDestroy(callback) {
  2042. assertNotDestroyed(this);
  2043. this._onDestroyHooks.push(callback);
  2044. return () => this.removeOnDestroy(callback);
  2045. }
  2046. runInContext(fn) {
  2047. assertNotDestroyed(this);
  2048. const previousInjector = setCurrentInjector(this);
  2049. const previousInjectImplementation = setInjectImplementation(undefined);
  2050. let prevInjectContext;
  2051. if (ngDevMode) {
  2052. prevInjectContext = setInjectorProfilerContext({ injector: this, token: null });
  2053. }
  2054. try {
  2055. return fn();
  2056. }
  2057. finally {
  2058. setCurrentInjector(previousInjector);
  2059. setInjectImplementation(previousInjectImplementation);
  2060. ngDevMode && setInjectorProfilerContext(prevInjectContext);
  2061. }
  2062. }
  2063. get(token, notFoundValue = THROW_IF_NOT_FOUND, flags = InjectFlags.Default) {
  2064. assertNotDestroyed(this);
  2065. if (token.hasOwnProperty(NG_ENV_ID)) {
  2066. return token[NG_ENV_ID](this);
  2067. }
  2068. flags = convertToBitFlags(flags);
  2069. // Set the injection context.
  2070. let prevInjectContext;
  2071. if (ngDevMode) {
  2072. prevInjectContext = setInjectorProfilerContext({ injector: this, token: token });
  2073. }
  2074. const previousInjector = setCurrentInjector(this);
  2075. const previousInjectImplementation = setInjectImplementation(undefined);
  2076. try {
  2077. // Check for the SkipSelf flag.
  2078. if (!(flags & InjectFlags.SkipSelf)) {
  2079. // SkipSelf isn't set, check if the record belongs to this injector.
  2080. let record = this.records.get(token);
  2081. if (record === undefined) {
  2082. // No record, but maybe the token is scoped to this injector. Look for an injectable
  2083. // def with a scope matching this injector.
  2084. const def = couldBeInjectableType(token) && getInjectableDef(token);
  2085. if (def && this.injectableDefInScope(def)) {
  2086. // Found an injectable def and it's scoped to this injector. Pretend as if it was here
  2087. // all along.
  2088. if (ngDevMode) {
  2089. runInInjectorProfilerContext(this, token, () => {
  2090. emitProviderConfiguredEvent(token);
  2091. });
  2092. }
  2093. record = makeRecord(injectableDefOrInjectorDefFactory(token), NOT_YET);
  2094. }
  2095. else {
  2096. record = null;
  2097. }
  2098. this.records.set(token, record);
  2099. }
  2100. // If a record was found, get the instance for it and return it.
  2101. if (record != null /* NOT null || undefined */) {
  2102. return this.hydrate(token, record);
  2103. }
  2104. }
  2105. // Select the next injector based on the Self flag - if self is set, the next injector is
  2106. // the NullInjector, otherwise it's the parent.
  2107. const nextInjector = !(flags & InjectFlags.Self) ? this.parent : getNullInjector();
  2108. // Set the notFoundValue based on the Optional flag - if optional is set and notFoundValue
  2109. // is undefined, the value is null, otherwise it's the notFoundValue.
  2110. notFoundValue =
  2111. flags & InjectFlags.Optional && notFoundValue === THROW_IF_NOT_FOUND ? null : notFoundValue;
  2112. return nextInjector.get(token, notFoundValue);
  2113. }
  2114. catch (e) {
  2115. if (e.name === 'NullInjectorError') {
  2116. const path = (e[NG_TEMP_TOKEN_PATH] = e[NG_TEMP_TOKEN_PATH] || []);
  2117. path.unshift(stringify(token));
  2118. if (previousInjector) {
  2119. // We still have a parent injector, keep throwing
  2120. throw e;
  2121. }
  2122. else {
  2123. // Format & throw the final error message when we don't have any previous injector
  2124. return catchInjectorError(e, token, 'R3InjectorError', this.source);
  2125. }
  2126. }
  2127. else {
  2128. throw e;
  2129. }
  2130. }
  2131. finally {
  2132. // Lastly, restore the previous injection context.
  2133. setInjectImplementation(previousInjectImplementation);
  2134. setCurrentInjector(previousInjector);
  2135. ngDevMode && setInjectorProfilerContext(prevInjectContext);
  2136. }
  2137. }
  2138. /** @internal */
  2139. resolveInjectorInitializers() {
  2140. const prevConsumer = setActiveConsumer(null);
  2141. const previousInjector = setCurrentInjector(this);
  2142. const previousInjectImplementation = setInjectImplementation(undefined);
  2143. let prevInjectContext;
  2144. if (ngDevMode) {
  2145. prevInjectContext = setInjectorProfilerContext({ injector: this, token: null });
  2146. }
  2147. try {
  2148. const initializers = this.get(ENVIRONMENT_INITIALIZER, EMPTY_ARRAY, InjectFlags.Self);
  2149. if (ngDevMode && !Array.isArray(initializers)) {
  2150. throw new RuntimeError(-209 /* RuntimeErrorCode.INVALID_MULTI_PROVIDER */, 'Unexpected type of the `ENVIRONMENT_INITIALIZER` token value ' +
  2151. `(expected an array, but got ${typeof initializers}). ` +
  2152. 'Please check that the `ENVIRONMENT_INITIALIZER` token is configured as a ' +
  2153. '`multi: true` provider.');
  2154. }
  2155. for (const initializer of initializers) {
  2156. initializer();
  2157. }
  2158. }
  2159. finally {
  2160. setCurrentInjector(previousInjector);
  2161. setInjectImplementation(previousInjectImplementation);
  2162. ngDevMode && setInjectorProfilerContext(prevInjectContext);
  2163. setActiveConsumer(prevConsumer);
  2164. }
  2165. }
  2166. toString() {
  2167. const tokens = [];
  2168. const records = this.records;
  2169. for (const token of records.keys()) {
  2170. tokens.push(stringify(token));
  2171. }
  2172. return `R3Injector[${tokens.join(', ')}]`;
  2173. }
  2174. /**
  2175. * Process a `SingleProvider` and add it.
  2176. */
  2177. processProvider(provider) {
  2178. // Determine the token from the provider. Either it's its own token, or has a {provide: ...}
  2179. // property.
  2180. provider = resolveForwardRef(provider);
  2181. let token = isTypeProvider(provider)
  2182. ? provider
  2183. : resolveForwardRef(provider && provider.provide);
  2184. // Construct a `Record` for the provider.
  2185. const record = providerToRecord(provider);
  2186. if (ngDevMode) {
  2187. runInInjectorProfilerContext(this, token, () => {
  2188. // Emit InjectorProfilerEventType.Create if provider is a value provider because
  2189. // these are the only providers that do not go through the value hydration logic
  2190. // where this event would normally be emitted from.
  2191. if (isValueProvider(provider)) {
  2192. emitInstanceCreatedByInjectorEvent(provider.useValue);
  2193. }
  2194. emitProviderConfiguredEvent(provider);
  2195. });
  2196. }
  2197. if (!isTypeProvider(provider) && provider.multi === true) {
  2198. // If the provider indicates that it's a multi-provider, process it specially.
  2199. // First check whether it's been defined already.
  2200. let multiRecord = this.records.get(token);
  2201. if (multiRecord) {
  2202. // It has. Throw a nice error if
  2203. if (ngDevMode && multiRecord.multi === undefined) {
  2204. throwMixedMultiProviderError();
  2205. }
  2206. }
  2207. else {
  2208. multiRecord = makeRecord(undefined, NOT_YET, true);
  2209. multiRecord.factory = () => injectArgs(multiRecord.multi);
  2210. this.records.set(token, multiRecord);
  2211. }
  2212. token = provider;
  2213. multiRecord.multi.push(provider);
  2214. }
  2215. else {
  2216. if (ngDevMode) {
  2217. const existing = this.records.get(token);
  2218. if (existing && existing.multi !== undefined) {
  2219. throwMixedMultiProviderError();
  2220. }
  2221. }
  2222. }
  2223. this.records.set(token, record);
  2224. }
  2225. hydrate(token, record) {
  2226. const prevConsumer = setActiveConsumer(null);
  2227. try {
  2228. if (record.value === CIRCULAR) {
  2229. throwCyclicDependencyError(stringify(token));
  2230. }
  2231. else if (record.value === NOT_YET) {
  2232. record.value = CIRCULAR;
  2233. if (ngDevMode) {
  2234. runInInjectorProfilerContext(this, token, () => {
  2235. record.value = record.factory();
  2236. emitInstanceCreatedByInjectorEvent(record.value);
  2237. });
  2238. }
  2239. else {
  2240. record.value = record.factory();
  2241. }
  2242. }
  2243. if (typeof record.value === 'object' && record.value && hasOnDestroy(record.value)) {
  2244. this._ngOnDestroyHooks.add(record.value);
  2245. }
  2246. return record.value;
  2247. }
  2248. finally {
  2249. setActiveConsumer(prevConsumer);
  2250. }
  2251. }
  2252. injectableDefInScope(def) {
  2253. if (!def.providedIn) {
  2254. return false;
  2255. }
  2256. const providedIn = resolveForwardRef(def.providedIn);
  2257. if (typeof providedIn === 'string') {
  2258. return providedIn === 'any' || this.scopes.has(providedIn);
  2259. }
  2260. else {
  2261. return this.injectorDefTypes.has(providedIn);
  2262. }
  2263. }
  2264. removeOnDestroy(callback) {
  2265. const destroyCBIdx = this._onDestroyHooks.indexOf(callback);
  2266. if (destroyCBIdx !== -1) {
  2267. this._onDestroyHooks.splice(destroyCBIdx, 1);
  2268. }
  2269. }
  2270. }
  2271. function injectableDefOrInjectorDefFactory(token) {
  2272. // Most tokens will have an injectable def directly on them, which specifies a factory directly.
  2273. const injectableDef = getInjectableDef(token);
  2274. const factory = injectableDef !== null ? injectableDef.factory : getFactoryDef(token);
  2275. if (factory !== null) {
  2276. return factory;
  2277. }
  2278. // InjectionTokens should have an injectable def (ɵprov) and thus should be handled above.
  2279. // If it's missing that, it's an error.
  2280. if (token instanceof InjectionToken) {
  2281. throw new RuntimeError(204 /* RuntimeErrorCode.INVALID_INJECTION_TOKEN */, ngDevMode && `Token ${stringify(token)} is missing a ɵprov definition.`);
  2282. }
  2283. // Undecorated types can sometimes be created if they have no constructor arguments.
  2284. if (token instanceof Function) {
  2285. return getUndecoratedInjectableFactory(token);
  2286. }
  2287. // There was no way to resolve a factory for this token.
  2288. throw new RuntimeError(204 /* RuntimeErrorCode.INVALID_INJECTION_TOKEN */, ngDevMode && 'unreachable');
  2289. }
  2290. function getUndecoratedInjectableFactory(token) {
  2291. // If the token has parameters then it has dependencies that we cannot resolve implicitly.
  2292. const paramLength = token.length;
  2293. if (paramLength > 0) {
  2294. throw new RuntimeError(204 /* RuntimeErrorCode.INVALID_INJECTION_TOKEN */, ngDevMode &&
  2295. `Can't resolve all parameters for ${stringify(token)}: (${newArray(paramLength, '?').join(', ')}).`);
  2296. }
  2297. // The constructor function appears to have no parameters.
  2298. // This might be because it inherits from a super-class. In which case, use an injectable
  2299. // def from an ancestor if there is one.
  2300. // Otherwise this really is a simple class with no dependencies, so return a factory that
  2301. // just instantiates the zero-arg constructor.
  2302. const inheritedInjectableDef = getInheritedInjectableDef(token);
  2303. if (inheritedInjectableDef !== null) {
  2304. return () => inheritedInjectableDef.factory(token);
  2305. }
  2306. else {
  2307. return () => new token();
  2308. }
  2309. }
  2310. function providerToRecord(provider) {
  2311. if (isValueProvider(provider)) {
  2312. return makeRecord(undefined, provider.useValue);
  2313. }
  2314. else {
  2315. const factory = providerToFactory(provider);
  2316. return makeRecord(factory, NOT_YET);
  2317. }
  2318. }
  2319. /**
  2320. * Converts a `SingleProvider` into a factory function.
  2321. *
  2322. * @param provider provider to convert to factory
  2323. */
  2324. function providerToFactory(provider, ngModuleType, providers) {
  2325. let factory = undefined;
  2326. if (ngDevMode && isEnvironmentProviders(provider)) {
  2327. throwInvalidProviderError(undefined, providers, provider);
  2328. }
  2329. if (isTypeProvider(provider)) {
  2330. const unwrappedProvider = resolveForwardRef(provider);
  2331. return getFactoryDef(unwrappedProvider) || injectableDefOrInjectorDefFactory(unwrappedProvider);
  2332. }
  2333. else {
  2334. if (isValueProvider(provider)) {
  2335. factory = () => resolveForwardRef(provider.useValue);
  2336. }
  2337. else if (isFactoryProvider(provider)) {
  2338. factory = () => provider.useFactory(...injectArgs(provider.deps || []));
  2339. }
  2340. else if (isExistingProvider(provider)) {
  2341. factory = () => ɵɵinject(resolveForwardRef(provider.useExisting));
  2342. }
  2343. else {
  2344. const classRef = resolveForwardRef(provider &&
  2345. (provider.useClass || provider.provide));
  2346. if (ngDevMode && !classRef) {
  2347. throwInvalidProviderError(ngModuleType, providers, provider);
  2348. }
  2349. if (hasDeps(provider)) {
  2350. factory = () => new classRef(...injectArgs(provider.deps));
  2351. }
  2352. else {
  2353. return getFactoryDef(classRef) || injectableDefOrInjectorDefFactory(classRef);
  2354. }
  2355. }
  2356. }
  2357. return factory;
  2358. }
  2359. function assertNotDestroyed(injector) {
  2360. if (injector.destroyed) {
  2361. throw new RuntimeError(205 /* RuntimeErrorCode.INJECTOR_ALREADY_DESTROYED */, ngDevMode && 'Injector has already been destroyed.');
  2362. }
  2363. }
  2364. function makeRecord(factory, value, multi = false) {
  2365. return {
  2366. factory: factory,
  2367. value: value,
  2368. multi: multi ? [] : undefined,
  2369. };
  2370. }
  2371. function hasDeps(value) {
  2372. return !!value.deps;
  2373. }
  2374. function hasOnDestroy(value) {
  2375. return (value !== null &&
  2376. typeof value === 'object' &&
  2377. typeof value.ngOnDestroy === 'function');
  2378. }
  2379. function couldBeInjectableType(value) {
  2380. return (typeof value === 'function' || (typeof value === 'object' && value instanceof InjectionToken));
  2381. }
  2382. function forEachSingleProvider(providers, fn) {
  2383. for (const provider of providers) {
  2384. if (Array.isArray(provider)) {
  2385. forEachSingleProvider(provider, fn);
  2386. }
  2387. else if (provider && isEnvironmentProviders(provider)) {
  2388. forEachSingleProvider(provider.ɵproviders, fn);
  2389. }
  2390. else {
  2391. fn(provider);
  2392. }
  2393. }
  2394. }
  2395. /**
  2396. * Runs the given function in the [context](guide/di/dependency-injection-context) of the given
  2397. * `Injector`.
  2398. *
  2399. * Within the function's stack frame, [`inject`](api/core/inject) can be used to inject dependencies
  2400. * from the given `Injector`. Note that `inject` is only usable synchronously, and cannot be used in
  2401. * any asynchronous callbacks or after any `await` points.
  2402. *
  2403. * @param injector the injector which will satisfy calls to [`inject`](api/core/inject) while `fn`
  2404. * is executing
  2405. * @param fn the closure to be run in the context of `injector`
  2406. * @returns the return value of the function, if any
  2407. * @publicApi
  2408. */
  2409. function runInInjectionContext(injector, fn) {
  2410. let internalInjector;
  2411. if (injector instanceof R3Injector) {
  2412. assertNotDestroyed(injector);
  2413. internalInjector = injector;
  2414. }
  2415. else {
  2416. internalInjector = new RetrievingInjector(injector);
  2417. }
  2418. let prevInjectorProfilerContext;
  2419. if (ngDevMode) {
  2420. prevInjectorProfilerContext = setInjectorProfilerContext({ injector, token: null });
  2421. }
  2422. const prevInjector = setCurrentInjector(internalInjector);
  2423. const previousInjectImplementation = setInjectImplementation(undefined);
  2424. try {
  2425. return fn();
  2426. }
  2427. finally {
  2428. setCurrentInjector(prevInjector);
  2429. ngDevMode && setInjectorProfilerContext(prevInjectorProfilerContext);
  2430. setInjectImplementation(previousInjectImplementation);
  2431. }
  2432. }
  2433. /**
  2434. * Whether the current stack frame is inside an injection context.
  2435. */
  2436. function isInInjectionContext() {
  2437. return getInjectImplementation() !== undefined || getCurrentInjector() != null;
  2438. }
  2439. /**
  2440. * Asserts that the current stack frame is within an [injection
  2441. * context](guide/di/dependency-injection-context) and has access to `inject`.
  2442. *
  2443. * @param debugFn a reference to the function making the assertion (used for the error message).
  2444. *
  2445. * @publicApi
  2446. */
  2447. function assertInInjectionContext(debugFn) {
  2448. // Taking a `Function` instead of a string name here prevents the unminified name of the function
  2449. // from being retained in the bundle regardless of minification.
  2450. if (!isInInjectionContext()) {
  2451. throw new RuntimeError(-203 /* RuntimeErrorCode.MISSING_INJECTION_CONTEXT */, ngDevMode &&
  2452. debugFn.name +
  2453. '() can only be used within an injection context such as a constructor, a factory function, a field initializer, or a function used with `runInInjectionContext`');
  2454. }
  2455. }
  2456. var FactoryTarget;
  2457. (function (FactoryTarget) {
  2458. FactoryTarget[FactoryTarget["Directive"] = 0] = "Directive";
  2459. FactoryTarget[FactoryTarget["Component"] = 1] = "Component";
  2460. FactoryTarget[FactoryTarget["Injectable"] = 2] = "Injectable";
  2461. FactoryTarget[FactoryTarget["Pipe"] = 3] = "Pipe";
  2462. FactoryTarget[FactoryTarget["NgModule"] = 4] = "NgModule";
  2463. })(FactoryTarget || (FactoryTarget = {}));
  2464. var R3TemplateDependencyKind;
  2465. (function (R3TemplateDependencyKind) {
  2466. R3TemplateDependencyKind[R3TemplateDependencyKind["Directive"] = 0] = "Directive";
  2467. R3TemplateDependencyKind[R3TemplateDependencyKind["Pipe"] = 1] = "Pipe";
  2468. R3TemplateDependencyKind[R3TemplateDependencyKind["NgModule"] = 2] = "NgModule";
  2469. })(R3TemplateDependencyKind || (R3TemplateDependencyKind = {}));
  2470. var ViewEncapsulation$1;
  2471. (function (ViewEncapsulation) {
  2472. ViewEncapsulation[ViewEncapsulation["Emulated"] = 0] = "Emulated";
  2473. // Historically the 1 value was for `Native` encapsulation which has been removed as of v11.
  2474. ViewEncapsulation[ViewEncapsulation["None"] = 2] = "None";
  2475. ViewEncapsulation[ViewEncapsulation["ShadowDom"] = 3] = "ShadowDom";
  2476. })(ViewEncapsulation$1 || (ViewEncapsulation$1 = {}));
  2477. function getCompilerFacade(request) {
  2478. const globalNg = _global['ng'];
  2479. if (globalNg && globalNg.ɵcompilerFacade) {
  2480. return globalNg.ɵcompilerFacade;
  2481. }
  2482. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  2483. // Log the type as an error so that a developer can easily navigate to the type from the
  2484. // console.
  2485. console.error(`JIT compilation failed for ${request.kind}`, request.type);
  2486. let message = `The ${request.kind} '${request.type.name}' needs to be compiled using the JIT compiler, but '@angular/compiler' is not available.\n\n`;
  2487. if (request.usage === 1 /* JitCompilerUsage.PartialDeclaration */) {
  2488. message += `The ${request.kind} is part of a library that has been partially compiled.\n`;
  2489. message += `However, the Angular Linker has not processed the library such that JIT compilation is used as fallback.\n`;
  2490. message += '\n';
  2491. message += `Ideally, the library is processed using the Angular Linker to become fully AOT compiled.\n`;
  2492. }
  2493. else {
  2494. message += `JIT compilation is discouraged for production use-cases! Consider using AOT mode instead.\n`;
  2495. }
  2496. message += `Alternatively, the JIT compiler should be loaded by bootstrapping using '@angular/platform-browser-dynamic' or '@angular/platform-server',\n`;
  2497. message += `or manually provide the compiler with 'import "@angular/compiler";' before bootstrapping.`;
  2498. throw new Error(message);
  2499. }
  2500. else {
  2501. throw new Error('JIT compiler unavailable');
  2502. }
  2503. }
  2504. /**
  2505. * A mapping of the @angular/core API surface used in generated expressions to the actual symbols.
  2506. *
  2507. * This should be kept up to date with the public exports of @angular/core.
  2508. */
  2509. const angularCoreDiEnv = {
  2510. 'ɵɵdefineInjectable': ɵɵdefineInjectable,
  2511. 'ɵɵdefineInjector': ɵɵdefineInjector,
  2512. 'ɵɵinject': ɵɵinject,
  2513. 'ɵɵinvalidFactoryDep': ɵɵinvalidFactoryDep,
  2514. 'resolveForwardRef': resolveForwardRef,
  2515. };
  2516. /**
  2517. * @description
  2518. *
  2519. * Represents a type that a Component or other object is instances of.
  2520. *
  2521. * An example of a `Type` is `MyCustomComponent` class, which in JavaScript is represented by
  2522. * the `MyCustomComponent` constructor function.
  2523. *
  2524. * @publicApi
  2525. */
  2526. const Type = Function;
  2527. function isType(v) {
  2528. return typeof v === 'function';
  2529. }
  2530. /*
  2531. * #########################
  2532. * Attention: These Regular expressions have to hold even if the code is minified!
  2533. * ##########################
  2534. */
  2535. /**
  2536. * Regular expression that detects pass-through constructors for ES5 output. This Regex
  2537. * intends to capture the common delegation pattern emitted by TypeScript and Babel. Also
  2538. * it intends to capture the pattern where existing constructors have been downleveled from
  2539. * ES2015 to ES5 using TypeScript w/ downlevel iteration. e.g.
  2540. *
  2541. * ```ts
  2542. * function MyClass() {
  2543. * var _this = _super.apply(this, arguments) || this;
  2544. * ```
  2545. *
  2546. * downleveled to ES5 with `downlevelIteration` for TypeScript < 4.2:
  2547. * ```ts
  2548. * function MyClass() {
  2549. * var _this = _super.apply(this, __spread(arguments)) || this;
  2550. * ```
  2551. *
  2552. * or downleveled to ES5 with `downlevelIteration` for TypeScript >= 4.2:
  2553. * ```ts
  2554. * function MyClass() {
  2555. * var _this = _super.apply(this, __spreadArray([], __read(arguments), false)) || this;
  2556. * ```
  2557. *
  2558. * More details can be found in: https://github.com/angular/angular/issues/38453.
  2559. */
  2560. const ES5_DELEGATE_CTOR = /^function\s+\S+\(\)\s*{[\s\S]+\.apply\(this,\s*(arguments|(?:[^()]+\(\[\],)?[^()]+\(arguments\).*)\)/;
  2561. /** Regular expression that detects ES2015 classes which extend from other classes. */
  2562. const ES2015_INHERITED_CLASS = /^class\s+[A-Za-z\d$_]*\s*extends\s+[^{]+{/;
  2563. /**
  2564. * Regular expression that detects ES2015 classes which extend from other classes and
  2565. * have an explicit constructor defined.
  2566. */
  2567. const ES2015_INHERITED_CLASS_WITH_CTOR = /^class\s+[A-Za-z\d$_]*\s*extends\s+[^{]+{[\s\S]*constructor\s*\(/;
  2568. /**
  2569. * Regular expression that detects ES2015 classes which extend from other classes
  2570. * and inherit a constructor.
  2571. */
  2572. const ES2015_INHERITED_CLASS_WITH_DELEGATE_CTOR = /^class\s+[A-Za-z\d$_]*\s*extends\s+[^{]+{[\s\S]*constructor\s*\(\)\s*{[^}]*super\(\.\.\.arguments\)/;
  2573. /**
  2574. * Determine whether a stringified type is a class which delegates its constructor
  2575. * to its parent.
  2576. *
  2577. * This is not trivial since compiled code can actually contain a constructor function
  2578. * even if the original source code did not. For instance, when the child class contains
  2579. * an initialized instance property.
  2580. */
  2581. function isDelegateCtor(typeStr) {
  2582. return (ES5_DELEGATE_CTOR.test(typeStr) ||
  2583. ES2015_INHERITED_CLASS_WITH_DELEGATE_CTOR.test(typeStr) ||
  2584. (ES2015_INHERITED_CLASS.test(typeStr) && !ES2015_INHERITED_CLASS_WITH_CTOR.test(typeStr)));
  2585. }
  2586. class ReflectionCapabilities {
  2587. _reflect;
  2588. constructor(reflect) {
  2589. this._reflect = reflect || _global['Reflect'];
  2590. }
  2591. factory(t) {
  2592. return (...args) => new t(...args);
  2593. }
  2594. /** @internal */
  2595. _zipTypesAndAnnotations(paramTypes, paramAnnotations) {
  2596. let result;
  2597. if (typeof paramTypes === 'undefined') {
  2598. result = newArray(paramAnnotations.length);
  2599. }
  2600. else {
  2601. result = newArray(paramTypes.length);
  2602. }
  2603. for (let i = 0; i < result.length; i++) {
  2604. // TS outputs Object for parameters without types, while Traceur omits
  2605. // the annotations. For now we preserve the Traceur behavior to aid
  2606. // migration, but this can be revisited.
  2607. if (typeof paramTypes === 'undefined') {
  2608. result[i] = [];
  2609. }
  2610. else if (paramTypes[i] && paramTypes[i] != Object) {
  2611. result[i] = [paramTypes[i]];
  2612. }
  2613. else {
  2614. result[i] = [];
  2615. }
  2616. if (paramAnnotations && paramAnnotations[i] != null) {
  2617. result[i] = result[i].concat(paramAnnotations[i]);
  2618. }
  2619. }
  2620. return result;
  2621. }
  2622. _ownParameters(type, parentCtor) {
  2623. const typeStr = type.toString();
  2624. // If we have no decorators, we only have function.length as metadata.
  2625. // In that case, to detect whether a child class declared an own constructor or not,
  2626. // we need to look inside of that constructor to check whether it is
  2627. // just calling the parent.
  2628. // This also helps to work around for https://github.com/Microsoft/TypeScript/issues/12439
  2629. // that sets 'design:paramtypes' to []
  2630. // if a class inherits from another class but has no ctor declared itself.
  2631. if (isDelegateCtor(typeStr)) {
  2632. return null;
  2633. }
  2634. // Prefer the direct API.
  2635. if (type.parameters && type.parameters !== parentCtor.parameters) {
  2636. return type.parameters;
  2637. }
  2638. // API of tsickle for lowering decorators to properties on the class.
  2639. const tsickleCtorParams = type.ctorParameters;
  2640. if (tsickleCtorParams && tsickleCtorParams !== parentCtor.ctorParameters) {
  2641. // Newer tsickle uses a function closure
  2642. // Retain the non-function case for compatibility with older tsickle
  2643. const ctorParameters = typeof tsickleCtorParams === 'function' ? tsickleCtorParams() : tsickleCtorParams;
  2644. const paramTypes = ctorParameters.map((ctorParam) => ctorParam && ctorParam.type);
  2645. const paramAnnotations = ctorParameters.map((ctorParam) => ctorParam && convertTsickleDecoratorIntoMetadata(ctorParam.decorators));
  2646. return this._zipTypesAndAnnotations(paramTypes, paramAnnotations);
  2647. }
  2648. // API for metadata created by invoking the decorators.
  2649. const paramAnnotations = type.hasOwnProperty(PARAMETERS) && type[PARAMETERS];
  2650. const paramTypes = this._reflect &&
  2651. this._reflect.getOwnMetadata &&
  2652. this._reflect.getOwnMetadata('design:paramtypes', type);
  2653. if (paramTypes || paramAnnotations) {
  2654. return this._zipTypesAndAnnotations(paramTypes, paramAnnotations);
  2655. }
  2656. // If a class has no decorators, at least create metadata
  2657. // based on function.length.
  2658. // Note: We know that this is a real constructor as we checked
  2659. // the content of the constructor above.
  2660. return newArray(type.length);
  2661. }
  2662. parameters(type) {
  2663. // Note: only report metadata if we have at least one class decorator
  2664. // to stay in sync with the static reflector.
  2665. if (!isType(type)) {
  2666. return [];
  2667. }
  2668. const parentCtor = getParentCtor(type);
  2669. let parameters = this._ownParameters(type, parentCtor);
  2670. if (!parameters && parentCtor !== Object) {
  2671. parameters = this.parameters(parentCtor);
  2672. }
  2673. return parameters || [];
  2674. }
  2675. _ownAnnotations(typeOrFunc, parentCtor) {
  2676. // Prefer the direct API.
  2677. if (typeOrFunc.annotations && typeOrFunc.annotations !== parentCtor.annotations) {
  2678. let annotations = typeOrFunc.annotations;
  2679. if (typeof annotations === 'function' && annotations.annotations) {
  2680. annotations = annotations.annotations;
  2681. }
  2682. return annotations;
  2683. }
  2684. // API of tsickle for lowering decorators to properties on the class.
  2685. if (typeOrFunc.decorators && typeOrFunc.decorators !== parentCtor.decorators) {
  2686. return convertTsickleDecoratorIntoMetadata(typeOrFunc.decorators);
  2687. }
  2688. // API for metadata created by invoking the decorators.
  2689. if (typeOrFunc.hasOwnProperty(ANNOTATIONS)) {
  2690. return typeOrFunc[ANNOTATIONS];
  2691. }
  2692. return null;
  2693. }
  2694. annotations(typeOrFunc) {
  2695. if (!isType(typeOrFunc)) {
  2696. return [];
  2697. }
  2698. const parentCtor = getParentCtor(typeOrFunc);
  2699. const ownAnnotations = this._ownAnnotations(typeOrFunc, parentCtor) || [];
  2700. const parentAnnotations = parentCtor !== Object ? this.annotations(parentCtor) : [];
  2701. return parentAnnotations.concat(ownAnnotations);
  2702. }
  2703. _ownPropMetadata(typeOrFunc, parentCtor) {
  2704. // Prefer the direct API.
  2705. if (typeOrFunc.propMetadata &&
  2706. typeOrFunc.propMetadata !== parentCtor.propMetadata) {
  2707. let propMetadata = typeOrFunc.propMetadata;
  2708. if (typeof propMetadata === 'function' && propMetadata.propMetadata) {
  2709. propMetadata = propMetadata.propMetadata;
  2710. }
  2711. return propMetadata;
  2712. }
  2713. // API of tsickle for lowering decorators to properties on the class.
  2714. if (typeOrFunc.propDecorators &&
  2715. typeOrFunc.propDecorators !== parentCtor.propDecorators) {
  2716. const propDecorators = typeOrFunc.propDecorators;
  2717. const propMetadata = {};
  2718. Object.keys(propDecorators).forEach((prop) => {
  2719. propMetadata[prop] = convertTsickleDecoratorIntoMetadata(propDecorators[prop]);
  2720. });
  2721. return propMetadata;
  2722. }
  2723. // API for metadata created by invoking the decorators.
  2724. if (typeOrFunc.hasOwnProperty(PROP_METADATA)) {
  2725. return typeOrFunc[PROP_METADATA];
  2726. }
  2727. return null;
  2728. }
  2729. propMetadata(typeOrFunc) {
  2730. if (!isType(typeOrFunc)) {
  2731. return {};
  2732. }
  2733. const parentCtor = getParentCtor(typeOrFunc);
  2734. const propMetadata = {};
  2735. if (parentCtor !== Object) {
  2736. const parentPropMetadata = this.propMetadata(parentCtor);
  2737. Object.keys(parentPropMetadata).forEach((propName) => {
  2738. propMetadata[propName] = parentPropMetadata[propName];
  2739. });
  2740. }
  2741. const ownPropMetadata = this._ownPropMetadata(typeOrFunc, parentCtor);
  2742. if (ownPropMetadata) {
  2743. Object.keys(ownPropMetadata).forEach((propName) => {
  2744. const decorators = [];
  2745. if (propMetadata.hasOwnProperty(propName)) {
  2746. decorators.push(...propMetadata[propName]);
  2747. }
  2748. decorators.push(...ownPropMetadata[propName]);
  2749. propMetadata[propName] = decorators;
  2750. });
  2751. }
  2752. return propMetadata;
  2753. }
  2754. ownPropMetadata(typeOrFunc) {
  2755. if (!isType(typeOrFunc)) {
  2756. return {};
  2757. }
  2758. return this._ownPropMetadata(typeOrFunc, getParentCtor(typeOrFunc)) || {};
  2759. }
  2760. hasLifecycleHook(type, lcProperty) {
  2761. return type instanceof Type && lcProperty in type.prototype;
  2762. }
  2763. }
  2764. function convertTsickleDecoratorIntoMetadata(decoratorInvocations) {
  2765. if (!decoratorInvocations) {
  2766. return [];
  2767. }
  2768. return decoratorInvocations.map((decoratorInvocation) => {
  2769. const decoratorType = decoratorInvocation.type;
  2770. const annotationCls = decoratorType.annotationCls;
  2771. const annotationArgs = decoratorInvocation.args ? decoratorInvocation.args : [];
  2772. return new annotationCls(...annotationArgs);
  2773. });
  2774. }
  2775. function getParentCtor(ctor) {
  2776. const parentProto = ctor.prototype ? Object.getPrototypeOf(ctor.prototype) : null;
  2777. const parentCtor = parentProto ? parentProto.constructor : null;
  2778. // Note: We always use `Object` as the null value
  2779. // to simplify checking later on.
  2780. return parentCtor || Object;
  2781. }
  2782. // Below are constants for LView indices to help us look up LView members
  2783. // without having to remember the specific indices.
  2784. // Uglify will inline these when minifying so there shouldn't be a cost.
  2785. const HOST = 0;
  2786. const TVIEW = 1;
  2787. // Shared with LContainer
  2788. const FLAGS = 2;
  2789. const PARENT = 3;
  2790. const NEXT = 4;
  2791. const T_HOST = 5;
  2792. // End shared with LContainer
  2793. const HYDRATION = 6;
  2794. const CLEANUP = 7;
  2795. const CONTEXT = 8;
  2796. const INJECTOR = 9;
  2797. const ENVIRONMENT = 10;
  2798. const RENDERER = 11;
  2799. const CHILD_HEAD = 12;
  2800. const CHILD_TAIL = 13;
  2801. // FIXME(misko): Investigate if the three declarations aren't all same thing.
  2802. const DECLARATION_VIEW = 14;
  2803. const DECLARATION_COMPONENT_VIEW = 15;
  2804. const DECLARATION_LCONTAINER = 16;
  2805. const PREORDER_HOOK_FLAGS = 17;
  2806. const QUERIES = 18;
  2807. const ID = 19;
  2808. const EMBEDDED_VIEW_INJECTOR = 20;
  2809. const ON_DESTROY_HOOKS = 21;
  2810. const EFFECTS_TO_SCHEDULE = 22;
  2811. const EFFECTS = 23;
  2812. const REACTIVE_TEMPLATE_CONSUMER = 24;
  2813. const AFTER_RENDER_SEQUENCES_TO_ADD = 25;
  2814. /**
  2815. * Size of LView's header. Necessary to adjust for it when setting slots.
  2816. *
  2817. * IMPORTANT: `HEADER_OFFSET` should only be referred to the in the `ɵɵ*` instructions to translate
  2818. * instruction index into `LView` index. All other indexes should be in the `LView` index space and
  2819. * there should be no need to refer to `HEADER_OFFSET` anywhere else.
  2820. */
  2821. const HEADER_OFFSET = 26;
  2822. /**
  2823. * Special location which allows easy identification of type. If we have an array which was
  2824. * retrieved from the `LView` and that array has `true` at `TYPE` location, we know it is
  2825. * `LContainer`.
  2826. */
  2827. const TYPE = 1;
  2828. /**
  2829. * Below are constants for LContainer indices to help us look up LContainer members
  2830. * without having to remember the specific indices.
  2831. * Uglify will inline these when minifying so there shouldn't be a cost.
  2832. */
  2833. // FLAGS, PARENT, NEXT, and T_HOST are indices 2, 3, 4, and 5
  2834. // As we already have these constants in LView, we don't need to re-create them.
  2835. const DEHYDRATED_VIEWS = 6;
  2836. const NATIVE = 7;
  2837. const VIEW_REFS = 8;
  2838. const MOVED_VIEWS = 9;
  2839. /**
  2840. * Size of LContainer's header. Represents the index after which all views in the
  2841. * container will be inserted. We need to keep a record of current views so we know
  2842. * which views are already in the DOM (and don't need to be re-added) and so we can
  2843. * remove views from the DOM when they are no longer required.
  2844. */
  2845. const CONTAINER_HEADER_OFFSET = 10;
  2846. /**
  2847. * True if `value` is `LView`.
  2848. * @param value wrapped value of `RNode`, `LView`, `LContainer`
  2849. */
  2850. function isLView(value) {
  2851. return Array.isArray(value) && typeof value[TYPE] === 'object';
  2852. }
  2853. /**
  2854. * True if `value` is `LContainer`.
  2855. * @param value wrapped value of `RNode`, `LView`, `LContainer`
  2856. */
  2857. function isLContainer(value) {
  2858. return Array.isArray(value) && value[TYPE] === true;
  2859. }
  2860. function isContentQueryHost(tNode) {
  2861. return (tNode.flags & 4 /* TNodeFlags.hasContentQuery */) !== 0;
  2862. }
  2863. function isComponentHost(tNode) {
  2864. return tNode.componentOffset > -1;
  2865. }
  2866. function isDirectiveHost(tNode) {
  2867. return (tNode.flags & 1 /* TNodeFlags.isDirectiveHost */) === 1 /* TNodeFlags.isDirectiveHost */;
  2868. }
  2869. function isComponentDef(def) {
  2870. return !!def.template;
  2871. }
  2872. function isRootView(target) {
  2873. // Determines whether a given LView is marked as a root view.
  2874. return (target[FLAGS] & 512 /* LViewFlags.IsRoot */) !== 0;
  2875. }
  2876. function isProjectionTNode(tNode) {
  2877. return (tNode.type & 16 /* TNodeType.Projection */) === 16 /* TNodeType.Projection */;
  2878. }
  2879. function hasI18n(lView) {
  2880. return (lView[FLAGS] & 32 /* LViewFlags.HasI18n */) === 32 /* LViewFlags.HasI18n */;
  2881. }
  2882. function isDestroyed(lView) {
  2883. // Determines whether a given LView is marked as destroyed.
  2884. return (lView[FLAGS] & 256 /* LViewFlags.Destroyed */) === 256 /* LViewFlags.Destroyed */;
  2885. }
  2886. // [Assert functions do not constraint type when they are guarded by a truthy
  2887. // expression.](https://github.com/microsoft/TypeScript/issues/37295)
  2888. function assertTNodeForLView(tNode, lView) {
  2889. assertTNodeForTView(tNode, lView[TVIEW]);
  2890. }
  2891. function assertTNodeForTView(tNode, tView) {
  2892. assertTNode(tNode);
  2893. const tData = tView.data;
  2894. for (let i = HEADER_OFFSET; i < tData.length; i++) {
  2895. if (tData[i] === tNode) {
  2896. return;
  2897. }
  2898. }
  2899. throwError('This TNode does not belong to this TView.');
  2900. }
  2901. function assertTNode(tNode) {
  2902. assertDefined(tNode, 'TNode must be defined');
  2903. if (!(tNode && typeof tNode === 'object' && tNode.hasOwnProperty('directiveStylingLast'))) {
  2904. throwError('Not of type TNode, got: ' + tNode);
  2905. }
  2906. }
  2907. function assertTIcu(tIcu) {
  2908. assertDefined(tIcu, 'Expected TIcu to be defined');
  2909. if (!(typeof tIcu.currentCaseLViewIndex === 'number')) {
  2910. throwError('Object is not of TIcu type.');
  2911. }
  2912. }
  2913. function assertComponentType(actual, msg = "Type passed in is not ComponentType, it does not have 'ɵcmp' property.") {
  2914. if (!getComponentDef(actual)) {
  2915. throwError(msg);
  2916. }
  2917. }
  2918. function assertNgModuleType(actual, msg = "Type passed in is not NgModuleType, it does not have 'ɵmod' property.") {
  2919. if (!getNgModuleDef(actual)) {
  2920. throwError(msg);
  2921. }
  2922. }
  2923. function assertHasParent(tNode) {
  2924. assertDefined(tNode, 'currentTNode should exist!');
  2925. assertDefined(tNode.parent, 'currentTNode should have a parent');
  2926. }
  2927. function assertLContainer(value) {
  2928. assertDefined(value, 'LContainer must be defined');
  2929. assertEqual(isLContainer(value), true, 'Expecting LContainer');
  2930. }
  2931. function assertLViewOrUndefined(value) {
  2932. value && assertEqual(isLView(value), true, 'Expecting LView or undefined or null');
  2933. }
  2934. function assertLView(value) {
  2935. assertDefined(value, 'LView must be defined');
  2936. assertEqual(isLView(value), true, 'Expecting LView');
  2937. }
  2938. function assertFirstCreatePass(tView, errMessage) {
  2939. assertEqual(tView.firstCreatePass, true, errMessage || 'Should only be called in first create pass.');
  2940. }
  2941. function assertFirstUpdatePass(tView, errMessage) {
  2942. assertEqual(tView.firstUpdatePass, true, 'Should only be called in first update pass.');
  2943. }
  2944. /**
  2945. * This is a basic sanity check that an object is probably a directive def. DirectiveDef is
  2946. * an interface, so we can't do a direct instanceof check.
  2947. */
  2948. function assertDirectiveDef(obj) {
  2949. if (obj.type === undefined || obj.selectors == undefined || obj.inputs === undefined) {
  2950. throwError(`Expected a DirectiveDef/ComponentDef and this object does not seem to have the expected shape.`);
  2951. }
  2952. }
  2953. function assertIndexInDeclRange(tView, index) {
  2954. assertBetween(HEADER_OFFSET, tView.bindingStartIndex, index);
  2955. }
  2956. function assertIndexInExpandoRange(lView, index) {
  2957. const tView = lView[1];
  2958. assertBetween(tView.expandoStartIndex, lView.length, index);
  2959. }
  2960. function assertBetween(lower, upper, index) {
  2961. if (!(lower <= index && index < upper)) {
  2962. throwError(`Index out of range (expecting ${lower} <= ${index} < ${upper})`);
  2963. }
  2964. }
  2965. function assertProjectionSlots(lView, errMessage) {
  2966. assertDefined(lView[DECLARATION_COMPONENT_VIEW], 'Component views should exist.');
  2967. assertDefined(lView[DECLARATION_COMPONENT_VIEW][T_HOST].projection, 'Components with projection nodes (<ng-content>) must have projection slots defined.');
  2968. }
  2969. function assertParentView(lView, errMessage) {
  2970. assertDefined(lView, "Component views should always have a parent view (component's host view)");
  2971. }
  2972. /**
  2973. * This is a basic sanity check that the `injectorIndex` seems to point to what looks like a
  2974. * NodeInjector data structure.
  2975. *
  2976. * @param lView `LView` which should be checked.
  2977. * @param injectorIndex index into the `LView` where the `NodeInjector` is expected.
  2978. */
  2979. function assertNodeInjector(lView, injectorIndex) {
  2980. assertIndexInExpandoRange(lView, injectorIndex);
  2981. assertIndexInExpandoRange(lView, injectorIndex + 8 /* NodeInjectorOffset.PARENT */);
  2982. assertNumber(lView[injectorIndex + 0], 'injectorIndex should point to a bloom filter');
  2983. assertNumber(lView[injectorIndex + 1], 'injectorIndex should point to a bloom filter');
  2984. assertNumber(lView[injectorIndex + 2], 'injectorIndex should point to a bloom filter');
  2985. assertNumber(lView[injectorIndex + 3], 'injectorIndex should point to a bloom filter');
  2986. assertNumber(lView[injectorIndex + 4], 'injectorIndex should point to a bloom filter');
  2987. assertNumber(lView[injectorIndex + 5], 'injectorIndex should point to a bloom filter');
  2988. assertNumber(lView[injectorIndex + 6], 'injectorIndex should point to a bloom filter');
  2989. assertNumber(lView[injectorIndex + 7], 'injectorIndex should point to a bloom filter');
  2990. assertNumber(lView[injectorIndex + 8 /* NodeInjectorOffset.PARENT */], 'injectorIndex should point to parent injector');
  2991. }
  2992. /**
  2993. * Represents a basic change from a previous to a new value for a single
  2994. * property on a directive instance. Passed as a value in a
  2995. * {@link SimpleChanges} object to the `ngOnChanges` hook.
  2996. *
  2997. * @see {@link OnChanges}
  2998. *
  2999. * @publicApi
  3000. */
  3001. class SimpleChange {
  3002. previousValue;
  3003. currentValue;
  3004. firstChange;
  3005. constructor(previousValue, currentValue, firstChange) {
  3006. this.previousValue = previousValue;
  3007. this.currentValue = currentValue;
  3008. this.firstChange = firstChange;
  3009. }
  3010. /**
  3011. * Check whether the new value is the first value assigned.
  3012. */
  3013. isFirstChange() {
  3014. return this.firstChange;
  3015. }
  3016. }
  3017. function applyValueToInputField(instance, inputSignalNode, privateName, value) {
  3018. if (inputSignalNode !== null) {
  3019. inputSignalNode.applyValueToInputSignal(inputSignalNode, value);
  3020. }
  3021. else {
  3022. instance[privateName] = value;
  3023. }
  3024. }
  3025. /**
  3026. * The NgOnChangesFeature decorates a component with support for the ngOnChanges
  3027. * lifecycle hook, so it should be included in any component that implements
  3028. * that hook.
  3029. *
  3030. * If the component or directive uses inheritance, the NgOnChangesFeature MUST
  3031. * be included as a feature AFTER {@link InheritDefinitionFeature}, otherwise
  3032. * inherited properties will not be propagated to the ngOnChanges lifecycle
  3033. * hook.
  3034. *
  3035. * Example usage:
  3036. *
  3037. * ```ts
  3038. * static ɵcmp = defineComponent({
  3039. * ...
  3040. * inputs: {name: 'publicName'},
  3041. * features: [NgOnChangesFeature]
  3042. * });
  3043. * ```
  3044. *
  3045. * @codeGenApi
  3046. */
  3047. const ɵɵNgOnChangesFeature = /* @__PURE__ */ (() => {
  3048. const ɵɵNgOnChangesFeatureImpl = () => NgOnChangesFeatureImpl;
  3049. // This option ensures that the ngOnChanges lifecycle hook will be inherited
  3050. // from superclasses (in InheritDefinitionFeature).
  3051. /** @nocollapse */
  3052. ɵɵNgOnChangesFeatureImpl.ngInherit = true;
  3053. return ɵɵNgOnChangesFeatureImpl;
  3054. })();
  3055. function NgOnChangesFeatureImpl(definition) {
  3056. if (definition.type.prototype.ngOnChanges) {
  3057. definition.setInput = ngOnChangesSetInput;
  3058. }
  3059. return rememberChangeHistoryAndInvokeOnChangesHook;
  3060. }
  3061. /**
  3062. * This is a synthetic lifecycle hook which gets inserted into `TView.preOrderHooks` to simulate
  3063. * `ngOnChanges`.
  3064. *
  3065. * The hook reads the `NgSimpleChangesStore` data from the component instance and if changes are
  3066. * found it invokes `ngOnChanges` on the component instance.
  3067. *
  3068. * @param this Component instance. Because this function gets inserted into `TView.preOrderHooks`,
  3069. * it is guaranteed to be called with component instance.
  3070. */
  3071. function rememberChangeHistoryAndInvokeOnChangesHook() {
  3072. const simpleChangesStore = getSimpleChangesStore(this);
  3073. const current = simpleChangesStore?.current;
  3074. if (current) {
  3075. const previous = simpleChangesStore.previous;
  3076. if (previous === EMPTY_OBJ) {
  3077. simpleChangesStore.previous = current;
  3078. }
  3079. else {
  3080. // New changes are copied to the previous store, so that we don't lose history for inputs
  3081. // which were not changed this time
  3082. for (let key in current) {
  3083. previous[key] = current[key];
  3084. }
  3085. }
  3086. simpleChangesStore.current = null;
  3087. this.ngOnChanges(current);
  3088. }
  3089. }
  3090. function ngOnChangesSetInput(instance, inputSignalNode, value, publicName, privateName) {
  3091. const declaredName = this.declaredInputs[publicName];
  3092. ngDevMode && assertString(declaredName, 'Name of input in ngOnChanges has to be a string');
  3093. const simpleChangesStore = getSimpleChangesStore(instance) ||
  3094. setSimpleChangesStore(instance, { previous: EMPTY_OBJ, current: null });
  3095. const current = simpleChangesStore.current || (simpleChangesStore.current = {});
  3096. const previous = simpleChangesStore.previous;
  3097. const previousChange = previous[declaredName];
  3098. current[declaredName] = new SimpleChange(previousChange && previousChange.currentValue, value, previous === EMPTY_OBJ);
  3099. applyValueToInputField(instance, inputSignalNode, privateName, value);
  3100. }
  3101. const SIMPLE_CHANGES_STORE = '__ngSimpleChanges__';
  3102. function getSimpleChangesStore(instance) {
  3103. return instance[SIMPLE_CHANGES_STORE] || null;
  3104. }
  3105. function setSimpleChangesStore(instance, store) {
  3106. return (instance[SIMPLE_CHANGES_STORE] = store);
  3107. }
  3108. let profilerCallback = null;
  3109. /**
  3110. * Sets the callback function which will be invoked before and after performing certain actions at
  3111. * runtime (for example, before and after running change detection).
  3112. *
  3113. * Warning: this function is *INTERNAL* and should not be relied upon in application's code.
  3114. * The contract of the function might be changed in any release and/or the function can be removed
  3115. * completely.
  3116. *
  3117. * @param profiler function provided by the caller or null value to disable profiling.
  3118. */
  3119. const setProfiler = (profiler) => {
  3120. profilerCallback = profiler;
  3121. };
  3122. /**
  3123. * Profiler function which wraps user code executed by the runtime.
  3124. *
  3125. * @param event ProfilerEvent corresponding to the execution context
  3126. * @param instance component instance
  3127. * @param hookOrListener lifecycle hook function or output listener. The value depends on the
  3128. * execution context
  3129. * @returns
  3130. */
  3131. const profiler = function (event, instance = null, hookOrListener) {
  3132. if (profilerCallback != null /* both `null` and `undefined` */) {
  3133. profilerCallback(event, instance, hookOrListener);
  3134. }
  3135. };
  3136. const SVG_NAMESPACE = 'svg';
  3137. const MATH_ML_NAMESPACE = 'math';
  3138. /**
  3139. * For efficiency reasons we often put several different data types (`RNode`, `LView`, `LContainer`)
  3140. * in same location in `LView`. This is because we don't want to pre-allocate space for it
  3141. * because the storage is sparse. This file contains utilities for dealing with such data types.
  3142. *
  3143. * How do we know what is stored at a given location in `LView`.
  3144. * - `Array.isArray(value) === false` => `RNode` (The normal storage value)
  3145. * - `Array.isArray(value) === true` => then the `value[0]` represents the wrapped value.
  3146. * - `typeof value[TYPE] === 'object'` => `LView`
  3147. * - This happens when we have a component at a given location
  3148. * - `typeof value[TYPE] === true` => `LContainer`
  3149. * - This happens when we have `LContainer` binding at a given location.
  3150. *
  3151. *
  3152. * NOTE: it is assumed that `Array.isArray` and `typeof` operations are very efficient.
  3153. */
  3154. /**
  3155. * Returns `RNode`.
  3156. * @param value wrapped value of `RNode`, `LView`, `LContainer`
  3157. */
  3158. function unwrapRNode(value) {
  3159. while (Array.isArray(value)) {
  3160. value = value[HOST];
  3161. }
  3162. return value;
  3163. }
  3164. /**
  3165. * Returns `LView` or `null` if not found.
  3166. * @param value wrapped value of `RNode`, `LView`, `LContainer`
  3167. */
  3168. function unwrapLView(value) {
  3169. while (Array.isArray(value)) {
  3170. // This check is same as `isLView()` but we don't call at as we don't want to call
  3171. // `Array.isArray()` twice and give JITer more work for inlining.
  3172. if (typeof value[TYPE] === 'object')
  3173. return value;
  3174. value = value[HOST];
  3175. }
  3176. return null;
  3177. }
  3178. /**
  3179. * Retrieves an element value from the provided `viewData`, by unwrapping
  3180. * from any containers, component views, or style contexts.
  3181. */
  3182. function getNativeByIndex(index, lView) {
  3183. ngDevMode && assertIndexInRange(lView, index);
  3184. ngDevMode && assertGreaterThanOrEqual(index, HEADER_OFFSET, 'Expected to be past HEADER_OFFSET');
  3185. return unwrapRNode(lView[index]);
  3186. }
  3187. /**
  3188. * Retrieve an `RNode` for a given `TNode` and `LView`.
  3189. *
  3190. * This function guarantees in dev mode to retrieve a non-null `RNode`.
  3191. *
  3192. * @param tNode
  3193. * @param lView
  3194. */
  3195. function getNativeByTNode(tNode, lView) {
  3196. ngDevMode && assertTNodeForLView(tNode, lView);
  3197. ngDevMode && assertIndexInRange(lView, tNode.index);
  3198. const node = unwrapRNode(lView[tNode.index]);
  3199. return node;
  3200. }
  3201. /**
  3202. * Retrieve an `RNode` or `null` for a given `TNode` and `LView`.
  3203. *
  3204. * Some `TNode`s don't have associated `RNode`s. For example `Projection`
  3205. *
  3206. * @param tNode
  3207. * @param lView
  3208. */
  3209. function getNativeByTNodeOrNull(tNode, lView) {
  3210. const index = tNode === null ? -1 : tNode.index;
  3211. if (index !== -1) {
  3212. ngDevMode && assertTNodeForLView(tNode, lView);
  3213. const node = unwrapRNode(lView[index]);
  3214. return node;
  3215. }
  3216. return null;
  3217. }
  3218. // fixme(misko): The return Type should be `TNode|null`
  3219. function getTNode(tView, index) {
  3220. ngDevMode && assertGreaterThan(index, -1, 'wrong index for TNode');
  3221. ngDevMode && assertLessThan(index, tView.data.length, 'wrong index for TNode');
  3222. const tNode = tView.data[index];
  3223. ngDevMode && tNode !== null && assertTNode(tNode);
  3224. return tNode;
  3225. }
  3226. /** Retrieves a value from any `LView` or `TData`. */
  3227. function load(view, index) {
  3228. ngDevMode && assertIndexInRange(view, index);
  3229. return view[index];
  3230. }
  3231. function getComponentLViewByIndex(nodeIndex, hostView) {
  3232. // Could be an LView or an LContainer. If LContainer, unwrap to find LView.
  3233. ngDevMode && assertIndexInRange(hostView, nodeIndex);
  3234. const slotValue = hostView[nodeIndex];
  3235. const lView = isLView(slotValue) ? slotValue : slotValue[HOST];
  3236. return lView;
  3237. }
  3238. /** Checks whether a given view is in creation mode */
  3239. function isCreationMode(view) {
  3240. return (view[FLAGS] & 4 /* LViewFlags.CreationMode */) === 4 /* LViewFlags.CreationMode */;
  3241. }
  3242. /**
  3243. * Returns a boolean for whether the view is attached to the change detection tree.
  3244. *
  3245. * Note: This determines whether a view should be checked, not whether it's inserted
  3246. * into a container. For that, you'll want `viewAttachedToContainer` below.
  3247. */
  3248. function viewAttachedToChangeDetector(view) {
  3249. return (view[FLAGS] & 128 /* LViewFlags.Attached */) === 128 /* LViewFlags.Attached */;
  3250. }
  3251. /** Returns a boolean for whether the view is attached to a container. */
  3252. function viewAttachedToContainer(view) {
  3253. return isLContainer(view[PARENT]);
  3254. }
  3255. function getConstant(consts, index) {
  3256. if (index === null || index === undefined)
  3257. return null;
  3258. ngDevMode && assertIndexInRange(consts, index);
  3259. return consts[index];
  3260. }
  3261. /**
  3262. * Resets the pre-order hook flags of the view.
  3263. * @param lView the LView on which the flags are reset
  3264. */
  3265. function resetPreOrderHookFlags(lView) {
  3266. lView[PREORDER_HOOK_FLAGS] = 0;
  3267. }
  3268. /**
  3269. * Adds the `RefreshView` flag from the lView and updates HAS_CHILD_VIEWS_TO_REFRESH flag of
  3270. * parents.
  3271. */
  3272. function markViewForRefresh(lView) {
  3273. if (lView[FLAGS] & 1024 /* LViewFlags.RefreshView */) {
  3274. return;
  3275. }
  3276. lView[FLAGS] |= 1024 /* LViewFlags.RefreshView */;
  3277. if (viewAttachedToChangeDetector(lView)) {
  3278. markAncestorsForTraversal(lView);
  3279. }
  3280. }
  3281. /**
  3282. * Walks up the LView hierarchy.
  3283. * @param nestingLevel Number of times to walk up in hierarchy.
  3284. * @param currentView View from which to start the lookup.
  3285. */
  3286. function walkUpViews(nestingLevel, currentView) {
  3287. while (nestingLevel > 0) {
  3288. ngDevMode &&
  3289. assertDefined(currentView[DECLARATION_VIEW], 'Declaration view should be defined if nesting level is greater than 0.');
  3290. currentView = currentView[DECLARATION_VIEW];
  3291. nestingLevel--;
  3292. }
  3293. return currentView;
  3294. }
  3295. function requiresRefreshOrTraversal(lView) {
  3296. return !!(lView[FLAGS] & (1024 /* LViewFlags.RefreshView */ | 8192 /* LViewFlags.HasChildViewsToRefresh */) ||
  3297. lView[REACTIVE_TEMPLATE_CONSUMER]?.dirty);
  3298. }
  3299. /**
  3300. * Updates the `HasChildViewsToRefresh` flag on the parents of the `LView` as well as the
  3301. * parents above.
  3302. */
  3303. function updateAncestorTraversalFlagsOnAttach(lView) {
  3304. lView[ENVIRONMENT].changeDetectionScheduler?.notify(8 /* NotificationSource.ViewAttached */);
  3305. if (lView[FLAGS] & 64 /* LViewFlags.Dirty */) {
  3306. lView[FLAGS] |= 1024 /* LViewFlags.RefreshView */;
  3307. }
  3308. if (requiresRefreshOrTraversal(lView)) {
  3309. markAncestorsForTraversal(lView);
  3310. }
  3311. }
  3312. /**
  3313. * Ensures views above the given `lView` are traversed during change detection even when they are
  3314. * not dirty.
  3315. *
  3316. * This is done by setting the `HAS_CHILD_VIEWS_TO_REFRESH` flag up to the root, stopping when the
  3317. * flag is already `true` or the `lView` is detached.
  3318. */
  3319. function markAncestorsForTraversal(lView) {
  3320. lView[ENVIRONMENT].changeDetectionScheduler?.notify(0 /* NotificationSource.MarkAncestorsForTraversal */);
  3321. let parent = getLViewParent(lView);
  3322. while (parent !== null) {
  3323. // We stop adding markers to the ancestors once we reach one that already has the marker. This
  3324. // is to avoid needlessly traversing all the way to the root when the marker already exists.
  3325. if (parent[FLAGS] & 8192 /* LViewFlags.HasChildViewsToRefresh */) {
  3326. break;
  3327. }
  3328. parent[FLAGS] |= 8192 /* LViewFlags.HasChildViewsToRefresh */;
  3329. if (!viewAttachedToChangeDetector(parent)) {
  3330. break;
  3331. }
  3332. parent = getLViewParent(parent);
  3333. }
  3334. }
  3335. /**
  3336. * Stores a LView-specific destroy callback.
  3337. */
  3338. function storeLViewOnDestroy(lView, onDestroyCallback) {
  3339. if (isDestroyed(lView)) {
  3340. throw new RuntimeError(911 /* RuntimeErrorCode.VIEW_ALREADY_DESTROYED */, ngDevMode && 'View has already been destroyed.');
  3341. }
  3342. if (lView[ON_DESTROY_HOOKS] === null) {
  3343. lView[ON_DESTROY_HOOKS] = [];
  3344. }
  3345. lView[ON_DESTROY_HOOKS].push(onDestroyCallback);
  3346. }
  3347. /**
  3348. * Removes previously registered LView-specific destroy callback.
  3349. */
  3350. function removeLViewOnDestroy(lView, onDestroyCallback) {
  3351. if (lView[ON_DESTROY_HOOKS] === null)
  3352. return;
  3353. const destroyCBIdx = lView[ON_DESTROY_HOOKS].indexOf(onDestroyCallback);
  3354. if (destroyCBIdx !== -1) {
  3355. lView[ON_DESTROY_HOOKS].splice(destroyCBIdx, 1);
  3356. }
  3357. }
  3358. /**
  3359. * Gets the parent LView of the passed LView, if the PARENT is an LContainer, will get the parent of
  3360. * that LContainer, which is an LView
  3361. * @param lView the lView whose parent to get
  3362. */
  3363. function getLViewParent(lView) {
  3364. ngDevMode && assertLView(lView);
  3365. const parent = lView[PARENT];
  3366. return isLContainer(parent) ? parent[PARENT] : parent;
  3367. }
  3368. function getOrCreateLViewCleanup(view) {
  3369. // top level variables should not be exported for performance reasons (PERF_NOTES.md)
  3370. return (view[CLEANUP] ??= []);
  3371. }
  3372. function getOrCreateTViewCleanup(tView) {
  3373. return (tView.cleanup ??= []);
  3374. }
  3375. /**
  3376. * Saves context for this cleanup function in LView.cleanupInstances.
  3377. *
  3378. * On the first template pass, saves in TView:
  3379. * - Cleanup function
  3380. * - Index of context we just saved in LView.cleanupInstances
  3381. */
  3382. function storeCleanupWithContext(tView, lView, context, cleanupFn) {
  3383. const lCleanup = getOrCreateLViewCleanup(lView);
  3384. // Historically the `storeCleanupWithContext` was used to register both framework-level and
  3385. // user-defined cleanup callbacks, but over time those two types of cleanups were separated.
  3386. // This dev mode checks assures that user-level cleanup callbacks are _not_ stored in data
  3387. // structures reserved for framework-specific hooks.
  3388. ngDevMode &&
  3389. assertDefined(context, 'Cleanup context is mandatory when registering framework-level destroy hooks');
  3390. lCleanup.push(context);
  3391. if (tView.firstCreatePass) {
  3392. getOrCreateTViewCleanup(tView).push(cleanupFn, lCleanup.length - 1);
  3393. }
  3394. else {
  3395. // Make sure that no new framework-level cleanup functions are registered after the first
  3396. // template pass is done (and TView data structures are meant to fully constructed).
  3397. if (ngDevMode) {
  3398. Object.freeze(getOrCreateTViewCleanup(tView));
  3399. }
  3400. }
  3401. }
  3402. const instructionState = {
  3403. lFrame: createLFrame(null),
  3404. bindingsEnabled: true,
  3405. skipHydrationRootTNode: null,
  3406. };
  3407. var CheckNoChangesMode;
  3408. (function (CheckNoChangesMode) {
  3409. CheckNoChangesMode[CheckNoChangesMode["Off"] = 0] = "Off";
  3410. CheckNoChangesMode[CheckNoChangesMode["Exhaustive"] = 1] = "Exhaustive";
  3411. CheckNoChangesMode[CheckNoChangesMode["OnlyDirtyViews"] = 2] = "OnlyDirtyViews";
  3412. })(CheckNoChangesMode || (CheckNoChangesMode = {}));
  3413. /**
  3414. * In this mode, any changes in bindings will throw an ExpressionChangedAfterChecked error.
  3415. *
  3416. * Necessary to support ChangeDetectorRef.checkNoChanges().
  3417. *
  3418. * The `checkNoChanges` function is invoked only in ngDevMode=true and verifies that no unintended
  3419. * changes exist in the change detector or its children.
  3420. */
  3421. let _checkNoChangesMode = 0; /* CheckNoChangesMode.Off */
  3422. /**
  3423. * Flag used to indicate that we are in the middle running change detection on a view
  3424. *
  3425. * @see detectChangesInViewWhileDirty
  3426. */
  3427. let _isRefreshingViews = false;
  3428. function getElementDepthCount() {
  3429. return instructionState.lFrame.elementDepthCount;
  3430. }
  3431. function increaseElementDepthCount() {
  3432. instructionState.lFrame.elementDepthCount++;
  3433. }
  3434. function decreaseElementDepthCount() {
  3435. instructionState.lFrame.elementDepthCount--;
  3436. }
  3437. function getBindingsEnabled() {
  3438. return instructionState.bindingsEnabled;
  3439. }
  3440. /**
  3441. * Returns true if currently inside a skip hydration block.
  3442. * @returns boolean
  3443. */
  3444. function isInSkipHydrationBlock$1() {
  3445. return instructionState.skipHydrationRootTNode !== null;
  3446. }
  3447. /**
  3448. * Returns true if this is the root TNode of the skip hydration block.
  3449. * @param tNode the current TNode
  3450. * @returns boolean
  3451. */
  3452. function isSkipHydrationRootTNode(tNode) {
  3453. return instructionState.skipHydrationRootTNode === tNode;
  3454. }
  3455. /**
  3456. * Enables directive matching on elements.
  3457. *
  3458. * * Example:
  3459. * ```html
  3460. * <my-comp my-directive>
  3461. * Should match component / directive.
  3462. * </my-comp>
  3463. * <div ngNonBindable>
  3464. * <!-- ɵɵdisableBindings() -->
  3465. * <my-comp my-directive>
  3466. * Should not match component / directive because we are in ngNonBindable.
  3467. * </my-comp>
  3468. * <!-- ɵɵenableBindings() -->
  3469. * </div>
  3470. * ```
  3471. *
  3472. * @codeGenApi
  3473. */
  3474. function ɵɵenableBindings() {
  3475. instructionState.bindingsEnabled = true;
  3476. }
  3477. /**
  3478. * Sets a flag to specify that the TNode is in a skip hydration block.
  3479. * @param tNode the current TNode
  3480. */
  3481. function enterSkipHydrationBlock(tNode) {
  3482. instructionState.skipHydrationRootTNode = tNode;
  3483. }
  3484. /**
  3485. * Disables directive matching on element.
  3486. *
  3487. * * Example:
  3488. * ```html
  3489. * <my-comp my-directive>
  3490. * Should match component / directive.
  3491. * </my-comp>
  3492. * <div ngNonBindable>
  3493. * <!-- ɵɵdisableBindings() -->
  3494. * <my-comp my-directive>
  3495. * Should not match component / directive because we are in ngNonBindable.
  3496. * </my-comp>
  3497. * <!-- ɵɵenableBindings() -->
  3498. * </div>
  3499. * ```
  3500. *
  3501. * @codeGenApi
  3502. */
  3503. function ɵɵdisableBindings() {
  3504. instructionState.bindingsEnabled = false;
  3505. }
  3506. /**
  3507. * Clears the root skip hydration node when leaving a skip hydration block.
  3508. */
  3509. function leaveSkipHydrationBlock() {
  3510. instructionState.skipHydrationRootTNode = null;
  3511. }
  3512. /**
  3513. * Return the current `LView`.
  3514. */
  3515. function getLView() {
  3516. return instructionState.lFrame.lView;
  3517. }
  3518. /**
  3519. * Return the current `TView`.
  3520. */
  3521. function getTView() {
  3522. return instructionState.lFrame.tView;
  3523. }
  3524. /**
  3525. * Restores `contextViewData` to the given OpaqueViewState instance.
  3526. *
  3527. * Used in conjunction with the getCurrentView() instruction to save a snapshot
  3528. * of the current view and restore it when listeners are invoked. This allows
  3529. * walking the declaration view tree in listeners to get vars from parent views.
  3530. *
  3531. * @param viewToRestore The OpaqueViewState instance to restore.
  3532. * @returns Context of the restored OpaqueViewState instance.
  3533. *
  3534. * @codeGenApi
  3535. */
  3536. function ɵɵrestoreView(viewToRestore) {
  3537. instructionState.lFrame.contextLView = viewToRestore;
  3538. return viewToRestore[CONTEXT];
  3539. }
  3540. /**
  3541. * Clears the view set in `ɵɵrestoreView` from memory. Returns the passed in
  3542. * value so that it can be used as a return value of an instruction.
  3543. *
  3544. * @codeGenApi
  3545. */
  3546. function ɵɵresetView(value) {
  3547. instructionState.lFrame.contextLView = null;
  3548. return value;
  3549. }
  3550. function getCurrentTNode() {
  3551. let currentTNode = getCurrentTNodePlaceholderOk();
  3552. while (currentTNode !== null && currentTNode.type === 64 /* TNodeType.Placeholder */) {
  3553. currentTNode = currentTNode.parent;
  3554. }
  3555. return currentTNode;
  3556. }
  3557. function getCurrentTNodePlaceholderOk() {
  3558. return instructionState.lFrame.currentTNode;
  3559. }
  3560. function getCurrentParentTNode() {
  3561. const lFrame = instructionState.lFrame;
  3562. const currentTNode = lFrame.currentTNode;
  3563. return lFrame.isParent ? currentTNode : currentTNode.parent;
  3564. }
  3565. function setCurrentTNode(tNode, isParent) {
  3566. ngDevMode && tNode && assertTNodeForTView(tNode, instructionState.lFrame.tView);
  3567. const lFrame = instructionState.lFrame;
  3568. lFrame.currentTNode = tNode;
  3569. lFrame.isParent = isParent;
  3570. }
  3571. function isCurrentTNodeParent() {
  3572. return instructionState.lFrame.isParent;
  3573. }
  3574. function setCurrentTNodeAsNotParent() {
  3575. instructionState.lFrame.isParent = false;
  3576. }
  3577. function getContextLView() {
  3578. const contextLView = instructionState.lFrame.contextLView;
  3579. ngDevMode && assertDefined(contextLView, 'contextLView must be defined.');
  3580. return contextLView;
  3581. }
  3582. function isInCheckNoChangesMode() {
  3583. !ngDevMode && throwError('Must never be called in production mode');
  3584. return _checkNoChangesMode !== CheckNoChangesMode.Off;
  3585. }
  3586. function isExhaustiveCheckNoChanges() {
  3587. !ngDevMode && throwError('Must never be called in production mode');
  3588. return _checkNoChangesMode === CheckNoChangesMode.Exhaustive;
  3589. }
  3590. function setIsInCheckNoChangesMode(mode) {
  3591. !ngDevMode && throwError('Must never be called in production mode');
  3592. _checkNoChangesMode = mode;
  3593. }
  3594. function isRefreshingViews() {
  3595. return _isRefreshingViews;
  3596. }
  3597. function setIsRefreshingViews(mode) {
  3598. const prev = _isRefreshingViews;
  3599. _isRefreshingViews = mode;
  3600. return prev;
  3601. }
  3602. // top level variables should not be exported for performance reasons (PERF_NOTES.md)
  3603. function getBindingRoot() {
  3604. const lFrame = instructionState.lFrame;
  3605. let index = lFrame.bindingRootIndex;
  3606. if (index === -1) {
  3607. index = lFrame.bindingRootIndex = lFrame.tView.bindingStartIndex;
  3608. }
  3609. return index;
  3610. }
  3611. function getBindingIndex() {
  3612. return instructionState.lFrame.bindingIndex;
  3613. }
  3614. function setBindingIndex(value) {
  3615. return (instructionState.lFrame.bindingIndex = value);
  3616. }
  3617. function nextBindingIndex() {
  3618. return instructionState.lFrame.bindingIndex++;
  3619. }
  3620. function incrementBindingIndex(count) {
  3621. const lFrame = instructionState.lFrame;
  3622. const index = lFrame.bindingIndex;
  3623. lFrame.bindingIndex = lFrame.bindingIndex + count;
  3624. return index;
  3625. }
  3626. function isInI18nBlock() {
  3627. return instructionState.lFrame.inI18n;
  3628. }
  3629. function setInI18nBlock(isInI18nBlock) {
  3630. instructionState.lFrame.inI18n = isInI18nBlock;
  3631. }
  3632. /**
  3633. * Set a new binding root index so that host template functions can execute.
  3634. *
  3635. * Bindings inside the host template are 0 index. But because we don't know ahead of time
  3636. * how many host bindings we have we can't pre-compute them. For this reason they are all
  3637. * 0 index and we just shift the root so that they match next available location in the LView.
  3638. *
  3639. * @param bindingRootIndex Root index for `hostBindings`
  3640. * @param currentDirectiveIndex `TData[currentDirectiveIndex]` will point to the current directive
  3641. * whose `hostBindings` are being processed.
  3642. */
  3643. function setBindingRootForHostBindings(bindingRootIndex, currentDirectiveIndex) {
  3644. const lFrame = instructionState.lFrame;
  3645. lFrame.bindingIndex = lFrame.bindingRootIndex = bindingRootIndex;
  3646. setCurrentDirectiveIndex(currentDirectiveIndex);
  3647. }
  3648. /**
  3649. * When host binding is executing this points to the directive index.
  3650. * `TView.data[getCurrentDirectiveIndex()]` is `DirectiveDef`
  3651. * `LView[getCurrentDirectiveIndex()]` is directive instance.
  3652. */
  3653. function getCurrentDirectiveIndex() {
  3654. return instructionState.lFrame.currentDirectiveIndex;
  3655. }
  3656. /**
  3657. * Sets an index of a directive whose `hostBindings` are being processed.
  3658. *
  3659. * @param currentDirectiveIndex `TData` index where current directive instance can be found.
  3660. */
  3661. function setCurrentDirectiveIndex(currentDirectiveIndex) {
  3662. instructionState.lFrame.currentDirectiveIndex = currentDirectiveIndex;
  3663. }
  3664. /**
  3665. * Retrieve the current `DirectiveDef` which is active when `hostBindings` instruction is being
  3666. * executed.
  3667. *
  3668. * @param tData Current `TData` where the `DirectiveDef` will be looked up at.
  3669. */
  3670. function getCurrentDirectiveDef(tData) {
  3671. const currentDirectiveIndex = instructionState.lFrame.currentDirectiveIndex;
  3672. return currentDirectiveIndex === -1 ? null : tData[currentDirectiveIndex];
  3673. }
  3674. function getCurrentQueryIndex() {
  3675. return instructionState.lFrame.currentQueryIndex;
  3676. }
  3677. function setCurrentQueryIndex(value) {
  3678. instructionState.lFrame.currentQueryIndex = value;
  3679. }
  3680. /**
  3681. * Returns a `TNode` of the location where the current `LView` is declared at.
  3682. *
  3683. * @param lView an `LView` that we want to find parent `TNode` for.
  3684. */
  3685. function getDeclarationTNode(lView) {
  3686. const tView = lView[TVIEW];
  3687. // Return the declaration parent for embedded views
  3688. if (tView.type === 2 /* TViewType.Embedded */) {
  3689. ngDevMode && assertDefined(tView.declTNode, 'Embedded TNodes should have declaration parents.');
  3690. return tView.declTNode;
  3691. }
  3692. // Components don't have `TView.declTNode` because each instance of component could be
  3693. // inserted in different location, hence `TView.declTNode` is meaningless.
  3694. // Falling back to `T_HOST` in case we cross component boundary.
  3695. if (tView.type === 1 /* TViewType.Component */) {
  3696. return lView[T_HOST];
  3697. }
  3698. // Remaining TNode type is `TViewType.Root` which doesn't have a parent TNode.
  3699. return null;
  3700. }
  3701. /**
  3702. * This is a light weight version of the `enterView` which is needed by the DI system.
  3703. *
  3704. * @param lView `LView` location of the DI context.
  3705. * @param tNode `TNode` for DI context
  3706. * @param flags DI context flags. if `SkipSelf` flag is set than we walk up the declaration
  3707. * tree from `tNode` until we find parent declared `TElementNode`.
  3708. * @returns `true` if we have successfully entered DI associated with `tNode` (or with declared
  3709. * `TNode` if `flags` has `SkipSelf`). Failing to enter DI implies that no associated
  3710. * `NodeInjector` can be found and we should instead use `ModuleInjector`.
  3711. * - If `true` than this call must be fallowed by `leaveDI`
  3712. * - If `false` than this call failed and we should NOT call `leaveDI`
  3713. */
  3714. function enterDI(lView, tNode, flags) {
  3715. ngDevMode && assertLViewOrUndefined(lView);
  3716. if (flags & InjectFlags.SkipSelf) {
  3717. ngDevMode && assertTNodeForTView(tNode, lView[TVIEW]);
  3718. let parentTNode = tNode;
  3719. let parentLView = lView;
  3720. while (true) {
  3721. ngDevMode && assertDefined(parentTNode, 'Parent TNode should be defined');
  3722. parentTNode = parentTNode.parent;
  3723. if (parentTNode === null && !(flags & InjectFlags.Host)) {
  3724. parentTNode = getDeclarationTNode(parentLView);
  3725. if (parentTNode === null)
  3726. break;
  3727. // In this case, a parent exists and is definitely an element. So it will definitely
  3728. // have an existing lView as the declaration view, which is why we can assume it's defined.
  3729. ngDevMode && assertDefined(parentLView, 'Parent LView should be defined');
  3730. parentLView = parentLView[DECLARATION_VIEW];
  3731. // In Ivy there are Comment nodes that correspond to ngIf and NgFor embedded directives
  3732. // We want to skip those and look only at Elements and ElementContainers to ensure
  3733. // we're looking at true parent nodes, and not content or other types.
  3734. if (parentTNode.type & (2 /* TNodeType.Element */ | 8 /* TNodeType.ElementContainer */)) {
  3735. break;
  3736. }
  3737. }
  3738. else {
  3739. break;
  3740. }
  3741. }
  3742. if (parentTNode === null) {
  3743. // If we failed to find a parent TNode this means that we should use module injector.
  3744. return false;
  3745. }
  3746. else {
  3747. tNode = parentTNode;
  3748. lView = parentLView;
  3749. }
  3750. }
  3751. ngDevMode && assertTNodeForLView(tNode, lView);
  3752. const lFrame = (instructionState.lFrame = allocLFrame());
  3753. lFrame.currentTNode = tNode;
  3754. lFrame.lView = lView;
  3755. return true;
  3756. }
  3757. /**
  3758. * Swap the current lView with a new lView.
  3759. *
  3760. * For performance reasons we store the lView in the top level of the module.
  3761. * This way we minimize the number of properties to read. Whenever a new view
  3762. * is entered we have to store the lView for later, and when the view is
  3763. * exited the state has to be restored
  3764. *
  3765. * @param newView New lView to become active
  3766. * @returns the previously active lView;
  3767. */
  3768. function enterView(newView) {
  3769. ngDevMode && assertNotEqual(newView[0], newView[1], '????');
  3770. ngDevMode && assertLViewOrUndefined(newView);
  3771. const newLFrame = allocLFrame();
  3772. if (ngDevMode) {
  3773. assertEqual(newLFrame.isParent, true, 'Expected clean LFrame');
  3774. assertEqual(newLFrame.lView, null, 'Expected clean LFrame');
  3775. assertEqual(newLFrame.tView, null, 'Expected clean LFrame');
  3776. assertEqual(newLFrame.selectedIndex, -1, 'Expected clean LFrame');
  3777. assertEqual(newLFrame.elementDepthCount, 0, 'Expected clean LFrame');
  3778. assertEqual(newLFrame.currentDirectiveIndex, -1, 'Expected clean LFrame');
  3779. assertEqual(newLFrame.currentNamespace, null, 'Expected clean LFrame');
  3780. assertEqual(newLFrame.bindingRootIndex, -1, 'Expected clean LFrame');
  3781. assertEqual(newLFrame.currentQueryIndex, 0, 'Expected clean LFrame');
  3782. }
  3783. const tView = newView[TVIEW];
  3784. instructionState.lFrame = newLFrame;
  3785. ngDevMode && tView.firstChild && assertTNodeForTView(tView.firstChild, tView);
  3786. newLFrame.currentTNode = tView.firstChild;
  3787. newLFrame.lView = newView;
  3788. newLFrame.tView = tView;
  3789. newLFrame.contextLView = newView;
  3790. newLFrame.bindingIndex = tView.bindingStartIndex;
  3791. newLFrame.inI18n = false;
  3792. }
  3793. /**
  3794. * Allocates next free LFrame. This function tries to reuse the `LFrame`s to lower memory pressure.
  3795. */
  3796. function allocLFrame() {
  3797. const currentLFrame = instructionState.lFrame;
  3798. const childLFrame = currentLFrame === null ? null : currentLFrame.child;
  3799. const newLFrame = childLFrame === null ? createLFrame(currentLFrame) : childLFrame;
  3800. return newLFrame;
  3801. }
  3802. function createLFrame(parent) {
  3803. const lFrame = {
  3804. currentTNode: null,
  3805. isParent: true,
  3806. lView: null,
  3807. tView: null,
  3808. selectedIndex: -1,
  3809. contextLView: null,
  3810. elementDepthCount: 0,
  3811. currentNamespace: null,
  3812. currentDirectiveIndex: -1,
  3813. bindingRootIndex: -1,
  3814. bindingIndex: -1,
  3815. currentQueryIndex: 0,
  3816. parent: parent,
  3817. child: null,
  3818. inI18n: false,
  3819. };
  3820. parent !== null && (parent.child = lFrame); // link the new LFrame for reuse.
  3821. return lFrame;
  3822. }
  3823. /**
  3824. * A lightweight version of leave which is used with DI.
  3825. *
  3826. * This function only resets `currentTNode` and `LView` as those are the only properties
  3827. * used with DI (`enterDI()`).
  3828. *
  3829. * NOTE: This function is reexported as `leaveDI`. However `leaveDI` has return type of `void` where
  3830. * as `leaveViewLight` has `LFrame`. This is so that `leaveViewLight` can be used in `leaveView`.
  3831. */
  3832. function leaveViewLight() {
  3833. const oldLFrame = instructionState.lFrame;
  3834. instructionState.lFrame = oldLFrame.parent;
  3835. oldLFrame.currentTNode = null;
  3836. oldLFrame.lView = null;
  3837. return oldLFrame;
  3838. }
  3839. /**
  3840. * This is a lightweight version of the `leaveView` which is needed by the DI system.
  3841. *
  3842. * NOTE: this function is an alias so that we can change the type of the function to have `void`
  3843. * return type.
  3844. */
  3845. const leaveDI = leaveViewLight;
  3846. /**
  3847. * Leave the current `LView`
  3848. *
  3849. * This pops the `LFrame` with the associated `LView` from the stack.
  3850. *
  3851. * IMPORTANT: We must zero out the `LFrame` values here otherwise they will be retained. This is
  3852. * because for performance reasons we don't release `LFrame` but rather keep it for next use.
  3853. */
  3854. function leaveView() {
  3855. const oldLFrame = leaveViewLight();
  3856. oldLFrame.isParent = true;
  3857. oldLFrame.tView = null;
  3858. oldLFrame.selectedIndex = -1;
  3859. oldLFrame.contextLView = null;
  3860. oldLFrame.elementDepthCount = 0;
  3861. oldLFrame.currentDirectiveIndex = -1;
  3862. oldLFrame.currentNamespace = null;
  3863. oldLFrame.bindingRootIndex = -1;
  3864. oldLFrame.bindingIndex = -1;
  3865. oldLFrame.currentQueryIndex = 0;
  3866. }
  3867. function nextContextImpl(level) {
  3868. const contextLView = (instructionState.lFrame.contextLView = walkUpViews(level, instructionState.lFrame.contextLView));
  3869. return contextLView[CONTEXT];
  3870. }
  3871. /**
  3872. * Gets the currently selected element index.
  3873. *
  3874. * Used with {@link property} instruction (and more in the future) to identify the index in the
  3875. * current `LView` to act on.
  3876. */
  3877. function getSelectedIndex() {
  3878. return instructionState.lFrame.selectedIndex;
  3879. }
  3880. /**
  3881. * Sets the most recent index passed to {@link select}
  3882. *
  3883. * Used with {@link property} instruction (and more in the future) to identify the index in the
  3884. * current `LView` to act on.
  3885. *
  3886. * (Note that if an "exit function" was set earlier (via `setElementExitFn()`) then that will be
  3887. * run if and when the provided `index` value is different from the current selected index value.)
  3888. */
  3889. function setSelectedIndex(index) {
  3890. ngDevMode &&
  3891. index !== -1 &&
  3892. assertGreaterThanOrEqual(index, HEADER_OFFSET, 'Index must be past HEADER_OFFSET (or -1).');
  3893. ngDevMode &&
  3894. assertLessThan(index, instructionState.lFrame.lView.length, "Can't set index passed end of LView");
  3895. instructionState.lFrame.selectedIndex = index;
  3896. }
  3897. /**
  3898. * Gets the `tNode` that represents currently selected element.
  3899. */
  3900. function getSelectedTNode() {
  3901. const lFrame = instructionState.lFrame;
  3902. return getTNode(lFrame.tView, lFrame.selectedIndex);
  3903. }
  3904. /**
  3905. * Sets the namespace used to create elements to `'http://www.w3.org/2000/svg'` in global state.
  3906. *
  3907. * @codeGenApi
  3908. */
  3909. function ɵɵnamespaceSVG() {
  3910. instructionState.lFrame.currentNamespace = SVG_NAMESPACE;
  3911. }
  3912. /**
  3913. * Sets the namespace used to create elements to `'http://www.w3.org/1998/MathML/'` in global state.
  3914. *
  3915. * @codeGenApi
  3916. */
  3917. function ɵɵnamespaceMathML() {
  3918. instructionState.lFrame.currentNamespace = MATH_ML_NAMESPACE;
  3919. }
  3920. /**
  3921. * Sets the namespace used to create elements to `null`, which forces element creation to use
  3922. * `createElement` rather than `createElementNS`.
  3923. *
  3924. * @codeGenApi
  3925. */
  3926. function ɵɵnamespaceHTML() {
  3927. namespaceHTMLInternal();
  3928. }
  3929. /**
  3930. * Sets the namespace used to create elements to `null`, which forces element creation to use
  3931. * `createElement` rather than `createElementNS`.
  3932. */
  3933. function namespaceHTMLInternal() {
  3934. instructionState.lFrame.currentNamespace = null;
  3935. }
  3936. function getNamespace() {
  3937. return instructionState.lFrame.currentNamespace;
  3938. }
  3939. let _wasLastNodeCreated = true;
  3940. /**
  3941. * Retrieves a global flag that indicates whether the most recent DOM node
  3942. * was created or hydrated.
  3943. */
  3944. function wasLastNodeCreated() {
  3945. return _wasLastNodeCreated;
  3946. }
  3947. /**
  3948. * Sets a global flag to indicate whether the most recent DOM node
  3949. * was created or hydrated.
  3950. */
  3951. function lastNodeWasCreated(flag) {
  3952. _wasLastNodeCreated = flag;
  3953. }
  3954. /**
  3955. * Adds all directive lifecycle hooks from the given `DirectiveDef` to the given `TView`.
  3956. *
  3957. * Must be run *only* on the first template pass.
  3958. *
  3959. * Sets up the pre-order hooks on the provided `tView`,
  3960. * see {@link HookData} for details about the data structure.
  3961. *
  3962. * @param directiveIndex The index of the directive in LView
  3963. * @param directiveDef The definition containing the hooks to setup in tView
  3964. * @param tView The current TView
  3965. */
  3966. function registerPreOrderHooks(directiveIndex, directiveDef, tView) {
  3967. ngDevMode && assertFirstCreatePass(tView);
  3968. const { ngOnChanges, ngOnInit, ngDoCheck } = directiveDef.type.prototype;
  3969. if (ngOnChanges) {
  3970. const wrappedOnChanges = NgOnChangesFeatureImpl(directiveDef);
  3971. (tView.preOrderHooks ??= []).push(directiveIndex, wrappedOnChanges);
  3972. (tView.preOrderCheckHooks ??= []).push(directiveIndex, wrappedOnChanges);
  3973. }
  3974. if (ngOnInit) {
  3975. (tView.preOrderHooks ??= []).push(0 - directiveIndex, ngOnInit);
  3976. }
  3977. if (ngDoCheck) {
  3978. (tView.preOrderHooks ??= []).push(directiveIndex, ngDoCheck);
  3979. (tView.preOrderCheckHooks ??= []).push(directiveIndex, ngDoCheck);
  3980. }
  3981. }
  3982. /**
  3983. *
  3984. * Loops through the directives on the provided `tNode` and queues hooks to be
  3985. * run that are not initialization hooks.
  3986. *
  3987. * Should be executed during `elementEnd()` and similar to
  3988. * preserve hook execution order. Content, view, and destroy hooks for projected
  3989. * components and directives must be called *before* their hosts.
  3990. *
  3991. * Sets up the content, view, and destroy hooks on the provided `tView`,
  3992. * see {@link HookData} for details about the data structure.
  3993. *
  3994. * NOTE: This does not set up `onChanges`, `onInit` or `doCheck`, those are set up
  3995. * separately at `elementStart`.
  3996. *
  3997. * @param tView The current TView
  3998. * @param tNode The TNode whose directives are to be searched for hooks to queue
  3999. */
  4000. function registerPostOrderHooks(tView, tNode) {
  4001. ngDevMode && assertFirstCreatePass(tView);
  4002. // It's necessary to loop through the directives at elementEnd() (rather than processing in
  4003. // directiveCreate) so we can preserve the current hook order. Content, view, and destroy
  4004. // hooks for projected components and directives must be called *before* their hosts.
  4005. for (let i = tNode.directiveStart, end = tNode.directiveEnd; i < end; i++) {
  4006. const directiveDef = tView.data[i];
  4007. ngDevMode && assertDefined(directiveDef, 'Expecting DirectiveDef');
  4008. const lifecycleHooks = directiveDef.type.prototype;
  4009. const { ngAfterContentInit, ngAfterContentChecked, ngAfterViewInit, ngAfterViewChecked, ngOnDestroy, } = lifecycleHooks;
  4010. if (ngAfterContentInit) {
  4011. (tView.contentHooks ??= []).push(-i, ngAfterContentInit);
  4012. }
  4013. if (ngAfterContentChecked) {
  4014. (tView.contentHooks ??= []).push(i, ngAfterContentChecked);
  4015. (tView.contentCheckHooks ??= []).push(i, ngAfterContentChecked);
  4016. }
  4017. if (ngAfterViewInit) {
  4018. (tView.viewHooks ??= []).push(-i, ngAfterViewInit);
  4019. }
  4020. if (ngAfterViewChecked) {
  4021. (tView.viewHooks ??= []).push(i, ngAfterViewChecked);
  4022. (tView.viewCheckHooks ??= []).push(i, ngAfterViewChecked);
  4023. }
  4024. if (ngOnDestroy != null) {
  4025. (tView.destroyHooks ??= []).push(i, ngOnDestroy);
  4026. }
  4027. }
  4028. }
  4029. /**
  4030. * Executing hooks requires complex logic as we need to deal with 2 constraints.
  4031. *
  4032. * 1. Init hooks (ngOnInit, ngAfterContentInit, ngAfterViewInit) must all be executed once and only
  4033. * once, across many change detection cycles. This must be true even if some hooks throw, or if
  4034. * some recursively trigger a change detection cycle.
  4035. * To solve that, it is required to track the state of the execution of these init hooks.
  4036. * This is done by storing and maintaining flags in the view: the {@link InitPhaseState},
  4037. * and the index within that phase. They can be seen as a cursor in the following structure:
  4038. * [[onInit1, onInit2], [afterContentInit1], [afterViewInit1, afterViewInit2, afterViewInit3]]
  4039. * They are stored as flags in LView[FLAGS].
  4040. *
  4041. * 2. Pre-order hooks can be executed in batches, because of the select instruction.
  4042. * To be able to pause and resume their execution, we also need some state about the hook's array
  4043. * that is being processed:
  4044. * - the index of the next hook to be executed
  4045. * - the number of init hooks already found in the processed part of the array
  4046. * They are stored as flags in LView[PREORDER_HOOK_FLAGS].
  4047. */
  4048. /**
  4049. * Executes pre-order check hooks ( OnChanges, DoChanges) given a view where all the init hooks were
  4050. * executed once. This is a light version of executeInitAndCheckPreOrderHooks where we can skip read
  4051. * / write of the init-hooks related flags.
  4052. * @param lView The LView where hooks are defined
  4053. * @param hooks Hooks to be run
  4054. * @param nodeIndex 3 cases depending on the value:
  4055. * - undefined: all hooks from the array should be executed (post-order case)
  4056. * - null: execute hooks only from the saved index until the end of the array (pre-order case, when
  4057. * flushing the remaining hooks)
  4058. * - number: execute hooks only from the saved index until that node index exclusive (pre-order
  4059. * case, when executing select(number))
  4060. */
  4061. function executeCheckHooks(lView, hooks, nodeIndex) {
  4062. callHooks(lView, hooks, 3 /* InitPhaseState.InitPhaseCompleted */, nodeIndex);
  4063. }
  4064. /**
  4065. * Executes post-order init and check hooks (one of AfterContentInit, AfterContentChecked,
  4066. * AfterViewInit, AfterViewChecked) given a view where there are pending init hooks to be executed.
  4067. * @param lView The LView where hooks are defined
  4068. * @param hooks Hooks to be run
  4069. * @param initPhase A phase for which hooks should be run
  4070. * @param nodeIndex 3 cases depending on the value:
  4071. * - undefined: all hooks from the array should be executed (post-order case)
  4072. * - null: execute hooks only from the saved index until the end of the array (pre-order case, when
  4073. * flushing the remaining hooks)
  4074. * - number: execute hooks only from the saved index until that node index exclusive (pre-order
  4075. * case, when executing select(number))
  4076. */
  4077. function executeInitAndCheckHooks(lView, hooks, initPhase, nodeIndex) {
  4078. ngDevMode &&
  4079. assertNotEqual(initPhase, 3 /* InitPhaseState.InitPhaseCompleted */, 'Init pre-order hooks should not be called more than once');
  4080. if ((lView[FLAGS] & 3 /* LViewFlags.InitPhaseStateMask */) === initPhase) {
  4081. callHooks(lView, hooks, initPhase, nodeIndex);
  4082. }
  4083. }
  4084. function incrementInitPhaseFlags(lView, initPhase) {
  4085. ngDevMode &&
  4086. assertNotEqual(initPhase, 3 /* InitPhaseState.InitPhaseCompleted */, 'Init hooks phase should not be incremented after all init hooks have been run.');
  4087. let flags = lView[FLAGS];
  4088. if ((flags & 3 /* LViewFlags.InitPhaseStateMask */) === initPhase) {
  4089. flags &= 16383 /* LViewFlags.IndexWithinInitPhaseReset */;
  4090. flags += 1 /* LViewFlags.InitPhaseStateIncrementer */;
  4091. lView[FLAGS] = flags;
  4092. }
  4093. }
  4094. /**
  4095. * Calls lifecycle hooks with their contexts, skipping init hooks if it's not
  4096. * the first LView pass
  4097. *
  4098. * @param currentView The current view
  4099. * @param arr The array in which the hooks are found
  4100. * @param initPhaseState the current state of the init phase
  4101. * @param currentNodeIndex 3 cases depending on the value:
  4102. * - undefined: all hooks from the array should be executed (post-order case)
  4103. * - null: execute hooks only from the saved index until the end of the array (pre-order case, when
  4104. * flushing the remaining hooks)
  4105. * - number: execute hooks only from the saved index until that node index exclusive (pre-order
  4106. * case, when executing select(number))
  4107. */
  4108. function callHooks(currentView, arr, initPhase, currentNodeIndex) {
  4109. ngDevMode &&
  4110. assertEqual(isInCheckNoChangesMode(), false, 'Hooks should never be run when in check no changes mode.');
  4111. const startIndex = currentNodeIndex !== undefined
  4112. ? currentView[PREORDER_HOOK_FLAGS] & 65535 /* PreOrderHookFlags.IndexOfTheNextPreOrderHookMaskMask */
  4113. : 0;
  4114. const nodeIndexLimit = currentNodeIndex != null ? currentNodeIndex : -1;
  4115. const max = arr.length - 1; // Stop the loop at length - 1, because we look for the hook at i + 1
  4116. let lastNodeIndexFound = 0;
  4117. for (let i = startIndex; i < max; i++) {
  4118. const hook = arr[i + 1];
  4119. if (typeof hook === 'number') {
  4120. lastNodeIndexFound = arr[i];
  4121. if (currentNodeIndex != null && lastNodeIndexFound >= currentNodeIndex) {
  4122. break;
  4123. }
  4124. }
  4125. else {
  4126. const isInitHook = arr[i] < 0;
  4127. if (isInitHook) {
  4128. currentView[PREORDER_HOOK_FLAGS] += 65536 /* PreOrderHookFlags.NumberOfInitHooksCalledIncrementer */;
  4129. }
  4130. if (lastNodeIndexFound < nodeIndexLimit || nodeIndexLimit == -1) {
  4131. callHook(currentView, initPhase, arr, i);
  4132. currentView[PREORDER_HOOK_FLAGS] =
  4133. (currentView[PREORDER_HOOK_FLAGS] & 4294901760 /* PreOrderHookFlags.NumberOfInitHooksCalledMask */) +
  4134. i +
  4135. 2;
  4136. }
  4137. i++;
  4138. }
  4139. }
  4140. }
  4141. /**
  4142. * Executes a single lifecycle hook, making sure that:
  4143. * - it is called in the non-reactive context;
  4144. * - profiling data are registered.
  4145. */
  4146. function callHookInternal(directive, hook) {
  4147. profiler(4 /* ProfilerEvent.LifecycleHookStart */, directive, hook);
  4148. const prevConsumer = setActiveConsumer$1(null);
  4149. try {
  4150. hook.call(directive);
  4151. }
  4152. finally {
  4153. setActiveConsumer$1(prevConsumer);
  4154. profiler(5 /* ProfilerEvent.LifecycleHookEnd */, directive, hook);
  4155. }
  4156. }
  4157. /**
  4158. * Execute one hook against the current `LView`.
  4159. *
  4160. * @param currentView The current view
  4161. * @param initPhaseState the current state of the init phase
  4162. * @param arr The array in which the hooks are found
  4163. * @param i The current index within the hook data array
  4164. */
  4165. function callHook(currentView, initPhase, arr, i) {
  4166. const isInitHook = arr[i] < 0;
  4167. const hook = arr[i + 1];
  4168. const directiveIndex = isInitHook ? -arr[i] : arr[i];
  4169. const directive = currentView[directiveIndex];
  4170. if (isInitHook) {
  4171. const indexWithintInitPhase = currentView[FLAGS] >> 14 /* LViewFlags.IndexWithinInitPhaseShift */;
  4172. // The init phase state must be always checked here as it may have been recursively updated.
  4173. if (indexWithintInitPhase <
  4174. currentView[PREORDER_HOOK_FLAGS] >> 16 /* PreOrderHookFlags.NumberOfInitHooksCalledShift */ &&
  4175. (currentView[FLAGS] & 3 /* LViewFlags.InitPhaseStateMask */) === initPhase) {
  4176. currentView[FLAGS] += 16384 /* LViewFlags.IndexWithinInitPhaseIncrementer */;
  4177. callHookInternal(directive, hook);
  4178. }
  4179. }
  4180. else {
  4181. callHookInternal(directive, hook);
  4182. }
  4183. }
  4184. const NO_PARENT_INJECTOR = -1;
  4185. /**
  4186. * Each injector is saved in 9 contiguous slots in `LView` and 9 contiguous slots in
  4187. * `TView.data`. This allows us to store information about the current node's tokens (which
  4188. * can be shared in `TView`) as well as the tokens of its ancestor nodes (which cannot be
  4189. * shared, so they live in `LView`).
  4190. *
  4191. * Each of these slots (aside from the last slot) contains a bloom filter. This bloom filter
  4192. * determines whether a directive is available on the associated node or not. This prevents us
  4193. * from searching the directives array at this level unless it's probable the directive is in it.
  4194. *
  4195. * See: https://en.wikipedia.org/wiki/Bloom_filter for more about bloom filters.
  4196. *
  4197. * Because all injectors have been flattened into `LView` and `TViewData`, they cannot typed
  4198. * using interfaces as they were previously. The start index of each `LInjector` and `TInjector`
  4199. * will differ based on where it is flattened into the main array, so it's not possible to know
  4200. * the indices ahead of time and save their types here. The interfaces are still included here
  4201. * for documentation purposes.
  4202. *
  4203. * export interface LInjector extends Array<any> {
  4204. *
  4205. * // Cumulative bloom for directive IDs 0-31 (IDs are % BLOOM_SIZE)
  4206. * [0]: number;
  4207. *
  4208. * // Cumulative bloom for directive IDs 32-63
  4209. * [1]: number;
  4210. *
  4211. * // Cumulative bloom for directive IDs 64-95
  4212. * [2]: number;
  4213. *
  4214. * // Cumulative bloom for directive IDs 96-127
  4215. * [3]: number;
  4216. *
  4217. * // Cumulative bloom for directive IDs 128-159
  4218. * [4]: number;
  4219. *
  4220. * // Cumulative bloom for directive IDs 160 - 191
  4221. * [5]: number;
  4222. *
  4223. * // Cumulative bloom for directive IDs 192 - 223
  4224. * [6]: number;
  4225. *
  4226. * // Cumulative bloom for directive IDs 224 - 255
  4227. * [7]: number;
  4228. *
  4229. * // We need to store a reference to the injector's parent so DI can keep looking up
  4230. * // the injector tree until it finds the dependency it's looking for.
  4231. * [PARENT_INJECTOR]: number;
  4232. * }
  4233. *
  4234. * export interface TInjector extends Array<any> {
  4235. *
  4236. * // Shared node bloom for directive IDs 0-31 (IDs are % BLOOM_SIZE)
  4237. * [0]: number;
  4238. *
  4239. * // Shared node bloom for directive IDs 32-63
  4240. * [1]: number;
  4241. *
  4242. * // Shared node bloom for directive IDs 64-95
  4243. * [2]: number;
  4244. *
  4245. * // Shared node bloom for directive IDs 96-127
  4246. * [3]: number;
  4247. *
  4248. * // Shared node bloom for directive IDs 128-159
  4249. * [4]: number;
  4250. *
  4251. * // Shared node bloom for directive IDs 160 - 191
  4252. * [5]: number;
  4253. *
  4254. * // Shared node bloom for directive IDs 192 - 223
  4255. * [6]: number;
  4256. *
  4257. * // Shared node bloom for directive IDs 224 - 255
  4258. * [7]: number;
  4259. *
  4260. * // Necessary to find directive indices for a particular node.
  4261. * [TNODE]: TElementNode|TElementContainerNode|TContainerNode;
  4262. * }
  4263. */
  4264. /**
  4265. * Factory for creating instances of injectors in the NodeInjector.
  4266. *
  4267. * This factory is complicated by the fact that it can resolve `multi` factories as well.
  4268. *
  4269. * NOTE: Some of the fields are optional which means that this class has two hidden classes.
  4270. * - One without `multi` support (most common)
  4271. * - One with `multi` values, (rare).
  4272. *
  4273. * Since VMs can cache up to 4 inline hidden classes this is OK.
  4274. *
  4275. * - Single factory: Only `resolving` and `factory` is defined.
  4276. * - `providers` factory: `componentProviders` is a number and `index = -1`.
  4277. * - `viewProviders` factory: `componentProviders` is a number and `index` points to `providers`.
  4278. */
  4279. class NodeInjectorFactory {
  4280. factory;
  4281. /**
  4282. * The inject implementation to be activated when using the factory.
  4283. */
  4284. injectImpl;
  4285. /**
  4286. * Marker set to true during factory invocation to see if we get into recursive loop.
  4287. * Recursive loop causes an error to be displayed.
  4288. */
  4289. resolving = false;
  4290. /**
  4291. * Marks that the token can see other Tokens declared in `viewProviders` on the same node.
  4292. */
  4293. canSeeViewProviders;
  4294. /**
  4295. * An array of factories to use in case of `multi` provider.
  4296. */
  4297. multi;
  4298. /**
  4299. * Number of `multi`-providers which belong to the component.
  4300. *
  4301. * This is needed because when multiple components and directives declare the `multi` provider
  4302. * they have to be concatenated in the correct order.
  4303. *
  4304. * Example:
  4305. *
  4306. * If we have a component and directive active an a single element as declared here
  4307. * ```ts
  4308. * component:
  4309. * providers: [ {provide: String, useValue: 'component', multi: true} ],
  4310. * viewProviders: [ {provide: String, useValue: 'componentView', multi: true} ],
  4311. *
  4312. * directive:
  4313. * providers: [ {provide: String, useValue: 'directive', multi: true} ],
  4314. * ```
  4315. *
  4316. * Then the expected results are:
  4317. *
  4318. * ```ts
  4319. * providers: ['component', 'directive']
  4320. * viewProviders: ['component', 'componentView', 'directive']
  4321. * ```
  4322. *
  4323. * The way to think about it is that the `viewProviders` have been inserted after the component
  4324. * but before the directives, which is why we need to know how many `multi`s have been declared by
  4325. * the component.
  4326. */
  4327. componentProviders;
  4328. /**
  4329. * Current index of the Factory in the `data`. Needed for `viewProviders` and `providers` merging.
  4330. * See `providerFactory`.
  4331. */
  4332. index;
  4333. /**
  4334. * Because the same `multi` provider can be declared in `providers` and `viewProviders` it is
  4335. * possible for `viewProviders` to shadow the `providers`. For this reason we store the
  4336. * `provideFactory` of the `providers` so that `providers` can be extended with `viewProviders`.
  4337. *
  4338. * Example:
  4339. *
  4340. * Given:
  4341. * ```ts
  4342. * providers: [ {provide: String, useValue: 'all', multi: true} ],
  4343. * viewProviders: [ {provide: String, useValue: 'viewOnly', multi: true} ],
  4344. * ```
  4345. *
  4346. * We have to return `['all']` in case of content injection, but `['all', 'viewOnly']` in case
  4347. * of view injection. We further have to make sure that the shared instances (in our case
  4348. * `all`) are the exact same instance in both the content as well as the view injection. (We
  4349. * have to make sure that we don't double instantiate.) For this reason the `viewProviders`
  4350. * `Factory` has a pointer to the shadowed `providers` factory so that it can instantiate the
  4351. * `providers` (`['all']`) and then extend it with `viewProviders` (`['all'] + ['viewOnly'] =
  4352. * ['all', 'viewOnly']`).
  4353. */
  4354. providerFactory;
  4355. constructor(
  4356. /**
  4357. * Factory to invoke in order to create a new instance.
  4358. */
  4359. factory,
  4360. /**
  4361. * Set to `true` if the token is declared in `viewProviders` (or if it is component).
  4362. */
  4363. isViewProvider, injectImplementation) {
  4364. this.factory = factory;
  4365. ngDevMode && assertDefined(factory, 'Factory not specified');
  4366. ngDevMode && assertEqual(typeof factory, 'function', 'Expected factory function.');
  4367. this.canSeeViewProviders = isViewProvider;
  4368. this.injectImpl = injectImplementation;
  4369. }
  4370. }
  4371. /**
  4372. * Converts `TNodeType` into human readable text.
  4373. * Make sure this matches with `TNodeType`
  4374. */
  4375. function toTNodeTypeAsString(tNodeType) {
  4376. let text = '';
  4377. tNodeType & 1 /* TNodeType.Text */ && (text += '|Text');
  4378. tNodeType & 2 /* TNodeType.Element */ && (text += '|Element');
  4379. tNodeType & 4 /* TNodeType.Container */ && (text += '|Container');
  4380. tNodeType & 8 /* TNodeType.ElementContainer */ && (text += '|ElementContainer');
  4381. tNodeType & 16 /* TNodeType.Projection */ && (text += '|Projection');
  4382. tNodeType & 32 /* TNodeType.Icu */ && (text += '|IcuContainer');
  4383. tNodeType & 64 /* TNodeType.Placeholder */ && (text += '|Placeholder');
  4384. tNodeType & 128 /* TNodeType.LetDeclaration */ && (text += '|LetDeclaration');
  4385. return text.length > 0 ? text.substring(1) : text;
  4386. }
  4387. /**
  4388. * Helper function to detect if a given value matches a `TNode` shape.
  4389. *
  4390. * The logic uses the `insertBeforeIndex` and its possible values as
  4391. * a way to differentiate a TNode shape from other types of objects
  4392. * within the `TView.data`. This is not a perfect check, but it can
  4393. * be a reasonable differentiator, since we control the shapes of objects
  4394. * within `TView.data`.
  4395. */
  4396. function isTNodeShape(value) {
  4397. return (value != null &&
  4398. typeof value === 'object' &&
  4399. (value.insertBeforeIndex === null ||
  4400. typeof value.insertBeforeIndex === 'number' ||
  4401. Array.isArray(value.insertBeforeIndex)));
  4402. }
  4403. function isLetDeclaration(tNode) {
  4404. return !!(tNode.type & 128 /* TNodeType.LetDeclaration */);
  4405. }
  4406. /**
  4407. * Returns `true` if the `TNode` has a directive which has `@Input()` for `class` binding.
  4408. *
  4409. * ```html
  4410. * <div my-dir [class]="exp"></div>
  4411. * ```
  4412. * and
  4413. * ```ts
  4414. * @Directive({
  4415. * })
  4416. * class MyDirective {
  4417. * @Input()
  4418. * class: string;
  4419. * }
  4420. * ```
  4421. *
  4422. * In the above case it is necessary to write the reconciled styling information into the
  4423. * directive's input.
  4424. *
  4425. * @param tNode
  4426. */
  4427. function hasClassInput(tNode) {
  4428. return (tNode.flags & 8 /* TNodeFlags.hasClassInput */) !== 0;
  4429. }
  4430. /**
  4431. * Returns `true` if the `TNode` has a directive which has `@Input()` for `style` binding.
  4432. *
  4433. * ```html
  4434. * <div my-dir [style]="exp"></div>
  4435. * ```
  4436. * and
  4437. * ```ts
  4438. * @Directive({
  4439. * })
  4440. * class MyDirective {
  4441. * @Input()
  4442. * class: string;
  4443. * }
  4444. * ```
  4445. *
  4446. * In the above case it is necessary to write the reconciled styling information into the
  4447. * directive's input.
  4448. *
  4449. * @param tNode
  4450. */
  4451. function hasStyleInput(tNode) {
  4452. return (tNode.flags & 16 /* TNodeFlags.hasStyleInput */) !== 0;
  4453. }
  4454. function assertTNodeType(tNode, expectedTypes, message) {
  4455. assertDefined(tNode, 'should be called with a TNode');
  4456. if ((tNode.type & expectedTypes) === 0) {
  4457. throwError(message ||
  4458. `Expected [${toTNodeTypeAsString(expectedTypes)}] but got ${toTNodeTypeAsString(tNode.type)}.`);
  4459. }
  4460. }
  4461. function assertPureTNodeType(type) {
  4462. if (!(type === 2 /* TNodeType.Element */ ||
  4463. type === 1 /* TNodeType.Text */ ||
  4464. type === 4 /* TNodeType.Container */ ||
  4465. type === 8 /* TNodeType.ElementContainer */ ||
  4466. type === 32 /* TNodeType.Icu */ ||
  4467. type === 16 /* TNodeType.Projection */ ||
  4468. type === 64 /* TNodeType.Placeholder */ ||
  4469. type === 128 /* TNodeType.LetDeclaration */)) {
  4470. throwError(`Expected TNodeType to have only a single type selected, but got ${toTNodeTypeAsString(type)}.`);
  4471. }
  4472. }
  4473. /**
  4474. * Assigns all attribute values to the provided element via the inferred renderer.
  4475. *
  4476. * This function accepts two forms of attribute entries:
  4477. *
  4478. * default: (key, value):
  4479. * attrs = [key1, value1, key2, value2]
  4480. *
  4481. * namespaced: (NAMESPACE_MARKER, uri, name, value)
  4482. * attrs = [NAMESPACE_MARKER, uri, name, value, NAMESPACE_MARKER, uri, name, value]
  4483. *
  4484. * The `attrs` array can contain a mix of both the default and namespaced entries.
  4485. * The "default" values are set without a marker, but if the function comes across
  4486. * a marker value then it will attempt to set a namespaced value. If the marker is
  4487. * not of a namespaced value then the function will quit and return the index value
  4488. * where it stopped during the iteration of the attrs array.
  4489. *
  4490. * See [AttributeMarker] to understand what the namespace marker value is.
  4491. *
  4492. * Note that this instruction does not support assigning style and class values to
  4493. * an element. See `elementStart` and `elementHostAttrs` to learn how styling values
  4494. * are applied to an element.
  4495. * @param renderer The renderer to be used
  4496. * @param native The element that the attributes will be assigned to
  4497. * @param attrs The attribute array of values that will be assigned to the element
  4498. * @returns the index value that was last accessed in the attributes array
  4499. */
  4500. function setUpAttributes(renderer, native, attrs) {
  4501. let i = 0;
  4502. while (i < attrs.length) {
  4503. const value = attrs[i];
  4504. if (typeof value === 'number') {
  4505. // only namespaces are supported. Other value types (such as style/class
  4506. // entries) are not supported in this function.
  4507. if (value !== 0 /* AttributeMarker.NamespaceURI */) {
  4508. break;
  4509. }
  4510. // we just landed on the marker value ... therefore
  4511. // we should skip to the next entry
  4512. i++;
  4513. const namespaceURI = attrs[i++];
  4514. const attrName = attrs[i++];
  4515. const attrVal = attrs[i++];
  4516. ngDevMode && ngDevMode.rendererSetAttribute++;
  4517. renderer.setAttribute(native, attrName, attrVal, namespaceURI);
  4518. }
  4519. else {
  4520. // attrName is string;
  4521. const attrName = value;
  4522. const attrVal = attrs[++i];
  4523. // Standard attributes
  4524. ngDevMode && ngDevMode.rendererSetAttribute++;
  4525. if (isAnimationProp(attrName)) {
  4526. renderer.setProperty(native, attrName, attrVal);
  4527. }
  4528. else {
  4529. renderer.setAttribute(native, attrName, attrVal);
  4530. }
  4531. i++;
  4532. }
  4533. }
  4534. // another piece of code may iterate over the same attributes array. Therefore
  4535. // it may be helpful to return the exact spot where the attributes array exited
  4536. // whether by running into an unsupported marker or if all the static values were
  4537. // iterated over.
  4538. return i;
  4539. }
  4540. /**
  4541. * Test whether the given value is a marker that indicates that the following
  4542. * attribute values in a `TAttributes` array are only the names of attributes,
  4543. * and not name-value pairs.
  4544. * @param marker The attribute marker to test.
  4545. * @returns true if the marker is a "name-only" marker (e.g. `Bindings`, `Template` or `I18n`).
  4546. */
  4547. function isNameOnlyAttributeMarker(marker) {
  4548. return (marker === 3 /* AttributeMarker.Bindings */ ||
  4549. marker === 4 /* AttributeMarker.Template */ ||
  4550. marker === 6 /* AttributeMarker.I18n */);
  4551. }
  4552. function isAnimationProp(name) {
  4553. // Perf note: accessing charCodeAt to check for the first character of a string is faster as
  4554. // compared to accessing a character at index 0 (ex. name[0]). The main reason for this is that
  4555. // charCodeAt doesn't allocate memory to return a substring.
  4556. return name.charCodeAt(0) === 64 /* CharCode.AT_SIGN */;
  4557. }
  4558. /**
  4559. * Merges `src` `TAttributes` into `dst` `TAttributes` removing any duplicates in the process.
  4560. *
  4561. * This merge function keeps the order of attrs same.
  4562. *
  4563. * @param dst Location of where the merged `TAttributes` should end up.
  4564. * @param src `TAttributes` which should be appended to `dst`
  4565. */
  4566. function mergeHostAttrs(dst, src) {
  4567. if (src === null || src.length === 0) ;
  4568. else if (dst === null || dst.length === 0) {
  4569. // We have source, but dst is empty, just make a copy.
  4570. dst = src.slice();
  4571. }
  4572. else {
  4573. let srcMarker = -1 /* AttributeMarker.ImplicitAttributes */;
  4574. for (let i = 0; i < src.length; i++) {
  4575. const item = src[i];
  4576. if (typeof item === 'number') {
  4577. srcMarker = item;
  4578. }
  4579. else {
  4580. if (srcMarker === 0 /* AttributeMarker.NamespaceURI */) ;
  4581. else if (srcMarker === -1 /* AttributeMarker.ImplicitAttributes */ ||
  4582. srcMarker === 2 /* AttributeMarker.Styles */) {
  4583. // Case where we have to consume `key1` and `value` only.
  4584. mergeHostAttribute(dst, srcMarker, item, null, src[++i]);
  4585. }
  4586. else {
  4587. // Case where we have to consume `key1` only.
  4588. mergeHostAttribute(dst, srcMarker, item, null, null);
  4589. }
  4590. }
  4591. }
  4592. }
  4593. return dst;
  4594. }
  4595. /**
  4596. * Append `key`/`value` to existing `TAttributes` taking region marker and duplicates into account.
  4597. *
  4598. * @param dst `TAttributes` to append to.
  4599. * @param marker Region where the `key`/`value` should be added.
  4600. * @param key1 Key to add to `TAttributes`
  4601. * @param key2 Key to add to `TAttributes` (in case of `AttributeMarker.NamespaceURI`)
  4602. * @param value Value to add or to overwrite to `TAttributes` Only used if `marker` is not Class.
  4603. */
  4604. function mergeHostAttribute(dst, marker, key1, key2, value) {
  4605. let i = 0;
  4606. // Assume that new markers will be inserted at the end.
  4607. let markerInsertPosition = dst.length;
  4608. // scan until correct type.
  4609. if (marker === -1 /* AttributeMarker.ImplicitAttributes */) {
  4610. markerInsertPosition = -1;
  4611. }
  4612. else {
  4613. while (i < dst.length) {
  4614. const dstValue = dst[i++];
  4615. if (typeof dstValue === 'number') {
  4616. if (dstValue === marker) {
  4617. markerInsertPosition = -1;
  4618. break;
  4619. }
  4620. else if (dstValue > marker) {
  4621. // We need to save this as we want the markers to be inserted in specific order.
  4622. markerInsertPosition = i - 1;
  4623. break;
  4624. }
  4625. }
  4626. }
  4627. }
  4628. // search until you find place of insertion
  4629. while (i < dst.length) {
  4630. const item = dst[i];
  4631. if (typeof item === 'number') {
  4632. // since `i` started as the index after the marker, we did not find it if we are at the next
  4633. // marker
  4634. break;
  4635. }
  4636. else if (item === key1) {
  4637. // We already have same token
  4638. {
  4639. if (value !== null) {
  4640. dst[i + 1] = value;
  4641. }
  4642. return;
  4643. }
  4644. }
  4645. // Increment counter.
  4646. i++;
  4647. if (value !== null)
  4648. i++;
  4649. }
  4650. // insert at location.
  4651. if (markerInsertPosition !== -1) {
  4652. dst.splice(markerInsertPosition, 0, marker);
  4653. i = markerInsertPosition + 1;
  4654. }
  4655. dst.splice(i++, 0, key1);
  4656. if (value !== null) {
  4657. dst.splice(i++, 0, value);
  4658. }
  4659. }
  4660. // This default value is when checking the hierarchy for a token.
  4661. //
  4662. // It means both:
  4663. // - the token is not provided by the current injector,
  4664. // - only the element injectors should be checked (ie do not check module injectors
  4665. //
  4666. // mod1
  4667. // /
  4668. // el1 mod2
  4669. // \ /
  4670. // el2
  4671. //
  4672. // When requesting el2.injector.get(token), we should check in the following order and return the
  4673. // first found value:
  4674. // - el2.injector.get(token, default)
  4675. // - el1.injector.get(token, NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR) -> do not check the module
  4676. // - mod2.injector.get(token, default)
  4677. const NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR = {};
  4678. /**
  4679. * Injector that looks up a value using a specific injector, before falling back to the module
  4680. * injector. Used primarily when creating components or embedded views dynamically.
  4681. */
  4682. class ChainedInjector {
  4683. injector;
  4684. parentInjector;
  4685. constructor(injector, parentInjector) {
  4686. this.injector = injector;
  4687. this.parentInjector = parentInjector;
  4688. }
  4689. get(token, notFoundValue, flags) {
  4690. flags = convertToBitFlags(flags);
  4691. const value = this.injector.get(token, NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR, flags);
  4692. if (value !== NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR ||
  4693. notFoundValue === NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR) {
  4694. // Return the value from the root element injector when
  4695. // - it provides it
  4696. // (value !== NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR)
  4697. // - the module injector should not be checked
  4698. // (notFoundValue === NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR)
  4699. return value;
  4700. }
  4701. return this.parentInjector.get(token, notFoundValue, flags);
  4702. }
  4703. }
  4704. /// Parent Injector Utils ///////////////////////////////////////////////////////////////
  4705. function hasParentInjector(parentLocation) {
  4706. return parentLocation !== NO_PARENT_INJECTOR;
  4707. }
  4708. function getParentInjectorIndex(parentLocation) {
  4709. if (ngDevMode) {
  4710. assertNumber(parentLocation, 'Number expected');
  4711. assertNotEqual(parentLocation, -1, 'Not a valid state.');
  4712. const parentInjectorIndex = parentLocation & 32767 /* RelativeInjectorLocationFlags.InjectorIndexMask */;
  4713. assertGreaterThan(parentInjectorIndex, HEADER_OFFSET, 'Parent injector must be pointing past HEADER_OFFSET.');
  4714. }
  4715. return parentLocation & 32767 /* RelativeInjectorLocationFlags.InjectorIndexMask */;
  4716. }
  4717. function getParentInjectorViewOffset(parentLocation) {
  4718. return parentLocation >> 16 /* RelativeInjectorLocationFlags.ViewOffsetShift */;
  4719. }
  4720. /**
  4721. * Unwraps a parent injector location number to find the view offset from the current injector,
  4722. * then walks up the declaration view tree until the view is found that contains the parent
  4723. * injector.
  4724. *
  4725. * @param location The location of the parent injector, which contains the view offset
  4726. * @param startView The LView instance from which to start walking up the view tree
  4727. * @returns The LView instance that contains the parent injector
  4728. */
  4729. function getParentInjectorView(location, startView) {
  4730. let viewOffset = getParentInjectorViewOffset(location);
  4731. let parentView = startView;
  4732. // For most cases, the parent injector can be found on the host node (e.g. for component
  4733. // or container), but we must keep the loop here to support the rarer case of deeply nested
  4734. // <ng-template> tags or inline views, where the parent injector might live many views
  4735. // above the child injector.
  4736. while (viewOffset > 0) {
  4737. parentView = parentView[DECLARATION_VIEW];
  4738. viewOffset--;
  4739. }
  4740. return parentView;
  4741. }
  4742. /**
  4743. * Detects whether an injector is an instance of a `ChainedInjector`,
  4744. * created based on the `OutletInjector`.
  4745. */
  4746. function isRouterOutletInjector(currentInjector) {
  4747. return (currentInjector instanceof ChainedInjector &&
  4748. typeof currentInjector.injector.__ngOutletInjector === 'function');
  4749. }
  4750. /**
  4751. * Defines if the call to `inject` should include `viewProviders` in its resolution.
  4752. *
  4753. * This is set to true when we try to instantiate a component. This value is reset in
  4754. * `getNodeInjectable` to a value which matches the declaration location of the token about to be
  4755. * instantiated. This is done so that if we are injecting a token which was declared outside of
  4756. * `viewProviders` we don't accidentally pull `viewProviders` in.
  4757. *
  4758. * Example:
  4759. *
  4760. * ```ts
  4761. * @Injectable()
  4762. * class MyService {
  4763. * constructor(public value: String) {}
  4764. * }
  4765. *
  4766. * @Component({
  4767. * providers: [
  4768. * MyService,
  4769. * {provide: String, value: 'providers' }
  4770. * ]
  4771. * viewProviders: [
  4772. * {provide: String, value: 'viewProviders'}
  4773. * ]
  4774. * })
  4775. * class MyComponent {
  4776. * constructor(myService: MyService, value: String) {
  4777. * // We expect that Component can see into `viewProviders`.
  4778. * expect(value).toEqual('viewProviders');
  4779. * // `MyService` was not declared in `viewProviders` hence it can't see it.
  4780. * expect(myService.value).toEqual('providers');
  4781. * }
  4782. * }
  4783. *
  4784. * ```
  4785. */
  4786. let includeViewProviders = true;
  4787. function setIncludeViewProviders(v) {
  4788. const oldValue = includeViewProviders;
  4789. includeViewProviders = v;
  4790. return oldValue;
  4791. }
  4792. /**
  4793. * The number of slots in each bloom filter (used by DI). The larger this number, the fewer
  4794. * directives that will share slots, and thus, the fewer false positives when checking for
  4795. * the existence of a directive.
  4796. */
  4797. const BLOOM_SIZE = 256;
  4798. const BLOOM_MASK = BLOOM_SIZE - 1;
  4799. /**
  4800. * The number of bits that is represented by a single bloom bucket. JS bit operations are 32 bits,
  4801. * so each bucket represents 32 distinct tokens which accounts for log2(32) = 5 bits of a bloom hash
  4802. * number.
  4803. */
  4804. const BLOOM_BUCKET_BITS = 5;
  4805. /** Counter used to generate unique IDs for directives. */
  4806. let nextNgElementId = 0;
  4807. /** Value used when something wasn't found by an injector. */
  4808. const NOT_FOUND = {};
  4809. /**
  4810. * Registers this directive as present in its node's injector by flipping the directive's
  4811. * corresponding bit in the injector's bloom filter.
  4812. *
  4813. * @param injectorIndex The index of the node injector where this token should be registered
  4814. * @param tView The TView for the injector's bloom filters
  4815. * @param type The directive token to register
  4816. */
  4817. function bloomAdd(injectorIndex, tView, type) {
  4818. ngDevMode && assertEqual(tView.firstCreatePass, true, 'expected firstCreatePass to be true');
  4819. let id;
  4820. if (typeof type === 'string') {
  4821. id = type.charCodeAt(0) || 0;
  4822. }
  4823. else if (type.hasOwnProperty(NG_ELEMENT_ID)) {
  4824. id = type[NG_ELEMENT_ID];
  4825. }
  4826. // Set a unique ID on the directive type, so if something tries to inject the directive,
  4827. // we can easily retrieve the ID and hash it into the bloom bit that should be checked.
  4828. if (id == null) {
  4829. id = type[NG_ELEMENT_ID] = nextNgElementId++;
  4830. }
  4831. // We only have BLOOM_SIZE (256) slots in our bloom filter (8 buckets * 32 bits each),
  4832. // so all unique IDs must be modulo-ed into a number from 0 - 255 to fit into the filter.
  4833. const bloomHash = id & BLOOM_MASK;
  4834. // Create a mask that targets the specific bit associated with the directive.
  4835. // JS bit operations are 32 bits, so this will be a number between 2^0 and 2^31, corresponding
  4836. // to bit positions 0 - 31 in a 32 bit integer.
  4837. const mask = 1 << bloomHash;
  4838. // Each bloom bucket in `tData` represents `BLOOM_BUCKET_BITS` number of bits of `bloomHash`.
  4839. // Any bits in `bloomHash` beyond `BLOOM_BUCKET_BITS` indicate the bucket offset that the mask
  4840. // should be written to.
  4841. tView.data[injectorIndex + (bloomHash >> BLOOM_BUCKET_BITS)] |= mask;
  4842. }
  4843. /**
  4844. * Creates (or gets an existing) injector for a given element or container.
  4845. *
  4846. * @param tNode for which an injector should be retrieved / created.
  4847. * @param lView View where the node is stored
  4848. * @returns Node injector
  4849. */
  4850. function getOrCreateNodeInjectorForNode(tNode, lView) {
  4851. const existingInjectorIndex = getInjectorIndex(tNode, lView);
  4852. if (existingInjectorIndex !== -1) {
  4853. return existingInjectorIndex;
  4854. }
  4855. const tView = lView[TVIEW];
  4856. if (tView.firstCreatePass) {
  4857. tNode.injectorIndex = lView.length;
  4858. insertBloom(tView.data, tNode); // foundation for node bloom
  4859. insertBloom(lView, null); // foundation for cumulative bloom
  4860. insertBloom(tView.blueprint, null);
  4861. }
  4862. const parentLoc = getParentInjectorLocation(tNode, lView);
  4863. const injectorIndex = tNode.injectorIndex;
  4864. // If a parent injector can't be found, its location is set to -1.
  4865. // In that case, we don't need to set up a cumulative bloom
  4866. if (hasParentInjector(parentLoc)) {
  4867. const parentIndex = getParentInjectorIndex(parentLoc);
  4868. const parentLView = getParentInjectorView(parentLoc, lView);
  4869. const parentData = parentLView[TVIEW].data;
  4870. // Creates a cumulative bloom filter that merges the parent's bloom filter
  4871. // and its own cumulative bloom (which contains tokens for all ancestors)
  4872. for (let i = 0; i < 8 /* NodeInjectorOffset.BLOOM_SIZE */; i++) {
  4873. lView[injectorIndex + i] = parentLView[parentIndex + i] | parentData[parentIndex + i];
  4874. }
  4875. }
  4876. lView[injectorIndex + 8 /* NodeInjectorOffset.PARENT */] = parentLoc;
  4877. return injectorIndex;
  4878. }
  4879. function insertBloom(arr, footer) {
  4880. arr.push(0, 0, 0, 0, 0, 0, 0, 0, footer);
  4881. }
  4882. function getInjectorIndex(tNode, lView) {
  4883. if (tNode.injectorIndex === -1 ||
  4884. // If the injector index is the same as its parent's injector index, then the index has been
  4885. // copied down from the parent node. No injector has been created yet on this node.
  4886. (tNode.parent && tNode.parent.injectorIndex === tNode.injectorIndex) ||
  4887. // After the first template pass, the injector index might exist but the parent values
  4888. // might not have been calculated yet for this instance
  4889. lView[tNode.injectorIndex + 8 /* NodeInjectorOffset.PARENT */] === null) {
  4890. return -1;
  4891. }
  4892. else {
  4893. ngDevMode && assertIndexInRange(lView, tNode.injectorIndex);
  4894. return tNode.injectorIndex;
  4895. }
  4896. }
  4897. /**
  4898. * Finds the index of the parent injector, with a view offset if applicable. Used to set the
  4899. * parent injector initially.
  4900. *
  4901. * @returns Returns a number that is the combination of the number of LViews that we have to go up
  4902. * to find the LView containing the parent inject AND the index of the injector within that LView.
  4903. */
  4904. function getParentInjectorLocation(tNode, lView) {
  4905. if (tNode.parent && tNode.parent.injectorIndex !== -1) {
  4906. // If we have a parent `TNode` and there is an injector associated with it we are done, because
  4907. // the parent injector is within the current `LView`.
  4908. return tNode.parent.injectorIndex; // ViewOffset is 0
  4909. }
  4910. // When parent injector location is computed it may be outside of the current view. (ie it could
  4911. // be pointing to a declared parent location). This variable stores number of declaration parents
  4912. // we need to walk up in order to find the parent injector location.
  4913. let declarationViewOffset = 0;
  4914. let parentTNode = null;
  4915. let lViewCursor = lView;
  4916. // The parent injector is not in the current `LView`. We will have to walk the declared parent
  4917. // `LView` hierarchy and look for it. If we walk of the top, that means that there is no parent
  4918. // `NodeInjector`.
  4919. while (lViewCursor !== null) {
  4920. parentTNode = getTNodeFromLView(lViewCursor);
  4921. if (parentTNode === null) {
  4922. // If we have no parent, than we are done.
  4923. return NO_PARENT_INJECTOR;
  4924. }
  4925. ngDevMode && parentTNode && assertTNodeForLView(parentTNode, lViewCursor[DECLARATION_VIEW]);
  4926. // Every iteration of the loop requires that we go to the declared parent.
  4927. declarationViewOffset++;
  4928. lViewCursor = lViewCursor[DECLARATION_VIEW];
  4929. if (parentTNode.injectorIndex !== -1) {
  4930. // We found a NodeInjector which points to something.
  4931. return (parentTNode.injectorIndex |
  4932. (declarationViewOffset <<
  4933. 16 /* RelativeInjectorLocationFlags.ViewOffsetShift */));
  4934. }
  4935. }
  4936. return NO_PARENT_INJECTOR;
  4937. }
  4938. /**
  4939. * Makes a type or an injection token public to the DI system by adding it to an
  4940. * injector's bloom filter.
  4941. *
  4942. * @param di The node injector in which a directive will be added
  4943. * @param token The type or the injection token to be made public
  4944. */
  4945. function diPublicInInjector(injectorIndex, tView, token) {
  4946. bloomAdd(injectorIndex, tView, token);
  4947. }
  4948. /**
  4949. * Inject static attribute value into directive constructor.
  4950. *
  4951. * This method is used with `factory` functions which are generated as part of
  4952. * `defineDirective` or `defineComponent`. The method retrieves the static value
  4953. * of an attribute. (Dynamic attributes are not supported since they are not resolved
  4954. * at the time of injection and can change over time.)
  4955. *
  4956. * # Example
  4957. * Given:
  4958. * ```ts
  4959. * @Component(...)
  4960. * class MyComponent {
  4961. * constructor(@Attribute('title') title: string) { ... }
  4962. * }
  4963. * ```
  4964. * When instantiated with
  4965. * ```html
  4966. * <my-component title="Hello"></my-component>
  4967. * ```
  4968. *
  4969. * Then factory method generated is:
  4970. * ```ts
  4971. * MyComponent.ɵcmp = defineComponent({
  4972. * factory: () => new MyComponent(injectAttribute('title'))
  4973. * ...
  4974. * })
  4975. * ```
  4976. *
  4977. * @publicApi
  4978. */
  4979. function injectAttributeImpl(tNode, attrNameToInject) {
  4980. ngDevMode && assertTNodeType(tNode, 12 /* TNodeType.AnyContainer */ | 3 /* TNodeType.AnyRNode */);
  4981. ngDevMode && assertDefined(tNode, 'expecting tNode');
  4982. if (attrNameToInject === 'class') {
  4983. return tNode.classes;
  4984. }
  4985. if (attrNameToInject === 'style') {
  4986. return tNode.styles;
  4987. }
  4988. const attrs = tNode.attrs;
  4989. if (attrs) {
  4990. const attrsLength = attrs.length;
  4991. let i = 0;
  4992. while (i < attrsLength) {
  4993. const value = attrs[i];
  4994. // If we hit a `Bindings` or `Template` marker then we are done.
  4995. if (isNameOnlyAttributeMarker(value))
  4996. break;
  4997. // Skip namespaced attributes
  4998. if (value === 0 /* AttributeMarker.NamespaceURI */) {
  4999. // we skip the next two values
  5000. // as namespaced attributes looks like
  5001. // [..., AttributeMarker.NamespaceURI, 'http://someuri.com/test', 'test:exist',
  5002. // 'existValue', ...]
  5003. i = i + 2;
  5004. }
  5005. else if (typeof value === 'number') {
  5006. // Skip to the first value of the marked attribute.
  5007. i++;
  5008. while (i < attrsLength && typeof attrs[i] === 'string') {
  5009. i++;
  5010. }
  5011. }
  5012. else if (value === attrNameToInject) {
  5013. return attrs[i + 1];
  5014. }
  5015. else {
  5016. i = i + 2;
  5017. }
  5018. }
  5019. }
  5020. return null;
  5021. }
  5022. function notFoundValueOrThrow(notFoundValue, token, flags) {
  5023. if (flags & InjectFlags.Optional || notFoundValue !== undefined) {
  5024. return notFoundValue;
  5025. }
  5026. else {
  5027. throwProviderNotFoundError(token, 'NodeInjector');
  5028. }
  5029. }
  5030. /**
  5031. * Returns the value associated to the given token from the ModuleInjector or throws exception
  5032. *
  5033. * @param lView The `LView` that contains the `tNode`
  5034. * @param token The token to look for
  5035. * @param flags Injection flags
  5036. * @param notFoundValue The value to return when the injection flags is `InjectFlags.Optional`
  5037. * @returns the value from the injector or throws an exception
  5038. */
  5039. function lookupTokenUsingModuleInjector(lView, token, flags, notFoundValue) {
  5040. if (flags & InjectFlags.Optional && notFoundValue === undefined) {
  5041. // This must be set or the NullInjector will throw for optional deps
  5042. notFoundValue = null;
  5043. }
  5044. if ((flags & (InjectFlags.Self | InjectFlags.Host)) === 0) {
  5045. const moduleInjector = lView[INJECTOR];
  5046. // switch to `injectInjectorOnly` implementation for module injector, since module injector
  5047. // should not have access to Component/Directive DI scope (that may happen through
  5048. // `directiveInject` implementation)
  5049. const previousInjectImplementation = setInjectImplementation(undefined);
  5050. try {
  5051. if (moduleInjector) {
  5052. return moduleInjector.get(token, notFoundValue, flags & InjectFlags.Optional);
  5053. }
  5054. else {
  5055. return injectRootLimpMode(token, notFoundValue, flags & InjectFlags.Optional);
  5056. }
  5057. }
  5058. finally {
  5059. setInjectImplementation(previousInjectImplementation);
  5060. }
  5061. }
  5062. return notFoundValueOrThrow(notFoundValue, token, flags);
  5063. }
  5064. /**
  5065. * Returns the value associated to the given token from the NodeInjectors => ModuleInjector.
  5066. *
  5067. * Look for the injector providing the token by walking up the node injector tree and then
  5068. * the module injector tree.
  5069. *
  5070. * This function patches `token` with `__NG_ELEMENT_ID__` which contains the id for the bloom
  5071. * filter. `-1` is reserved for injecting `Injector` (implemented by `NodeInjector`)
  5072. *
  5073. * @param tNode The Node where the search for the injector should start
  5074. * @param lView The `LView` that contains the `tNode`
  5075. * @param token The token to look for
  5076. * @param flags Injection flags
  5077. * @param notFoundValue The value to return when the injection flags is `InjectFlags.Optional`
  5078. * @returns the value from the injector, `null` when not found, or `notFoundValue` if provided
  5079. */
  5080. function getOrCreateInjectable(tNode, lView, token, flags = InjectFlags.Default, notFoundValue) {
  5081. if (tNode !== null) {
  5082. // If the view or any of its ancestors have an embedded
  5083. // view injector, we have to look it up there first.
  5084. if (lView[FLAGS] & 2048 /* LViewFlags.HasEmbeddedViewInjector */ &&
  5085. // The token must be present on the current node injector when the `Self`
  5086. // flag is set, so the lookup on embedded view injector(s) can be skipped.
  5087. !(flags & InjectFlags.Self)) {
  5088. const embeddedInjectorValue = lookupTokenUsingEmbeddedInjector(tNode, lView, token, flags, NOT_FOUND);
  5089. if (embeddedInjectorValue !== NOT_FOUND) {
  5090. return embeddedInjectorValue;
  5091. }
  5092. }
  5093. // Otherwise try the node injector.
  5094. const value = lookupTokenUsingNodeInjector(tNode, lView, token, flags, NOT_FOUND);
  5095. if (value !== NOT_FOUND) {
  5096. return value;
  5097. }
  5098. }
  5099. // Finally, fall back to the module injector.
  5100. return lookupTokenUsingModuleInjector(lView, token, flags, notFoundValue);
  5101. }
  5102. /**
  5103. * Returns the value associated to the given token from the node injector.
  5104. *
  5105. * @param tNode The Node where the search for the injector should start
  5106. * @param lView The `LView` that contains the `tNode`
  5107. * @param token The token to look for
  5108. * @param flags Injection flags
  5109. * @param notFoundValue The value to return when the injection flags is `InjectFlags.Optional`
  5110. * @returns the value from the injector, `null` when not found, or `notFoundValue` if provided
  5111. */
  5112. function lookupTokenUsingNodeInjector(tNode, lView, token, flags, notFoundValue) {
  5113. const bloomHash = bloomHashBitOrFactory(token);
  5114. // If the ID stored here is a function, this is a special object like ElementRef or TemplateRef
  5115. // so just call the factory function to create it.
  5116. if (typeof bloomHash === 'function') {
  5117. if (!enterDI(lView, tNode, flags)) {
  5118. // Failed to enter DI, try module injector instead. If a token is injected with the @Host
  5119. // flag, the module injector is not searched for that token in Ivy.
  5120. return flags & InjectFlags.Host
  5121. ? notFoundValueOrThrow(notFoundValue, token, flags)
  5122. : lookupTokenUsingModuleInjector(lView, token, flags, notFoundValue);
  5123. }
  5124. try {
  5125. let value;
  5126. if (ngDevMode) {
  5127. runInInjectorProfilerContext(new NodeInjector(getCurrentTNode(), getLView()), token, () => {
  5128. value = bloomHash(flags);
  5129. if (value != null) {
  5130. emitInstanceCreatedByInjectorEvent(value);
  5131. }
  5132. });
  5133. }
  5134. else {
  5135. value = bloomHash(flags);
  5136. }
  5137. if (value == null && !(flags & InjectFlags.Optional)) {
  5138. throwProviderNotFoundError(token);
  5139. }
  5140. else {
  5141. return value;
  5142. }
  5143. }
  5144. finally {
  5145. leaveDI();
  5146. }
  5147. }
  5148. else if (typeof bloomHash === 'number') {
  5149. // A reference to the previous injector TView that was found while climbing the element
  5150. // injector tree. This is used to know if viewProviders can be accessed on the current
  5151. // injector.
  5152. let previousTView = null;
  5153. let injectorIndex = getInjectorIndex(tNode, lView);
  5154. let parentLocation = NO_PARENT_INJECTOR;
  5155. let hostTElementNode = flags & InjectFlags.Host ? lView[DECLARATION_COMPONENT_VIEW][T_HOST] : null;
  5156. // If we should skip this injector, or if there is no injector on this node, start by
  5157. // searching the parent injector.
  5158. if (injectorIndex === -1 || flags & InjectFlags.SkipSelf) {
  5159. parentLocation =
  5160. injectorIndex === -1
  5161. ? getParentInjectorLocation(tNode, lView)
  5162. : lView[injectorIndex + 8 /* NodeInjectorOffset.PARENT */];
  5163. if (parentLocation === NO_PARENT_INJECTOR || !shouldSearchParent(flags, false)) {
  5164. injectorIndex = -1;
  5165. }
  5166. else {
  5167. previousTView = lView[TVIEW];
  5168. injectorIndex = getParentInjectorIndex(parentLocation);
  5169. lView = getParentInjectorView(parentLocation, lView);
  5170. }
  5171. }
  5172. // Traverse up the injector tree until we find a potential match or until we know there
  5173. // *isn't* a match.
  5174. while (injectorIndex !== -1) {
  5175. ngDevMode && assertNodeInjector(lView, injectorIndex);
  5176. // Check the current injector. If it matches, see if it contains token.
  5177. const tView = lView[TVIEW];
  5178. ngDevMode &&
  5179. assertTNodeForLView(tView.data[injectorIndex + 8 /* NodeInjectorOffset.TNODE */], lView);
  5180. if (bloomHasToken(bloomHash, injectorIndex, tView.data)) {
  5181. // At this point, we have an injector which *may* contain the token, so we step through
  5182. // the providers and directives associated with the injector's corresponding node to get
  5183. // the instance.
  5184. const instance = searchTokensOnInjector(injectorIndex, lView, token, previousTView, flags, hostTElementNode);
  5185. if (instance !== NOT_FOUND) {
  5186. return instance;
  5187. }
  5188. }
  5189. parentLocation = lView[injectorIndex + 8 /* NodeInjectorOffset.PARENT */];
  5190. if (parentLocation !== NO_PARENT_INJECTOR &&
  5191. shouldSearchParent(flags, lView[TVIEW].data[injectorIndex + 8 /* NodeInjectorOffset.TNODE */] === hostTElementNode) &&
  5192. bloomHasToken(bloomHash, injectorIndex, lView)) {
  5193. // The def wasn't found anywhere on this node, so it was a false positive.
  5194. // Traverse up the tree and continue searching.
  5195. previousTView = tView;
  5196. injectorIndex = getParentInjectorIndex(parentLocation);
  5197. lView = getParentInjectorView(parentLocation, lView);
  5198. }
  5199. else {
  5200. // If we should not search parent OR If the ancestor bloom filter value does not have the
  5201. // bit corresponding to the directive we can give up on traversing up to find the specific
  5202. // injector.
  5203. injectorIndex = -1;
  5204. }
  5205. }
  5206. }
  5207. return notFoundValue;
  5208. }
  5209. function searchTokensOnInjector(injectorIndex, lView, token, previousTView, flags, hostTElementNode) {
  5210. const currentTView = lView[TVIEW];
  5211. const tNode = currentTView.data[injectorIndex + 8 /* NodeInjectorOffset.TNODE */];
  5212. // First, we need to determine if view providers can be accessed by the starting element.
  5213. // There are two possibilities
  5214. const canAccessViewProviders = previousTView == null
  5215. ? // 1) This is the first invocation `previousTView == null` which means that we are at the
  5216. // `TNode` of where injector is starting to look. In such a case the only time we are allowed
  5217. // to look into the ViewProviders is if:
  5218. // - we are on a component
  5219. // - AND the injector set `includeViewProviders` to true (implying that the token can see
  5220. // ViewProviders because it is the Component or a Service which itself was declared in
  5221. // ViewProviders)
  5222. isComponentHost(tNode) && includeViewProviders
  5223. : // 2) `previousTView != null` which means that we are now walking across the parent nodes.
  5224. // In such a case we are only allowed to look into the ViewProviders if:
  5225. // - We just crossed from child View to Parent View `previousTView != currentTView`
  5226. // - AND the parent TNode is an Element.
  5227. // This means that we just came from the Component's View and therefore are allowed to see
  5228. // into the ViewProviders.
  5229. previousTView != currentTView && (tNode.type & 3 /* TNodeType.AnyRNode */) !== 0;
  5230. // This special case happens when there is a @host on the inject and when we are searching
  5231. // on the host element node.
  5232. const isHostSpecialCase = flags & InjectFlags.Host && hostTElementNode === tNode;
  5233. const injectableIdx = locateDirectiveOrProvider(tNode, currentTView, token, canAccessViewProviders, isHostSpecialCase);
  5234. if (injectableIdx !== null) {
  5235. return getNodeInjectable(lView, currentTView, injectableIdx, tNode);
  5236. }
  5237. else {
  5238. return NOT_FOUND;
  5239. }
  5240. }
  5241. /**
  5242. * Searches for the given token among the node's directives and providers.
  5243. *
  5244. * @param tNode TNode on which directives are present.
  5245. * @param tView The tView we are currently processing
  5246. * @param token Provider token or type of a directive to look for.
  5247. * @param canAccessViewProviders Whether view providers should be considered.
  5248. * @param isHostSpecialCase Whether the host special case applies.
  5249. * @returns Index of a found directive or provider, or null when none found.
  5250. */
  5251. function locateDirectiveOrProvider(tNode, tView, token, canAccessViewProviders, isHostSpecialCase) {
  5252. const nodeProviderIndexes = tNode.providerIndexes;
  5253. const tInjectables = tView.data;
  5254. const injectablesStart = nodeProviderIndexes & 1048575 /* TNodeProviderIndexes.ProvidersStartIndexMask */;
  5255. const directivesStart = tNode.directiveStart;
  5256. const directiveEnd = tNode.directiveEnd;
  5257. const cptViewProvidersCount = nodeProviderIndexes >> 20 /* TNodeProviderIndexes.CptViewProvidersCountShift */;
  5258. const startingIndex = canAccessViewProviders
  5259. ? injectablesStart
  5260. : injectablesStart + cptViewProvidersCount;
  5261. // When the host special case applies, only the viewProviders and the component are visible
  5262. const endIndex = isHostSpecialCase ? injectablesStart + cptViewProvidersCount : directiveEnd;
  5263. for (let i = startingIndex; i < endIndex; i++) {
  5264. const providerTokenOrDef = tInjectables[i];
  5265. if ((i < directivesStart && token === providerTokenOrDef) ||
  5266. (i >= directivesStart && providerTokenOrDef.type === token)) {
  5267. return i;
  5268. }
  5269. }
  5270. if (isHostSpecialCase) {
  5271. const dirDef = tInjectables[directivesStart];
  5272. if (dirDef && isComponentDef(dirDef) && dirDef.type === token) {
  5273. return directivesStart;
  5274. }
  5275. }
  5276. return null;
  5277. }
  5278. /**
  5279. * Retrieve or instantiate the injectable from the `LView` at particular `index`.
  5280. *
  5281. * This function checks to see if the value has already been instantiated and if so returns the
  5282. * cached `injectable`. Otherwise if it detects that the value is still a factory it
  5283. * instantiates the `injectable` and caches the value.
  5284. */
  5285. function getNodeInjectable(lView, tView, index, tNode) {
  5286. let value = lView[index];
  5287. const tData = tView.data;
  5288. if (value instanceof NodeInjectorFactory) {
  5289. const factory = value;
  5290. if (factory.resolving) {
  5291. throwCyclicDependencyError(stringifyForError(tData[index]));
  5292. }
  5293. const previousIncludeViewProviders = setIncludeViewProviders(factory.canSeeViewProviders);
  5294. factory.resolving = true;
  5295. let prevInjectContext;
  5296. if (ngDevMode) {
  5297. // tData indexes mirror the concrete instances in its corresponding LView.
  5298. // lView[index] here is either the injectable instace itself or a factory,
  5299. // therefore tData[index] is the constructor of that injectable or a
  5300. // definition object that contains the constructor in a `.type` field.
  5301. const token = tData[index].type || tData[index];
  5302. const injector = new NodeInjector(tNode, lView);
  5303. prevInjectContext = setInjectorProfilerContext({ injector, token });
  5304. }
  5305. const previousInjectImplementation = factory.injectImpl
  5306. ? setInjectImplementation(factory.injectImpl)
  5307. : null;
  5308. const success = enterDI(lView, tNode, InjectFlags.Default);
  5309. ngDevMode &&
  5310. assertEqual(success, true, "Because flags do not contain `SkipSelf' we expect this to always succeed.");
  5311. try {
  5312. value = lView[index] = factory.factory(undefined, tData, lView, tNode);
  5313. ngDevMode && emitInstanceCreatedByInjectorEvent(value);
  5314. // This code path is hit for both directives and providers.
  5315. // For perf reasons, we want to avoid searching for hooks on providers.
  5316. // It does no harm to try (the hooks just won't exist), but the extra
  5317. // checks are unnecessary and this is a hot path. So we check to see
  5318. // if the index of the dependency is in the directive range for this
  5319. // tNode. If it's not, we know it's a provider and skip hook registration.
  5320. if (tView.firstCreatePass && index >= tNode.directiveStart) {
  5321. ngDevMode && assertDirectiveDef(tData[index]);
  5322. registerPreOrderHooks(index, tData[index], tView);
  5323. }
  5324. }
  5325. finally {
  5326. ngDevMode && setInjectorProfilerContext(prevInjectContext);
  5327. previousInjectImplementation !== null &&
  5328. setInjectImplementation(previousInjectImplementation);
  5329. setIncludeViewProviders(previousIncludeViewProviders);
  5330. factory.resolving = false;
  5331. leaveDI();
  5332. }
  5333. }
  5334. return value;
  5335. }
  5336. /**
  5337. * Returns the bit in an injector's bloom filter that should be used to determine whether or not
  5338. * the directive might be provided by the injector.
  5339. *
  5340. * When a directive is public, it is added to the bloom filter and given a unique ID that can be
  5341. * retrieved on the Type. When the directive isn't public or the token is not a directive `null`
  5342. * is returned as the node injector can not possibly provide that token.
  5343. *
  5344. * @param token the injection token
  5345. * @returns the matching bit to check in the bloom filter or `null` if the token is not known.
  5346. * When the returned value is negative then it represents special values such as `Injector`.
  5347. */
  5348. function bloomHashBitOrFactory(token) {
  5349. ngDevMode && assertDefined(token, 'token must be defined');
  5350. if (typeof token === 'string') {
  5351. return token.charCodeAt(0) || 0;
  5352. }
  5353. const tokenId =
  5354. // First check with `hasOwnProperty` so we don't get an inherited ID.
  5355. token.hasOwnProperty(NG_ELEMENT_ID) ? token[NG_ELEMENT_ID] : undefined;
  5356. // Negative token IDs are used for special objects such as `Injector`
  5357. if (typeof tokenId === 'number') {
  5358. if (tokenId >= 0) {
  5359. return tokenId & BLOOM_MASK;
  5360. }
  5361. else {
  5362. ngDevMode &&
  5363. assertEqual(tokenId, -1 /* InjectorMarkers.Injector */, 'Expecting to get Special Injector Id');
  5364. return createNodeInjector;
  5365. }
  5366. }
  5367. else {
  5368. return tokenId;
  5369. }
  5370. }
  5371. function bloomHasToken(bloomHash, injectorIndex, injectorView) {
  5372. // Create a mask that targets the specific bit associated with the directive we're looking for.
  5373. // JS bit operations are 32 bits, so this will be a number between 2^0 and 2^31, corresponding
  5374. // to bit positions 0 - 31 in a 32 bit integer.
  5375. const mask = 1 << bloomHash;
  5376. // Each bloom bucket in `injectorView` represents `BLOOM_BUCKET_BITS` number of bits of
  5377. // `bloomHash`. Any bits in `bloomHash` beyond `BLOOM_BUCKET_BITS` indicate the bucket offset
  5378. // that should be used.
  5379. const value = injectorView[injectorIndex + (bloomHash >> BLOOM_BUCKET_BITS)];
  5380. // If the bloom filter value has the bit corresponding to the directive's bloomBit flipped on,
  5381. // this injector is a potential match.
  5382. return !!(value & mask);
  5383. }
  5384. /** Returns true if flags prevent parent injector from being searched for tokens */
  5385. function shouldSearchParent(flags, isFirstHostTNode) {
  5386. return !(flags & InjectFlags.Self) && !(flags & InjectFlags.Host && isFirstHostTNode);
  5387. }
  5388. function getNodeInjectorLView(nodeInjector) {
  5389. return nodeInjector._lView;
  5390. }
  5391. function getNodeInjectorTNode(nodeInjector) {
  5392. return nodeInjector._tNode;
  5393. }
  5394. class NodeInjector {
  5395. _tNode;
  5396. _lView;
  5397. constructor(_tNode, _lView) {
  5398. this._tNode = _tNode;
  5399. this._lView = _lView;
  5400. }
  5401. get(token, notFoundValue, flags) {
  5402. return getOrCreateInjectable(this._tNode, this._lView, token, convertToBitFlags(flags), notFoundValue);
  5403. }
  5404. }
  5405. /** Creates a `NodeInjector` for the current node. */
  5406. function createNodeInjector() {
  5407. return new NodeInjector(getCurrentTNode(), getLView());
  5408. }
  5409. /**
  5410. * @codeGenApi
  5411. */
  5412. function ɵɵgetInheritedFactory(type) {
  5413. return noSideEffects(() => {
  5414. const ownConstructor = type.prototype.constructor;
  5415. const ownFactory = ownConstructor[NG_FACTORY_DEF] || getFactoryOf(ownConstructor);
  5416. const objectPrototype = Object.prototype;
  5417. let parent = Object.getPrototypeOf(type.prototype).constructor;
  5418. // Go up the prototype until we hit `Object`.
  5419. while (parent && parent !== objectPrototype) {
  5420. const factory = parent[NG_FACTORY_DEF] || getFactoryOf(parent);
  5421. // If we hit something that has a factory and the factory isn't the same as the type,
  5422. // we've found the inherited factory. Note the check that the factory isn't the type's
  5423. // own factory is redundant in most cases, but if the user has custom decorators on the
  5424. // class, this lookup will start one level down in the prototype chain, causing us to
  5425. // find the own factory first and potentially triggering an infinite loop downstream.
  5426. if (factory && factory !== ownFactory) {
  5427. return factory;
  5428. }
  5429. parent = Object.getPrototypeOf(parent);
  5430. }
  5431. // There is no factory defined. Either this was improper usage of inheritance
  5432. // (no Angular decorator on the superclass) or there is no constructor at all
  5433. // in the inheritance chain. Since the two cases cannot be distinguished, the
  5434. // latter has to be assumed.
  5435. return (t) => new t();
  5436. });
  5437. }
  5438. function getFactoryOf(type) {
  5439. if (isForwardRef(type)) {
  5440. return () => {
  5441. const factory = getFactoryOf(resolveForwardRef(type));
  5442. return factory && factory();
  5443. };
  5444. }
  5445. return getFactoryDef(type);
  5446. }
  5447. /**
  5448. * Returns a value from the closest embedded or node injector.
  5449. *
  5450. * @param tNode The Node where the search for the injector should start
  5451. * @param lView The `LView` that contains the `tNode`
  5452. * @param token The token to look for
  5453. * @param flags Injection flags
  5454. * @param notFoundValue The value to return when the injection flags is `InjectFlags.Optional`
  5455. * @returns the value from the injector, `null` when not found, or `notFoundValue` if provided
  5456. */
  5457. function lookupTokenUsingEmbeddedInjector(tNode, lView, token, flags, notFoundValue) {
  5458. let currentTNode = tNode;
  5459. let currentLView = lView;
  5460. // When an LView with an embedded view injector is inserted, it'll likely be interlaced with
  5461. // nodes who may have injectors (e.g. node injector -> embedded view injector -> node injector).
  5462. // Since the bloom filters for the node injectors have already been constructed and we don't
  5463. // have a way of extracting the records from an injector, the only way to maintain the correct
  5464. // hierarchy when resolving the value is to walk it node-by-node while attempting to resolve
  5465. // the token at each level.
  5466. while (currentTNode !== null &&
  5467. currentLView !== null &&
  5468. currentLView[FLAGS] & 2048 /* LViewFlags.HasEmbeddedViewInjector */ &&
  5469. !isRootView(currentLView)) {
  5470. ngDevMode && assertTNodeForLView(currentTNode, currentLView);
  5471. // Note that this lookup on the node injector is using the `Self` flag, because
  5472. // we don't want the node injector to look at any parent injectors since we
  5473. // may hit the embedded view injector first.
  5474. const nodeInjectorValue = lookupTokenUsingNodeInjector(currentTNode, currentLView, token, flags | InjectFlags.Self, NOT_FOUND);
  5475. if (nodeInjectorValue !== NOT_FOUND) {
  5476. return nodeInjectorValue;
  5477. }
  5478. // Has an explicit type due to a TS bug: https://github.com/microsoft/TypeScript/issues/33191
  5479. let parentTNode = currentTNode.parent;
  5480. // `TNode.parent` includes the parent within the current view only. If it doesn't exist,
  5481. // it means that we've hit the view boundary and we need to go up to the next view.
  5482. if (!parentTNode) {
  5483. // Before we go to the next LView, check if the token exists on the current embedded injector.
  5484. const embeddedViewInjector = currentLView[EMBEDDED_VIEW_INJECTOR];
  5485. if (embeddedViewInjector) {
  5486. const embeddedViewInjectorValue = embeddedViewInjector.get(token, NOT_FOUND, flags);
  5487. if (embeddedViewInjectorValue !== NOT_FOUND) {
  5488. return embeddedViewInjectorValue;
  5489. }
  5490. }
  5491. // Otherwise keep going up the tree.
  5492. parentTNode = getTNodeFromLView(currentLView);
  5493. currentLView = currentLView[DECLARATION_VIEW];
  5494. }
  5495. currentTNode = parentTNode;
  5496. }
  5497. return notFoundValue;
  5498. }
  5499. /** Gets the TNode associated with an LView inside of the declaration view. */
  5500. function getTNodeFromLView(lView) {
  5501. const tView = lView[TVIEW];
  5502. const tViewType = tView.type;
  5503. // The parent pointer differs based on `TView.type`.
  5504. if (tViewType === 2 /* TViewType.Embedded */) {
  5505. ngDevMode && assertDefined(tView.declTNode, 'Embedded TNodes should have declaration parents.');
  5506. return tView.declTNode;
  5507. }
  5508. else if (tViewType === 1 /* TViewType.Component */) {
  5509. // Components don't have `TView.declTNode` because each instance of component could be
  5510. // inserted in different location, hence `TView.declTNode` is meaningless.
  5511. return lView[T_HOST];
  5512. }
  5513. return null;
  5514. }
  5515. /**
  5516. * Facade for the attribute injection from DI.
  5517. *
  5518. * @codeGenApi
  5519. */
  5520. function ɵɵinjectAttribute(attrNameToInject) {
  5521. return injectAttributeImpl(getCurrentTNode(), attrNameToInject);
  5522. }
  5523. /**
  5524. * Attribute decorator and metadata.
  5525. *
  5526. * @Annotation
  5527. * @publicApi
  5528. */
  5529. const Attribute = makeParamDecorator('Attribute', (attributeName) => ({
  5530. attributeName,
  5531. __NG_ELEMENT_ID__: () => ɵɵinjectAttribute(attributeName),
  5532. }));
  5533. let _reflect = null;
  5534. function getReflect() {
  5535. return (_reflect = _reflect || new ReflectionCapabilities());
  5536. }
  5537. function reflectDependencies(type) {
  5538. return convertDependencies(getReflect().parameters(type));
  5539. }
  5540. function convertDependencies(deps) {
  5541. return deps.map((dep) => reflectDependency(dep));
  5542. }
  5543. function reflectDependency(dep) {
  5544. const meta = {
  5545. token: null,
  5546. attribute: null,
  5547. host: false,
  5548. optional: false,
  5549. self: false,
  5550. skipSelf: false,
  5551. };
  5552. if (Array.isArray(dep) && dep.length > 0) {
  5553. for (let j = 0; j < dep.length; j++) {
  5554. const param = dep[j];
  5555. if (param === undefined) {
  5556. // param may be undefined if type of dep is not set by ngtsc
  5557. continue;
  5558. }
  5559. const proto = Object.getPrototypeOf(param);
  5560. if (param instanceof Optional || proto.ngMetadataName === 'Optional') {
  5561. meta.optional = true;
  5562. }
  5563. else if (param instanceof SkipSelf || proto.ngMetadataName === 'SkipSelf') {
  5564. meta.skipSelf = true;
  5565. }
  5566. else if (param instanceof Self || proto.ngMetadataName === 'Self') {
  5567. meta.self = true;
  5568. }
  5569. else if (param instanceof Host || proto.ngMetadataName === 'Host') {
  5570. meta.host = true;
  5571. }
  5572. else if (param instanceof Inject) {
  5573. meta.token = param.token;
  5574. }
  5575. else if (param instanceof Attribute) {
  5576. if (param.attributeName === undefined) {
  5577. throw new RuntimeError(204 /* RuntimeErrorCode.INVALID_INJECTION_TOKEN */, ngDevMode && `Attribute name must be defined.`);
  5578. }
  5579. meta.attribute = param.attributeName;
  5580. }
  5581. else {
  5582. meta.token = param;
  5583. }
  5584. }
  5585. }
  5586. else if (dep === undefined || (Array.isArray(dep) && dep.length === 0)) {
  5587. meta.token = null;
  5588. }
  5589. else {
  5590. meta.token = dep;
  5591. }
  5592. return meta;
  5593. }
  5594. /**
  5595. * Compile an Angular injectable according to its `Injectable` metadata, and patch the resulting
  5596. * injectable def (`ɵprov`) onto the injectable type.
  5597. */
  5598. function compileInjectable(type, meta) {
  5599. let ngInjectableDef = null;
  5600. let ngFactoryDef = null;
  5601. // if NG_PROV_DEF is already defined on this class then don't overwrite it
  5602. if (!type.hasOwnProperty(NG_PROV_DEF)) {
  5603. Object.defineProperty(type, NG_PROV_DEF, {
  5604. get: () => {
  5605. if (ngInjectableDef === null) {
  5606. const compiler = getCompilerFacade({
  5607. usage: 0 /* JitCompilerUsage.Decorator */,
  5608. kind: 'injectable',
  5609. type,
  5610. });
  5611. ngInjectableDef = compiler.compileInjectable(angularCoreDiEnv, `ng:///${type.name}/ɵprov.js`, getInjectableMetadata(type, meta));
  5612. }
  5613. return ngInjectableDef;
  5614. },
  5615. });
  5616. }
  5617. // if NG_FACTORY_DEF is already defined on this class then don't overwrite it
  5618. if (!type.hasOwnProperty(NG_FACTORY_DEF)) {
  5619. Object.defineProperty(type, NG_FACTORY_DEF, {
  5620. get: () => {
  5621. if (ngFactoryDef === null) {
  5622. const compiler = getCompilerFacade({
  5623. usage: 0 /* JitCompilerUsage.Decorator */,
  5624. kind: 'injectable',
  5625. type,
  5626. });
  5627. ngFactoryDef = compiler.compileFactory(angularCoreDiEnv, `ng:///${type.name}/ɵfac.js`, {
  5628. name: type.name,
  5629. type,
  5630. typeArgumentCount: 0, // In JIT mode types are not available nor used.
  5631. deps: reflectDependencies(type),
  5632. target: compiler.FactoryTarget.Injectable,
  5633. });
  5634. }
  5635. return ngFactoryDef;
  5636. },
  5637. // Leave this configurable so that the factories from directives or pipes can take precedence.
  5638. configurable: true,
  5639. });
  5640. }
  5641. }
  5642. const USE_VALUE = getClosureSafeProperty({
  5643. provide: String,
  5644. useValue: getClosureSafeProperty,
  5645. });
  5646. function isUseClassProvider(meta) {
  5647. return meta.useClass !== undefined;
  5648. }
  5649. function isUseValueProvider(meta) {
  5650. return USE_VALUE in meta;
  5651. }
  5652. function isUseFactoryProvider(meta) {
  5653. return meta.useFactory !== undefined;
  5654. }
  5655. function isUseExistingProvider(meta) {
  5656. return meta.useExisting !== undefined;
  5657. }
  5658. function getInjectableMetadata(type, srcMeta) {
  5659. // Allow the compilation of a class with a `@Injectable()` decorator without parameters
  5660. const meta = srcMeta || { providedIn: null };
  5661. const compilerMeta = {
  5662. name: type.name,
  5663. type: type,
  5664. typeArgumentCount: 0,
  5665. providedIn: meta.providedIn,
  5666. };
  5667. if ((isUseClassProvider(meta) || isUseFactoryProvider(meta)) && meta.deps !== undefined) {
  5668. compilerMeta.deps = convertDependencies(meta.deps);
  5669. }
  5670. // Check to see if the user explicitly provided a `useXxxx` property.
  5671. if (isUseClassProvider(meta)) {
  5672. compilerMeta.useClass = meta.useClass;
  5673. }
  5674. else if (isUseValueProvider(meta)) {
  5675. compilerMeta.useValue = meta.useValue;
  5676. }
  5677. else if (isUseFactoryProvider(meta)) {
  5678. compilerMeta.useFactory = meta.useFactory;
  5679. }
  5680. else if (isUseExistingProvider(meta)) {
  5681. compilerMeta.useExisting = meta.useExisting;
  5682. }
  5683. return compilerMeta;
  5684. }
  5685. /**
  5686. * Injectable decorator and metadata.
  5687. *
  5688. * @Annotation
  5689. * @publicApi
  5690. */
  5691. const Injectable = makeDecorator('Injectable', undefined, undefined, undefined, (type, meta) => compileInjectable(type, meta));
  5692. /**
  5693. * Create a new `Injector` which is configured using a `defType` of `InjectorType<any>`s.
  5694. */
  5695. function createInjector(defType, parent = null, additionalProviders = null, name) {
  5696. const injector = createInjectorWithoutInjectorInstances(defType, parent, additionalProviders, name);
  5697. injector.resolveInjectorInitializers();
  5698. return injector;
  5699. }
  5700. /**
  5701. * Creates a new injector without eagerly resolving its injector types. Can be used in places
  5702. * where resolving the injector types immediately can lead to an infinite loop. The injector types
  5703. * should be resolved at a later point by calling `_resolveInjectorDefTypes`.
  5704. */
  5705. function createInjectorWithoutInjectorInstances(defType, parent = null, additionalProviders = null, name, scopes = new Set()) {
  5706. const providers = [additionalProviders || EMPTY_ARRAY, importProvidersFrom(defType)];
  5707. name = name || (typeof defType === 'object' ? undefined : stringify(defType));
  5708. return new R3Injector(providers, parent || getNullInjector(), name || null, scopes);
  5709. }
  5710. /**
  5711. * Concrete injectors implement this interface. Injectors are configured
  5712. * with [providers](guide/di/dependency-injection-providers) that associate
  5713. * dependencies of various types with [injection tokens](guide/di/dependency-injection-providers).
  5714. *
  5715. * @see [DI Providers](guide/di/dependency-injection-providers).
  5716. * @see {@link StaticProvider}
  5717. *
  5718. * @usageNotes
  5719. *
  5720. * The following example creates a service injector instance.
  5721. *
  5722. * {@example core/di/ts/provider_spec.ts region='ConstructorProvider'}
  5723. *
  5724. * ### Usage example
  5725. *
  5726. * {@example core/di/ts/injector_spec.ts region='Injector'}
  5727. *
  5728. * `Injector` returns itself when given `Injector` as a token:
  5729. *
  5730. * {@example core/di/ts/injector_spec.ts region='injectInjector'}
  5731. *
  5732. * @publicApi
  5733. */
  5734. class Injector {
  5735. static THROW_IF_NOT_FOUND = THROW_IF_NOT_FOUND;
  5736. static NULL = new NullInjector();
  5737. static create(options, parent) {
  5738. if (Array.isArray(options)) {
  5739. return createInjector({ name: '' }, parent, options, '');
  5740. }
  5741. else {
  5742. const name = options.name ?? '';
  5743. return createInjector({ name }, options.parent, options.providers, name);
  5744. }
  5745. }
  5746. /** @nocollapse */
  5747. static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
  5748. token: Injector,
  5749. providedIn: 'any',
  5750. factory: () => ɵɵinject(INJECTOR$1),
  5751. });
  5752. /**
  5753. * @internal
  5754. * @nocollapse
  5755. */
  5756. static __NG_ELEMENT_ID__ = -1 /* InjectorMarkers.Injector */;
  5757. }
  5758. /*!
  5759. * @license
  5760. * Copyright Google LLC All Rights Reserved.
  5761. *
  5762. * Use of this source code is governed by an MIT-style license that can be
  5763. * found in the LICENSE file at https://angular.dev/license
  5764. */
  5765. /**
  5766. * Creates a token that can be used to inject static attributes of the host node.
  5767. *
  5768. * @usageNotes
  5769. * ### Injecting an attribute that is known to exist
  5770. * ```ts
  5771. * @Directive()
  5772. * class MyDir {
  5773. * attr: string = inject(new HostAttributeToken('some-attr'));
  5774. * }
  5775. * ```
  5776. *
  5777. * ### Optionally injecting an attribute
  5778. * ```ts
  5779. * @Directive()
  5780. * class MyDir {
  5781. * attr: string | null = inject(new HostAttributeToken('some-attr'), {optional: true});
  5782. * }
  5783. * ```
  5784. * @publicApi
  5785. */
  5786. class HostAttributeToken {
  5787. attributeName;
  5788. constructor(attributeName) {
  5789. this.attributeName = attributeName;
  5790. }
  5791. /** @internal */
  5792. __NG_ELEMENT_ID__ = () => ɵɵinjectAttribute(this.attributeName);
  5793. toString() {
  5794. return `HostAttributeToken ${this.attributeName}`;
  5795. }
  5796. }
  5797. /**
  5798. * A token that can be used to inject the tag name of the host node.
  5799. *
  5800. * @usageNotes
  5801. * ### Injecting a tag name that is known to exist
  5802. * ```ts
  5803. * @Directive()
  5804. * class MyDir {
  5805. * tagName: string = inject(HOST_TAG_NAME);
  5806. * }
  5807. * ```
  5808. *
  5809. * ### Optionally injecting a tag name
  5810. * ```ts
  5811. * @Directive()
  5812. * class MyDir {
  5813. * tagName: string | null = inject(HOST_TAG_NAME, {optional: true});
  5814. * }
  5815. * ```
  5816. * @publicApi
  5817. */
  5818. const HOST_TAG_NAME = new InjectionToken(ngDevMode ? 'HOST_TAG_NAME' : '');
  5819. // HOST_TAG_NAME should be resolved at the current node, similar to e.g. ElementRef,
  5820. // so we manually specify __NG_ELEMENT_ID__ here, instead of using a factory.
  5821. // tslint:disable-next-line:no-toplevel-property-access
  5822. HOST_TAG_NAME.__NG_ELEMENT_ID__ = (flags) => {
  5823. const tNode = getCurrentTNode();
  5824. if (tNode === null) {
  5825. throw new RuntimeError(204 /* RuntimeErrorCode.INVALID_INJECTION_TOKEN */, ngDevMode &&
  5826. 'HOST_TAG_NAME can only be injected in directives and components ' +
  5827. 'during construction time (in a class constructor or as a class field initializer)');
  5828. }
  5829. if (tNode.type & 2 /* TNodeType.Element */) {
  5830. return tNode.value;
  5831. }
  5832. if (flags & InjectFlags.Optional) {
  5833. return null;
  5834. }
  5835. throw new RuntimeError(204 /* RuntimeErrorCode.INVALID_INJECTION_TOKEN */, ngDevMode &&
  5836. `HOST_TAG_NAME was used on ${getDevModeNodeName(tNode)} which doesn't have an underlying element in the DOM. ` +
  5837. `This is invalid, and so the dependency should be marked as optional.`);
  5838. };
  5839. function getDevModeNodeName(tNode) {
  5840. if (tNode.type & 8 /* TNodeType.ElementContainer */) {
  5841. return 'an <ng-container>';
  5842. }
  5843. else if (tNode.type & 4 /* TNodeType.Container */) {
  5844. return 'an <ng-template>';
  5845. }
  5846. else if (tNode.type & 128 /* TNodeType.LetDeclaration */) {
  5847. return 'an @let declaration';
  5848. }
  5849. else {
  5850. return 'a node';
  5851. }
  5852. }
  5853. const SCHEDULE_IN_ROOT_ZONE_DEFAULT = false;
  5854. /**
  5855. * `DestroyRef` lets you set callbacks to run for any cleanup or destruction behavior.
  5856. * The scope of this destruction depends on where `DestroyRef` is injected. If `DestroyRef`
  5857. * is injected in a component or directive, the callbacks run when that component or
  5858. * directive is destroyed. Otherwise the callbacks run when a corresponding injector is destroyed.
  5859. *
  5860. * @publicApi
  5861. */
  5862. class DestroyRef {
  5863. /**
  5864. * @internal
  5865. * @nocollapse
  5866. */
  5867. static __NG_ELEMENT_ID__ = injectDestroyRef;
  5868. /**
  5869. * @internal
  5870. * @nocollapse
  5871. */
  5872. static __NG_ENV_ID__ = (injector) => injector;
  5873. }
  5874. class NodeInjectorDestroyRef extends DestroyRef {
  5875. _lView;
  5876. constructor(_lView) {
  5877. super();
  5878. this._lView = _lView;
  5879. }
  5880. onDestroy(callback) {
  5881. storeLViewOnDestroy(this._lView, callback);
  5882. return () => removeLViewOnDestroy(this._lView, callback);
  5883. }
  5884. }
  5885. function injectDestroyRef() {
  5886. return new NodeInjectorDestroyRef(getLView());
  5887. }
  5888. /**
  5889. * Injectable that is notified when an `LView` is made aware of changes to application state.
  5890. */
  5891. class ChangeDetectionScheduler {
  5892. }
  5893. /** Token used to indicate if zoneless was enabled via provideZonelessChangeDetection(). */
  5894. const ZONELESS_ENABLED = new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'Zoneless enabled' : '', { providedIn: 'root', factory: () => false });
  5895. /** Token used to indicate `provideExperimentalZonelessChangeDetection` was used. */
  5896. const PROVIDED_ZONELESS = new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'Zoneless provided' : '', { providedIn: 'root', factory: () => false });
  5897. const ZONELESS_SCHEDULER_DISABLED = new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'scheduler disabled' : '');
  5898. // TODO(atscott): Remove in v19. Scheduler should be done with runOutsideAngular.
  5899. const SCHEDULE_IN_ROOT_ZONE = new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'run changes outside zone in root' : '');
  5900. /**
  5901. * Internal implementation of the pending tasks service.
  5902. */
  5903. class PendingTasksInternal {
  5904. taskId = 0;
  5905. pendingTasks = new Set();
  5906. get _hasPendingTasks() {
  5907. return this.hasPendingTasks.value;
  5908. }
  5909. hasPendingTasks = new BehaviorSubject(false);
  5910. add() {
  5911. if (!this._hasPendingTasks) {
  5912. this.hasPendingTasks.next(true);
  5913. }
  5914. const taskId = this.taskId++;
  5915. this.pendingTasks.add(taskId);
  5916. return taskId;
  5917. }
  5918. has(taskId) {
  5919. return this.pendingTasks.has(taskId);
  5920. }
  5921. remove(taskId) {
  5922. this.pendingTasks.delete(taskId);
  5923. if (this.pendingTasks.size === 0 && this._hasPendingTasks) {
  5924. this.hasPendingTasks.next(false);
  5925. }
  5926. }
  5927. ngOnDestroy() {
  5928. this.pendingTasks.clear();
  5929. if (this._hasPendingTasks) {
  5930. this.hasPendingTasks.next(false);
  5931. }
  5932. }
  5933. /** @nocollapse */
  5934. static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
  5935. token: PendingTasksInternal,
  5936. providedIn: 'root',
  5937. factory: () => new PendingTasksInternal(),
  5938. });
  5939. }
  5940. /**
  5941. * Service that keeps track of pending tasks contributing to the stableness of Angular
  5942. * application. While several existing Angular services (ex.: `HttpClient`) will internally manage
  5943. * tasks influencing stability, this API gives control over stability to library and application
  5944. * developers for specific cases not covered by Angular internals.
  5945. *
  5946. * The concept of stability comes into play in several important scenarios:
  5947. * - SSR process needs to wait for the application stability before serializing and sending rendered
  5948. * HTML;
  5949. * - tests might want to delay assertions until the application becomes stable;
  5950. *
  5951. * @usageNotes
  5952. * ```ts
  5953. * const pendingTasks = inject(PendingTasks);
  5954. * const taskCleanup = pendingTasks.add();
  5955. * // do work that should block application's stability and then:
  5956. * taskCleanup();
  5957. * ```
  5958. *
  5959. * @publicApi
  5960. * @developerPreview
  5961. */
  5962. class PendingTasks {
  5963. internalPendingTasks = inject(PendingTasksInternal);
  5964. scheduler = inject(ChangeDetectionScheduler);
  5965. /**
  5966. * Adds a new task that should block application's stability.
  5967. * @returns A cleanup function that removes a task when called.
  5968. */
  5969. add() {
  5970. const taskId = this.internalPendingTasks.add();
  5971. return () => {
  5972. if (!this.internalPendingTasks.has(taskId)) {
  5973. // This pending task has already been cleared.
  5974. return;
  5975. }
  5976. // Notifying the scheduler will hold application stability open until the next tick.
  5977. this.scheduler.notify(11 /* NotificationSource.PendingTaskRemoved */);
  5978. this.internalPendingTasks.remove(taskId);
  5979. };
  5980. }
  5981. /**
  5982. * Runs an asynchronous function and blocks the application's stability until the function completes.
  5983. *
  5984. * ```ts
  5985. * pendingTasks.run(async () => {
  5986. * const userData = await fetch('/api/user');
  5987. * this.userData.set(userData);
  5988. * });
  5989. * ```
  5990. *
  5991. * Application stability is at least delayed until the next tick after the `run` method resolves
  5992. * so it is safe to make additional updates to application state that would require UI synchronization:
  5993. *
  5994. * ```ts
  5995. * const userData = await pendingTasks.run(() => fetch('/api/user'));
  5996. * this.userData.set(userData);
  5997. * ```
  5998. *
  5999. * @param fn The asynchronous function to execute
  6000. */
  6001. async run(fn) {
  6002. const removeTask = this.add();
  6003. try {
  6004. return await fn();
  6005. }
  6006. finally {
  6007. removeTask();
  6008. }
  6009. }
  6010. /** @nocollapse */
  6011. static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
  6012. token: PendingTasks,
  6013. providedIn: 'root',
  6014. factory: () => new PendingTasks(),
  6015. });
  6016. }
  6017. class EventEmitter_ extends Subject {
  6018. // tslint:disable-next-line:require-internal-with-underscore
  6019. __isAsync;
  6020. destroyRef = undefined;
  6021. pendingTasks = undefined;
  6022. constructor(isAsync = false) {
  6023. super();
  6024. this.__isAsync = isAsync;
  6025. // Attempt to retrieve a `DestroyRef` and `PendingTasks` optionally.
  6026. // For backwards compatibility reasons, this cannot be required.
  6027. if (isInInjectionContext()) {
  6028. // `DestroyRef` is optional because it is not available in all contexts.
  6029. // But it is useful to properly complete the `EventEmitter` if used with `outputToObservable`
  6030. // when the component/directive is destroyed. (See `outputToObservable` for more details.)
  6031. this.destroyRef = inject(DestroyRef, { optional: true }) ?? undefined;
  6032. this.pendingTasks = inject(PendingTasksInternal, { optional: true }) ?? undefined;
  6033. }
  6034. }
  6035. emit(value) {
  6036. const prevConsumer = setActiveConsumer$1(null);
  6037. try {
  6038. super.next(value);
  6039. }
  6040. finally {
  6041. setActiveConsumer$1(prevConsumer);
  6042. }
  6043. }
  6044. subscribe(observerOrNext, error, complete) {
  6045. let nextFn = observerOrNext;
  6046. let errorFn = error || (() => null);
  6047. let completeFn = complete;
  6048. if (observerOrNext && typeof observerOrNext === 'object') {
  6049. const observer = observerOrNext;
  6050. nextFn = observer.next?.bind(observer);
  6051. errorFn = observer.error?.bind(observer);
  6052. completeFn = observer.complete?.bind(observer);
  6053. }
  6054. if (this.__isAsync) {
  6055. errorFn = this.wrapInTimeout(errorFn);
  6056. if (nextFn) {
  6057. nextFn = this.wrapInTimeout(nextFn);
  6058. }
  6059. if (completeFn) {
  6060. completeFn = this.wrapInTimeout(completeFn);
  6061. }
  6062. }
  6063. const sink = super.subscribe({ next: nextFn, error: errorFn, complete: completeFn });
  6064. if (observerOrNext instanceof Subscription) {
  6065. observerOrNext.add(sink);
  6066. }
  6067. return sink;
  6068. }
  6069. wrapInTimeout(fn) {
  6070. return (value) => {
  6071. const taskId = this.pendingTasks?.add();
  6072. setTimeout(() => {
  6073. fn(value);
  6074. if (taskId !== undefined) {
  6075. this.pendingTasks?.remove(taskId);
  6076. }
  6077. });
  6078. };
  6079. }
  6080. }
  6081. /**
  6082. * @publicApi
  6083. */
  6084. const EventEmitter = EventEmitter_;
  6085. function noop(...args) {
  6086. // Do nothing.
  6087. }
  6088. /**
  6089. * Gets a scheduling function that runs the callback after the first of setTimeout and
  6090. * requestAnimationFrame resolves.
  6091. *
  6092. * - `requestAnimationFrame` ensures that change detection runs ahead of a browser repaint.
  6093. * This ensures that the create and update passes of a change detection always happen
  6094. * in the same frame.
  6095. * - When the browser is resource-starved, `rAF` can execute _before_ a `setTimeout` because
  6096. * rendering is a very high priority process. This means that `setTimeout` cannot guarantee
  6097. * same-frame create and update pass, when `setTimeout` is used to schedule the update phase.
  6098. * - While `rAF` gives us the desirable same-frame updates, it has two limitations that
  6099. * prevent it from being used alone. First, it does not run in background tabs, which would
  6100. * prevent Angular from initializing an application when opened in a new tab (for example).
  6101. * Second, repeated calls to requestAnimationFrame will execute at the refresh rate of the
  6102. * hardware (~16ms for a 60Hz display). This would cause significant slowdown of tests that
  6103. * are written with several updates and asserts in the form of "update; await stable; assert;".
  6104. * - Both `setTimeout` and `rAF` are able to "coalesce" several events from a single user
  6105. * interaction into a single change detection. Importantly, this reduces view tree traversals when
  6106. * compared to an alternative timing mechanism like `queueMicrotask`, where change detection would
  6107. * then be interleaves between each event.
  6108. *
  6109. * By running change detection after the first of `setTimeout` and `rAF` to execute, we get the
  6110. * best of both worlds.
  6111. *
  6112. * @returns a function to cancel the scheduled callback
  6113. */
  6114. function scheduleCallbackWithRafRace(callback) {
  6115. let timeoutId;
  6116. let animationFrameId;
  6117. function cleanup() {
  6118. callback = noop;
  6119. try {
  6120. if (animationFrameId !== undefined && typeof cancelAnimationFrame === 'function') {
  6121. cancelAnimationFrame(animationFrameId);
  6122. }
  6123. if (timeoutId !== undefined) {
  6124. clearTimeout(timeoutId);
  6125. }
  6126. }
  6127. catch {
  6128. // Clearing/canceling can fail in tests due to the timing of functions being patched and unpatched
  6129. // Just ignore the errors - we protect ourselves from this issue by also making the callback a no-op.
  6130. }
  6131. }
  6132. timeoutId = setTimeout(() => {
  6133. callback();
  6134. cleanup();
  6135. });
  6136. if (typeof requestAnimationFrame === 'function') {
  6137. animationFrameId = requestAnimationFrame(() => {
  6138. callback();
  6139. cleanup();
  6140. });
  6141. }
  6142. return () => cleanup();
  6143. }
  6144. function scheduleCallbackWithMicrotask(callback) {
  6145. queueMicrotask(() => callback());
  6146. return () => {
  6147. callback = noop;
  6148. };
  6149. }
  6150. class AsyncStackTaggingZoneSpec {
  6151. createTask;
  6152. constructor(namePrefix, consoleAsyncStackTaggingImpl = console) {
  6153. this.name = 'asyncStackTagging for ' + namePrefix;
  6154. this.createTask = consoleAsyncStackTaggingImpl?.createTask ?? (() => null);
  6155. }
  6156. // ZoneSpec implementation below.
  6157. name;
  6158. onScheduleTask(delegate, _current, target, task) {
  6159. task.consoleTask = this.createTask(`Zone - ${task.source || task.type}`);
  6160. return delegate.scheduleTask(target, task);
  6161. }
  6162. onInvokeTask(delegate, _currentZone, targetZone, task, applyThis, applyArgs) {
  6163. let ret;
  6164. if (task.consoleTask) {
  6165. ret = task.consoleTask.run(() => delegate.invokeTask(targetZone, task, applyThis, applyArgs));
  6166. }
  6167. else {
  6168. ret = delegate.invokeTask(targetZone, task, applyThis, applyArgs);
  6169. }
  6170. return ret;
  6171. }
  6172. }
  6173. const isAngularZoneProperty = 'isAngularZone';
  6174. const angularZoneInstanceIdProperty = isAngularZoneProperty + '_ID';
  6175. let ngZoneInstanceId = 0;
  6176. /**
  6177. * An injectable service for executing work inside or outside of the Angular zone.
  6178. *
  6179. * The most common use of this service is to optimize performance when starting a work consisting of
  6180. * one or more asynchronous tasks that don't require UI updates or error handling to be handled by
  6181. * Angular. Such tasks can be kicked off via {@link #runOutsideAngular} and if needed, these tasks
  6182. * can reenter the Angular zone via {@link #run}.
  6183. *
  6184. * <!-- TODO: add/fix links to:
  6185. * - docs explaining zones and the use of zones in Angular and change-detection
  6186. * - link to runOutsideAngular/run (throughout this file!)
  6187. * -->
  6188. *
  6189. * @usageNotes
  6190. * ### Example
  6191. *
  6192. * ```ts
  6193. * import {Component, NgZone} from '@angular/core';
  6194. * import {NgIf} from '@angular/common';
  6195. *
  6196. * @Component({
  6197. * selector: 'ng-zone-demo',
  6198. * template: `
  6199. * <h2>Demo: NgZone</h2>
  6200. *
  6201. * <p>Progress: {{progress}}%</p>
  6202. * <p *ngIf="progress >= 100">Done processing {{label}} of Angular zone!</p>
  6203. *
  6204. * <button (click)="processWithinAngularZone()">Process within Angular zone</button>
  6205. * <button (click)="processOutsideOfAngularZone()">Process outside of Angular zone</button>
  6206. * `,
  6207. * })
  6208. * export class NgZoneDemo {
  6209. * progress: number = 0;
  6210. * label: string;
  6211. *
  6212. * constructor(private _ngZone: NgZone) {}
  6213. *
  6214. * // Loop inside the Angular zone
  6215. * // so the UI DOES refresh after each setTimeout cycle
  6216. * processWithinAngularZone() {
  6217. * this.label = 'inside';
  6218. * this.progress = 0;
  6219. * this._increaseProgress(() => console.log('Inside Done!'));
  6220. * }
  6221. *
  6222. * // Loop outside of the Angular zone
  6223. * // so the UI DOES NOT refresh after each setTimeout cycle
  6224. * processOutsideOfAngularZone() {
  6225. * this.label = 'outside';
  6226. * this.progress = 0;
  6227. * this._ngZone.runOutsideAngular(() => {
  6228. * this._increaseProgress(() => {
  6229. * // reenter the Angular zone and display done
  6230. * this._ngZone.run(() => { console.log('Outside Done!'); });
  6231. * });
  6232. * });
  6233. * }
  6234. *
  6235. * _increaseProgress(doneCallback: () => void) {
  6236. * this.progress += 1;
  6237. * console.log(`Current progress: ${this.progress}%`);
  6238. *
  6239. * if (this.progress < 100) {
  6240. * window.setTimeout(() => this._increaseProgress(doneCallback), 10);
  6241. * } else {
  6242. * doneCallback();
  6243. * }
  6244. * }
  6245. * }
  6246. * ```
  6247. *
  6248. * @publicApi
  6249. */
  6250. class NgZone {
  6251. hasPendingMacrotasks = false;
  6252. hasPendingMicrotasks = false;
  6253. /**
  6254. * Whether there are no outstanding microtasks or macrotasks.
  6255. */
  6256. isStable = true;
  6257. /**
  6258. * Notifies when code enters Angular Zone. This gets fired first on VM Turn.
  6259. */
  6260. onUnstable = new EventEmitter(false);
  6261. /**
  6262. * Notifies when there is no more microtasks enqueued in the current VM Turn.
  6263. * This is a hint for Angular to do change detection, which may enqueue more microtasks.
  6264. * For this reason this event can fire multiple times per VM Turn.
  6265. */
  6266. onMicrotaskEmpty = new EventEmitter(false);
  6267. /**
  6268. * Notifies when the last `onMicrotaskEmpty` has run and there are no more microtasks, which
  6269. * implies we are about to relinquish VM turn.
  6270. * This event gets called just once.
  6271. */
  6272. onStable = new EventEmitter(false);
  6273. /**
  6274. * Notifies that an error has been delivered.
  6275. */
  6276. onError = new EventEmitter(false);
  6277. constructor(options) {
  6278. const { enableLongStackTrace = false, shouldCoalesceEventChangeDetection = false, shouldCoalesceRunChangeDetection = false, scheduleInRootZone = SCHEDULE_IN_ROOT_ZONE_DEFAULT, } = options;
  6279. if (typeof Zone == 'undefined') {
  6280. throw new RuntimeError(908 /* RuntimeErrorCode.MISSING_ZONEJS */, ngDevMode && `In this configuration Angular requires Zone.js`);
  6281. }
  6282. Zone.assertZonePatched();
  6283. const self = this;
  6284. self._nesting = 0;
  6285. self._outer = self._inner = Zone.current;
  6286. // AsyncStackTaggingZoneSpec provides `linked stack traces` to show
  6287. // where the async operation is scheduled. For more details, refer
  6288. // to this article, https://developer.chrome.com/blog/devtools-better-angular-debugging/
  6289. // And we only import this AsyncStackTaggingZoneSpec in development mode,
  6290. // in the production mode, the AsyncStackTaggingZoneSpec will be tree shaken away.
  6291. if (ngDevMode) {
  6292. self._inner = self._inner.fork(new AsyncStackTaggingZoneSpec('Angular'));
  6293. }
  6294. if (Zone['TaskTrackingZoneSpec']) {
  6295. self._inner = self._inner.fork(new Zone['TaskTrackingZoneSpec']());
  6296. }
  6297. if (enableLongStackTrace && Zone['longStackTraceZoneSpec']) {
  6298. self._inner = self._inner.fork(Zone['longStackTraceZoneSpec']);
  6299. }
  6300. // if shouldCoalesceRunChangeDetection is true, all tasks including event tasks will be
  6301. // coalesced, so shouldCoalesceEventChangeDetection option is not necessary and can be skipped.
  6302. self.shouldCoalesceEventChangeDetection =
  6303. !shouldCoalesceRunChangeDetection && shouldCoalesceEventChangeDetection;
  6304. self.shouldCoalesceRunChangeDetection = shouldCoalesceRunChangeDetection;
  6305. self.callbackScheduled = false;
  6306. self.scheduleInRootZone = scheduleInRootZone;
  6307. forkInnerZoneWithAngularBehavior(self);
  6308. }
  6309. /**
  6310. This method checks whether the method call happens within an Angular Zone instance.
  6311. */
  6312. static isInAngularZone() {
  6313. // Zone needs to be checked, because this method might be called even when NoopNgZone is used.
  6314. return typeof Zone !== 'undefined' && Zone.current.get(isAngularZoneProperty) === true;
  6315. }
  6316. /**
  6317. Assures that the method is called within the Angular Zone, otherwise throws an error.
  6318. */
  6319. static assertInAngularZone() {
  6320. if (!NgZone.isInAngularZone()) {
  6321. throw new RuntimeError(909 /* RuntimeErrorCode.UNEXPECTED_ZONE_STATE */, ngDevMode && 'Expected to be in Angular Zone, but it is not!');
  6322. }
  6323. }
  6324. /**
  6325. Assures that the method is called outside of the Angular Zone, otherwise throws an error.
  6326. */
  6327. static assertNotInAngularZone() {
  6328. if (NgZone.isInAngularZone()) {
  6329. throw new RuntimeError(909 /* RuntimeErrorCode.UNEXPECTED_ZONE_STATE */, ngDevMode && 'Expected to not be in Angular Zone, but it is!');
  6330. }
  6331. }
  6332. /**
  6333. * Executes the `fn` function synchronously within the Angular zone and returns value returned by
  6334. * the function.
  6335. *
  6336. * Running functions via `run` allows you to reenter Angular zone from a task that was executed
  6337. * outside of the Angular zone (typically started via {@link #runOutsideAngular}).
  6338. *
  6339. * Any future tasks or microtasks scheduled from within this function will continue executing from
  6340. * within the Angular zone.
  6341. *
  6342. * If a synchronous error happens it will be rethrown and not reported via `onError`.
  6343. */
  6344. run(fn, applyThis, applyArgs) {
  6345. return this._inner.run(fn, applyThis, applyArgs);
  6346. }
  6347. /**
  6348. * Executes the `fn` function synchronously within the Angular zone as a task and returns value
  6349. * returned by the function.
  6350. *
  6351. * Running functions via `runTask` allows you to reenter Angular zone from a task that was executed
  6352. * outside of the Angular zone (typically started via {@link #runOutsideAngular}).
  6353. *
  6354. * Any future tasks or microtasks scheduled from within this function will continue executing from
  6355. * within the Angular zone.
  6356. *
  6357. * If a synchronous error happens it will be rethrown and not reported via `onError`.
  6358. */
  6359. runTask(fn, applyThis, applyArgs, name) {
  6360. const zone = this._inner;
  6361. const task = zone.scheduleEventTask('NgZoneEvent: ' + name, fn, EMPTY_PAYLOAD, noop, noop);
  6362. try {
  6363. return zone.runTask(task, applyThis, applyArgs);
  6364. }
  6365. finally {
  6366. zone.cancelTask(task);
  6367. }
  6368. }
  6369. /**
  6370. * Same as `run`, except that synchronous errors are caught and forwarded via `onError` and not
  6371. * rethrown.
  6372. */
  6373. runGuarded(fn, applyThis, applyArgs) {
  6374. return this._inner.runGuarded(fn, applyThis, applyArgs);
  6375. }
  6376. /**
  6377. * Executes the `fn` function synchronously in Angular's parent zone and returns value returned by
  6378. * the function.
  6379. *
  6380. * Running functions via {@link #runOutsideAngular} allows you to escape Angular's zone and do
  6381. * work that
  6382. * doesn't trigger Angular change-detection or is subject to Angular's error handling.
  6383. *
  6384. * Any future tasks or microtasks scheduled from within this function will continue executing from
  6385. * outside of the Angular zone.
  6386. *
  6387. * Use {@link #run} to reenter the Angular zone and do work that updates the application model.
  6388. */
  6389. runOutsideAngular(fn) {
  6390. return this._outer.run(fn);
  6391. }
  6392. }
  6393. const EMPTY_PAYLOAD = {};
  6394. function checkStable(zone) {
  6395. // TODO: @JiaLiPassion, should check zone.isCheckStableRunning to prevent
  6396. // re-entry. The case is:
  6397. //
  6398. // @Component({...})
  6399. // export class AppComponent {
  6400. // constructor(private ngZone: NgZone) {
  6401. // this.ngZone.onStable.subscribe(() => {
  6402. // this.ngZone.run(() => console.log('stable'););
  6403. // });
  6404. // }
  6405. //
  6406. // The onStable subscriber run another function inside ngZone
  6407. // which causes `checkStable()` re-entry.
  6408. // But this fix causes some issues in g3, so this fix will be
  6409. // launched in another PR.
  6410. if (zone._nesting == 0 && !zone.hasPendingMicrotasks && !zone.isStable) {
  6411. try {
  6412. zone._nesting++;
  6413. zone.onMicrotaskEmpty.emit(null);
  6414. }
  6415. finally {
  6416. zone._nesting--;
  6417. if (!zone.hasPendingMicrotasks) {
  6418. try {
  6419. zone.runOutsideAngular(() => zone.onStable.emit(null));
  6420. }
  6421. finally {
  6422. zone.isStable = true;
  6423. }
  6424. }
  6425. }
  6426. }
  6427. }
  6428. function delayChangeDetectionForEvents(zone) {
  6429. /**
  6430. * We also need to check _nesting here
  6431. * Consider the following case with shouldCoalesceRunChangeDetection = true
  6432. *
  6433. * ngZone.run(() => {});
  6434. * ngZone.run(() => {});
  6435. *
  6436. * We want the two `ngZone.run()` only trigger one change detection
  6437. * when shouldCoalesceRunChangeDetection is true.
  6438. * And because in this case, change detection run in async way(requestAnimationFrame),
  6439. * so we also need to check the _nesting here to prevent multiple
  6440. * change detections.
  6441. */
  6442. if (zone.isCheckStableRunning || zone.callbackScheduled) {
  6443. return;
  6444. }
  6445. zone.callbackScheduled = true;
  6446. function scheduleCheckStable() {
  6447. scheduleCallbackWithRafRace(() => {
  6448. zone.callbackScheduled = false;
  6449. updateMicroTaskStatus(zone);
  6450. zone.isCheckStableRunning = true;
  6451. checkStable(zone);
  6452. zone.isCheckStableRunning = false;
  6453. });
  6454. }
  6455. if (zone.scheduleInRootZone) {
  6456. Zone.root.run(() => {
  6457. scheduleCheckStable();
  6458. });
  6459. }
  6460. else {
  6461. zone._outer.run(() => {
  6462. scheduleCheckStable();
  6463. });
  6464. }
  6465. updateMicroTaskStatus(zone);
  6466. }
  6467. function forkInnerZoneWithAngularBehavior(zone) {
  6468. const delayChangeDetectionForEventsDelegate = () => {
  6469. delayChangeDetectionForEvents(zone);
  6470. };
  6471. const instanceId = ngZoneInstanceId++;
  6472. zone._inner = zone._inner.fork({
  6473. name: 'angular',
  6474. properties: {
  6475. [isAngularZoneProperty]: true,
  6476. [angularZoneInstanceIdProperty]: instanceId,
  6477. [angularZoneInstanceIdProperty + instanceId]: true,
  6478. },
  6479. onInvokeTask: (delegate, current, target, task, applyThis, applyArgs) => {
  6480. // Prevent triggering change detection when the flag is detected.
  6481. if (shouldBeIgnoredByZone(applyArgs)) {
  6482. return delegate.invokeTask(target, task, applyThis, applyArgs);
  6483. }
  6484. try {
  6485. onEnter(zone);
  6486. return delegate.invokeTask(target, task, applyThis, applyArgs);
  6487. }
  6488. finally {
  6489. if ((zone.shouldCoalesceEventChangeDetection && task.type === 'eventTask') ||
  6490. zone.shouldCoalesceRunChangeDetection) {
  6491. delayChangeDetectionForEventsDelegate();
  6492. }
  6493. onLeave(zone);
  6494. }
  6495. },
  6496. onInvoke: (delegate, current, target, callback, applyThis, applyArgs, source) => {
  6497. try {
  6498. onEnter(zone);
  6499. return delegate.invoke(target, callback, applyThis, applyArgs, source);
  6500. }
  6501. finally {
  6502. if (zone.shouldCoalesceRunChangeDetection &&
  6503. // Do not delay change detection when the task is the scheduler's tick.
  6504. // We need to synchronously trigger the stability logic so that the
  6505. // zone-based scheduler can prevent a duplicate ApplicationRef.tick
  6506. // by first checking if the scheduler tick is running. This does seem a bit roundabout,
  6507. // but we _do_ still want to trigger all the correct events when we exit the zone.run
  6508. // (`onMicrotaskEmpty` and `onStable` _should_ emit; developers can have code which
  6509. // relies on these events happening after change detection runs).
  6510. // Note: `zone.callbackScheduled` is already in delayChangeDetectionForEventsDelegate
  6511. // but is added here as well to prevent reads of applyArgs when not necessary
  6512. !zone.callbackScheduled &&
  6513. !isSchedulerTick(applyArgs)) {
  6514. delayChangeDetectionForEventsDelegate();
  6515. }
  6516. onLeave(zone);
  6517. }
  6518. },
  6519. onHasTask: (delegate, current, target, hasTaskState) => {
  6520. delegate.hasTask(target, hasTaskState);
  6521. if (current === target) {
  6522. // We are only interested in hasTask events which originate from our zone
  6523. // (A child hasTask event is not interesting to us)
  6524. if (hasTaskState.change == 'microTask') {
  6525. zone._hasPendingMicrotasks = hasTaskState.microTask;
  6526. updateMicroTaskStatus(zone);
  6527. checkStable(zone);
  6528. }
  6529. else if (hasTaskState.change == 'macroTask') {
  6530. zone.hasPendingMacrotasks = hasTaskState.macroTask;
  6531. }
  6532. }
  6533. },
  6534. onHandleError: (delegate, current, target, error) => {
  6535. delegate.handleError(target, error);
  6536. zone.runOutsideAngular(() => zone.onError.emit(error));
  6537. return false;
  6538. },
  6539. });
  6540. }
  6541. function updateMicroTaskStatus(zone) {
  6542. if (zone._hasPendingMicrotasks ||
  6543. ((zone.shouldCoalesceEventChangeDetection || zone.shouldCoalesceRunChangeDetection) &&
  6544. zone.callbackScheduled === true)) {
  6545. zone.hasPendingMicrotasks = true;
  6546. }
  6547. else {
  6548. zone.hasPendingMicrotasks = false;
  6549. }
  6550. }
  6551. function onEnter(zone) {
  6552. zone._nesting++;
  6553. if (zone.isStable) {
  6554. zone.isStable = false;
  6555. zone.onUnstable.emit(null);
  6556. }
  6557. }
  6558. function onLeave(zone) {
  6559. zone._nesting--;
  6560. checkStable(zone);
  6561. }
  6562. /**
  6563. * Provides a noop implementation of `NgZone` which does nothing. This zone requires explicit calls
  6564. * to framework to perform rendering.
  6565. */
  6566. class NoopNgZone {
  6567. hasPendingMicrotasks = false;
  6568. hasPendingMacrotasks = false;
  6569. isStable = true;
  6570. onUnstable = new EventEmitter();
  6571. onMicrotaskEmpty = new EventEmitter();
  6572. onStable = new EventEmitter();
  6573. onError = new EventEmitter();
  6574. run(fn, applyThis, applyArgs) {
  6575. return fn.apply(applyThis, applyArgs);
  6576. }
  6577. runGuarded(fn, applyThis, applyArgs) {
  6578. return fn.apply(applyThis, applyArgs);
  6579. }
  6580. runOutsideAngular(fn) {
  6581. return fn();
  6582. }
  6583. runTask(fn, applyThis, applyArgs, name) {
  6584. return fn.apply(applyThis, applyArgs);
  6585. }
  6586. }
  6587. function shouldBeIgnoredByZone(applyArgs) {
  6588. return hasApplyArgsData(applyArgs, '__ignore_ng_zone__');
  6589. }
  6590. function isSchedulerTick(applyArgs) {
  6591. return hasApplyArgsData(applyArgs, '__scheduler_tick__');
  6592. }
  6593. function hasApplyArgsData(applyArgs, key) {
  6594. if (!Array.isArray(applyArgs)) {
  6595. return false;
  6596. }
  6597. // We should only ever get 1 arg passed through to invokeTask.
  6598. // Short circuit here incase that behavior changes.
  6599. if (applyArgs.length !== 1) {
  6600. return false;
  6601. }
  6602. return applyArgs[0]?.data?.[key] === true;
  6603. }
  6604. function getNgZone(ngZoneToUse = 'zone.js', options) {
  6605. if (ngZoneToUse === 'noop') {
  6606. return new NoopNgZone();
  6607. }
  6608. if (ngZoneToUse === 'zone.js') {
  6609. return new NgZone(options);
  6610. }
  6611. return ngZoneToUse;
  6612. }
  6613. /**
  6614. * Provides a hook for centralized exception handling.
  6615. *
  6616. * The default implementation of `ErrorHandler` prints error messages to the `console`. To
  6617. * intercept error handling, write a custom exception handler that replaces this default as
  6618. * appropriate for your app.
  6619. *
  6620. * @usageNotes
  6621. * ### Example
  6622. *
  6623. * ```ts
  6624. * class MyErrorHandler implements ErrorHandler {
  6625. * handleError(error) {
  6626. * // do something with the exception
  6627. * }
  6628. * }
  6629. *
  6630. * // Provide in standalone apps
  6631. * bootstrapApplication(AppComponent, {
  6632. * providers: [{provide: ErrorHandler, useClass: MyErrorHandler}]
  6633. * })
  6634. *
  6635. * // Provide in module-based apps
  6636. * @NgModule({
  6637. * providers: [{provide: ErrorHandler, useClass: MyErrorHandler}]
  6638. * })
  6639. * class MyModule {}
  6640. * ```
  6641. *
  6642. * @publicApi
  6643. */
  6644. class ErrorHandler {
  6645. /**
  6646. * @internal
  6647. */
  6648. _console = console;
  6649. handleError(error) {
  6650. this._console.error('ERROR', error);
  6651. }
  6652. }
  6653. /**
  6654. * `InjectionToken` used to configure how to call the `ErrorHandler`.
  6655. *
  6656. * `NgZone` is provided by default today so the default (and only) implementation for this
  6657. * is calling `ErrorHandler.handleError` outside of the Angular zone.
  6658. */
  6659. const INTERNAL_APPLICATION_ERROR_HANDLER = new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'internal error handler' : '', {
  6660. providedIn: 'root',
  6661. factory: () => {
  6662. const zone = inject(NgZone);
  6663. const userErrorHandler = inject(ErrorHandler);
  6664. return (e) => zone.runOutsideAngular(() => userErrorHandler.handleError(e));
  6665. },
  6666. });
  6667. /**
  6668. * An `OutputEmitterRef` is created by the `output()` function and can be
  6669. * used to emit values to consumers of your directive or component.
  6670. *
  6671. * Consumers of your directive/component can bind to the output and
  6672. * subscribe to changes via the bound event syntax. For example:
  6673. *
  6674. * ```html
  6675. * <my-comp (valueChange)="processNewValue($event)" />
  6676. * ```
  6677. *
  6678. * @publicAPI
  6679. */
  6680. class OutputEmitterRef {
  6681. destroyed = false;
  6682. listeners = null;
  6683. errorHandler = inject(ErrorHandler, { optional: true });
  6684. /** @internal */
  6685. destroyRef = inject(DestroyRef);
  6686. constructor() {
  6687. // Clean-up all listeners and mark as destroyed upon destroy.
  6688. this.destroyRef.onDestroy(() => {
  6689. this.destroyed = true;
  6690. this.listeners = null;
  6691. });
  6692. }
  6693. subscribe(callback) {
  6694. if (this.destroyed) {
  6695. throw new RuntimeError(953 /* RuntimeErrorCode.OUTPUT_REF_DESTROYED */, ngDevMode &&
  6696. 'Unexpected subscription to destroyed `OutputRef`. ' +
  6697. 'The owning directive/component is destroyed.');
  6698. }
  6699. (this.listeners ??= []).push(callback);
  6700. return {
  6701. unsubscribe: () => {
  6702. const idx = this.listeners?.indexOf(callback);
  6703. if (idx !== undefined && idx !== -1) {
  6704. this.listeners?.splice(idx, 1);
  6705. }
  6706. },
  6707. };
  6708. }
  6709. /** Emits a new value to the output. */
  6710. emit(value) {
  6711. if (this.destroyed) {
  6712. console.warn(formatRuntimeError(953 /* RuntimeErrorCode.OUTPUT_REF_DESTROYED */, ngDevMode &&
  6713. 'Unexpected emit for destroyed `OutputRef`. ' +
  6714. 'The owning directive/component is destroyed.'));
  6715. return;
  6716. }
  6717. if (this.listeners === null) {
  6718. return;
  6719. }
  6720. const previousConsumer = setActiveConsumer$1(null);
  6721. try {
  6722. for (const listenerFn of this.listeners) {
  6723. try {
  6724. listenerFn(value);
  6725. }
  6726. catch (err) {
  6727. this.errorHandler?.handleError(err);
  6728. }
  6729. }
  6730. }
  6731. finally {
  6732. setActiveConsumer$1(previousConsumer);
  6733. }
  6734. }
  6735. }
  6736. /** Gets the owning `DestroyRef` for the given output. */
  6737. function getOutputDestroyRef(ref) {
  6738. return ref.destroyRef;
  6739. }
  6740. /**
  6741. * The `output` function allows declaration of Angular outputs in
  6742. * directives and components.
  6743. *
  6744. * You can use outputs to emit values to parent directives and component.
  6745. * Parents can subscribe to changes via:
  6746. *
  6747. * - template event bindings. For example, `(myOutput)="doSomething($event)"`
  6748. * - programmatic subscription by using `OutputRef#subscribe`.
  6749. *
  6750. * @usageNotes
  6751. *
  6752. * To use `output()`, import the function from `@angular/core`.
  6753. *
  6754. * ```ts
  6755. * import {output} from '@angular/core';
  6756. * ```
  6757. *
  6758. * Inside your component, introduce a new class member and initialize
  6759. * it with a call to `output`.
  6760. *
  6761. * ```ts
  6762. * @Directive({
  6763. * ...
  6764. * })
  6765. * export class MyDir {
  6766. * nameChange = output<string>(); // OutputEmitterRef<string>
  6767. * onClick = output(); // OutputEmitterRef<void>
  6768. * }
  6769. * ```
  6770. *
  6771. * You can emit values to consumers of your directive, by using
  6772. * the `emit` method from `OutputEmitterRef`.
  6773. *
  6774. * ```ts
  6775. * updateName(newName: string): void {
  6776. * this.nameChange.emit(newName);
  6777. * }
  6778. * ```
  6779. * @initializerApiFunction {"showTypesInSignaturePreview": true}
  6780. * @publicAPI
  6781. */
  6782. function output(opts) {
  6783. ngDevMode && assertInInjectionContext(output);
  6784. return new OutputEmitterRef();
  6785. }
  6786. function inputFunction(initialValue, opts) {
  6787. ngDevMode && assertInInjectionContext(input);
  6788. return createInputSignal(initialValue, opts);
  6789. }
  6790. function inputRequiredFunction(opts) {
  6791. ngDevMode && assertInInjectionContext(input);
  6792. return createInputSignal(REQUIRED_UNSET_VALUE, opts);
  6793. }
  6794. /**
  6795. * The `input` function allows declaration of Angular inputs in directives
  6796. * and components.
  6797. *
  6798. * There are two variants of inputs that can be declared:
  6799. *
  6800. * 1. **Optional inputs** with an initial value.
  6801. * 2. **Required inputs** that consumers need to set.
  6802. *
  6803. * By default, the `input` function will declare optional inputs that
  6804. * always have an initial value. Required inputs can be declared
  6805. * using the `input.required()` function.
  6806. *
  6807. * Inputs are signals. The values of an input are exposed as a `Signal`.
  6808. * The signal always holds the latest value of the input that is bound
  6809. * from the parent.
  6810. *
  6811. * @usageNotes
  6812. * To use signal-based inputs, import `input` from `@angular/core`.
  6813. *
  6814. * ```ts
  6815. * import {input} from '@angular/core`;
  6816. * ```
  6817. *
  6818. * Inside your component, introduce a new class member and initialize
  6819. * it with a call to `input` or `input.required`.
  6820. *
  6821. * ```ts
  6822. * @Component({
  6823. * ...
  6824. * })
  6825. * export class UserProfileComponent {
  6826. * firstName = input<string>(); // Signal<string|undefined>
  6827. * lastName = input.required<string>(); // Signal<string>
  6828. * age = input(0) // Signal<number>
  6829. * }
  6830. * ```
  6831. *
  6832. * Inside your component template, you can display values of the inputs
  6833. * by calling the signal.
  6834. *
  6835. * ```html
  6836. * <span>{{firstName()}}</span>
  6837. * ```
  6838. *
  6839. * @publicAPI
  6840. * @initializerApiFunction
  6841. */
  6842. const input = (() => {
  6843. // Note: This may be considered a side-effect, but nothing will depend on
  6844. // this assignment, unless this `input` constant export is accessed. It's a
  6845. // self-contained side effect that is local to the user facing`input` export.
  6846. inputFunction.required = inputRequiredFunction;
  6847. return inputFunction;
  6848. })();
  6849. /**
  6850. * Creates an ElementRef from the most recent node.
  6851. *
  6852. * @returns The ElementRef instance to use
  6853. */
  6854. function injectElementRef() {
  6855. return createElementRef(getCurrentTNode(), getLView());
  6856. }
  6857. /**
  6858. * Creates an ElementRef given a node.
  6859. *
  6860. * @param tNode The node for which you'd like an ElementRef
  6861. * @param lView The view to which the node belongs
  6862. * @returns The ElementRef instance to use
  6863. */
  6864. function createElementRef(tNode, lView) {
  6865. return new ElementRef(getNativeByTNode(tNode, lView));
  6866. }
  6867. /**
  6868. * A wrapper around a native element inside of a View.
  6869. *
  6870. * An `ElementRef` is backed by a render-specific element. In the browser, this is usually a DOM
  6871. * element.
  6872. *
  6873. * @security Permitting direct access to the DOM can make your application more vulnerable to
  6874. * XSS attacks. Carefully review any use of `ElementRef` in your code. For more detail, see the
  6875. * [Security Guide](https://g.co/ng/security).
  6876. *
  6877. * @publicApi
  6878. */
  6879. // Note: We don't expose things like `Injector`, `ViewContainer`, ... here,
  6880. // i.e. users have to ask for what they need. With that, we can build better analysis tools
  6881. // and could do better codegen in the future.
  6882. class ElementRef {
  6883. /**
  6884. * <div class="callout is-critical">
  6885. * <header>Use with caution</header>
  6886. * <p>
  6887. * Use this API as the last resort when direct access to DOM is needed. Use templating and
  6888. * data-binding provided by Angular instead. Alternatively you can take a look at
  6889. * {@link Renderer2} which provides an API that can be safely used.
  6890. * </p>
  6891. * </div>
  6892. */
  6893. nativeElement;
  6894. constructor(nativeElement) {
  6895. this.nativeElement = nativeElement;
  6896. }
  6897. /**
  6898. * @internal
  6899. * @nocollapse
  6900. */
  6901. static __NG_ELEMENT_ID__ = injectElementRef;
  6902. }
  6903. /**
  6904. * Unwraps `ElementRef` and return the `nativeElement`.
  6905. *
  6906. * @param value value to unwrap
  6907. * @returns `nativeElement` if `ElementRef` otherwise returns value as is.
  6908. */
  6909. function unwrapElementRef(value) {
  6910. return value instanceof ElementRef ? value.nativeElement : value;
  6911. }
  6912. /**
  6913. * Checks if the given `value` is a reactive `Signal`.
  6914. */
  6915. function isSignal(value) {
  6916. return typeof value === 'function' && value[SIGNAL] !== undefined;
  6917. }
  6918. /**
  6919. * Utility function used during template type checking to extract the value from a `WritableSignal`.
  6920. * @codeGenApi
  6921. */
  6922. function ɵunwrapWritableSignal(value) {
  6923. // Note: the function uses `WRITABLE_SIGNAL` as a brand instead of `WritableSignal<T>`,
  6924. // because the latter incorrectly unwraps non-signal getter functions.
  6925. return null;
  6926. }
  6927. /**
  6928. * Create a `Signal` that can be set or updated directly.
  6929. */
  6930. function signal(initialValue, options) {
  6931. const signalFn = createSignal(initialValue, options?.equal);
  6932. const node = signalFn[SIGNAL];
  6933. signalFn.set = (newValue) => signalSetFn(node, newValue);
  6934. signalFn.update = (updateFn) => signalUpdateFn(node, updateFn);
  6935. signalFn.asReadonly = signalAsReadonlyFn.bind(signalFn);
  6936. if (ngDevMode) {
  6937. signalFn.toString = () => `[Signal: ${signalFn()}]`;
  6938. node.debugName = options?.debugName;
  6939. }
  6940. return signalFn;
  6941. }
  6942. function signalAsReadonlyFn() {
  6943. const node = this[SIGNAL];
  6944. if (node.readonlyFn === undefined) {
  6945. const readonlyFn = () => this();
  6946. readonlyFn[SIGNAL] = node;
  6947. node.readonlyFn = readonlyFn;
  6948. }
  6949. return node.readonlyFn;
  6950. }
  6951. /**
  6952. * Checks if the given `value` is a writeable signal.
  6953. */
  6954. function isWritableSignal(value) {
  6955. return isSignal(value) && typeof value.set === 'function';
  6956. }
  6957. function symbolIterator() {
  6958. // @ts-expect-error accessing a private member
  6959. return this._results[Symbol.iterator]();
  6960. }
  6961. /**
  6962. * An unmodifiable list of items that Angular keeps up to date when the state
  6963. * of the application changes.
  6964. *
  6965. * The type of object that {@link ViewChildren}, {@link ContentChildren}, and {@link QueryList}
  6966. * provide.
  6967. *
  6968. * Implements an iterable interface, therefore it can be used in both ES6
  6969. * javascript `for (var i of items)` loops as well as in Angular templates with
  6970. * `*ngFor="let i of myList"`.
  6971. *
  6972. * Changes can be observed by subscribing to the changes `Observable`.
  6973. *
  6974. * NOTE: In the future this class will implement an `Observable` interface.
  6975. *
  6976. * @usageNotes
  6977. * ### Example
  6978. * ```ts
  6979. * @Component({...})
  6980. * class Container {
  6981. * @ViewChildren(Item) items:QueryList<Item>;
  6982. * }
  6983. * ```
  6984. *
  6985. * @publicApi
  6986. */
  6987. class QueryList {
  6988. _emitDistinctChangesOnly;
  6989. dirty = true;
  6990. _onDirty = undefined;
  6991. _results = [];
  6992. _changesDetected = false;
  6993. _changes = undefined;
  6994. length = 0;
  6995. first = undefined;
  6996. last = undefined;
  6997. /**
  6998. * Returns `Observable` of `QueryList` notifying the subscriber of changes.
  6999. */
  7000. get changes() {
  7001. return (this._changes ??= new Subject());
  7002. }
  7003. /**
  7004. * @param emitDistinctChangesOnly Whether `QueryList.changes` should fire only when actual change
  7005. * has occurred. Or if it should fire when query is recomputed. (recomputing could resolve in
  7006. * the same result)
  7007. */
  7008. constructor(_emitDistinctChangesOnly = false) {
  7009. this._emitDistinctChangesOnly = _emitDistinctChangesOnly;
  7010. }
  7011. /**
  7012. * Returns the QueryList entry at `index`.
  7013. */
  7014. get(index) {
  7015. return this._results[index];
  7016. }
  7017. /**
  7018. * See
  7019. * [Array.map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
  7020. */
  7021. map(fn) {
  7022. return this._results.map(fn);
  7023. }
  7024. filter(fn) {
  7025. return this._results.filter(fn);
  7026. }
  7027. /**
  7028. * See
  7029. * [Array.find](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find)
  7030. */
  7031. find(fn) {
  7032. return this._results.find(fn);
  7033. }
  7034. /**
  7035. * See
  7036. * [Array.reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)
  7037. */
  7038. reduce(fn, init) {
  7039. return this._results.reduce(fn, init);
  7040. }
  7041. /**
  7042. * See
  7043. * [Array.forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)
  7044. */
  7045. forEach(fn) {
  7046. this._results.forEach(fn);
  7047. }
  7048. /**
  7049. * See
  7050. * [Array.some](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some)
  7051. */
  7052. some(fn) {
  7053. return this._results.some(fn);
  7054. }
  7055. /**
  7056. * Returns a copy of the internal results list as an Array.
  7057. */
  7058. toArray() {
  7059. return this._results.slice();
  7060. }
  7061. toString() {
  7062. return this._results.toString();
  7063. }
  7064. /**
  7065. * Updates the stored data of the query list, and resets the `dirty` flag to `false`, so that
  7066. * on change detection, it will not notify of changes to the queries, unless a new change
  7067. * occurs.
  7068. *
  7069. * @param resultsTree The query results to store
  7070. * @param identityAccessor Optional function for extracting stable object identity from a value
  7071. * in the array. This function is executed for each element of the query result list while
  7072. * comparing current query list with the new one (provided as a first argument of the `reset`
  7073. * function) to detect if the lists are different. If the function is not provided, elements
  7074. * are compared as is (without any pre-processing).
  7075. */
  7076. reset(resultsTree, identityAccessor) {
  7077. this.dirty = false;
  7078. const newResultFlat = flatten(resultsTree);
  7079. if ((this._changesDetected = !arrayEquals(this._results, newResultFlat, identityAccessor))) {
  7080. this._results = newResultFlat;
  7081. this.length = newResultFlat.length;
  7082. this.last = newResultFlat[this.length - 1];
  7083. this.first = newResultFlat[0];
  7084. }
  7085. }
  7086. /**
  7087. * Triggers a change event by emitting on the `changes` {@link EventEmitter}.
  7088. */
  7089. notifyOnChanges() {
  7090. if (this._changes !== undefined && (this._changesDetected || !this._emitDistinctChangesOnly))
  7091. this._changes.next(this);
  7092. }
  7093. /** @internal */
  7094. onDirty(cb) {
  7095. this._onDirty = cb;
  7096. }
  7097. /** internal */
  7098. setDirty() {
  7099. this.dirty = true;
  7100. this._onDirty?.();
  7101. }
  7102. /** internal */
  7103. destroy() {
  7104. if (this._changes !== undefined) {
  7105. this._changes.complete();
  7106. this._changes.unsubscribe();
  7107. }
  7108. }
  7109. [Symbol.iterator] = (() => symbolIterator)();
  7110. }
  7111. /**
  7112. * The name of an attribute that can be added to the hydration boundary node
  7113. * (component host node) to disable hydration for the content within that boundary.
  7114. */
  7115. const SKIP_HYDRATION_ATTR_NAME = 'ngSkipHydration';
  7116. /** Lowercase name of the `ngSkipHydration` attribute used for case-insensitive comparisons. */
  7117. const SKIP_HYDRATION_ATTR_NAME_LOWER_CASE = 'ngskiphydration';
  7118. /**
  7119. * Helper function to check if a given TNode has the 'ngSkipHydration' attribute.
  7120. */
  7121. function hasSkipHydrationAttrOnTNode(tNode) {
  7122. const attrs = tNode.mergedAttrs;
  7123. if (attrs === null)
  7124. return false;
  7125. // only ever look at the attribute name and skip the values
  7126. for (let i = 0; i < attrs.length; i += 2) {
  7127. const value = attrs[i];
  7128. // This is a marker, which means that the static attributes section is over,
  7129. // so we can exit early.
  7130. if (typeof value === 'number')
  7131. return false;
  7132. if (typeof value === 'string' && value.toLowerCase() === SKIP_HYDRATION_ATTR_NAME_LOWER_CASE) {
  7133. return true;
  7134. }
  7135. }
  7136. return false;
  7137. }
  7138. /**
  7139. * Helper function to check if a given RElement has the 'ngSkipHydration' attribute.
  7140. */
  7141. function hasSkipHydrationAttrOnRElement(rNode) {
  7142. return rNode.hasAttribute(SKIP_HYDRATION_ATTR_NAME);
  7143. }
  7144. /**
  7145. * Checks whether a TNode has a flag to indicate that it's a part of
  7146. * a skip hydration block.
  7147. */
  7148. function hasInSkipHydrationBlockFlag(tNode) {
  7149. return (tNode.flags & 128 /* TNodeFlags.inSkipHydrationBlock */) === 128 /* TNodeFlags.inSkipHydrationBlock */;
  7150. }
  7151. /**
  7152. * Helper function that determines if a given node is within a skip hydration block
  7153. * by navigating up the TNode tree to see if any parent nodes have skip hydration
  7154. * attribute.
  7155. */
  7156. function isInSkipHydrationBlock(tNode) {
  7157. if (hasInSkipHydrationBlockFlag(tNode)) {
  7158. return true;
  7159. }
  7160. let currentTNode = tNode.parent;
  7161. while (currentTNode) {
  7162. if (hasInSkipHydrationBlockFlag(tNode) || hasSkipHydrationAttrOnTNode(currentTNode)) {
  7163. return true;
  7164. }
  7165. currentTNode = currentTNode.parent;
  7166. }
  7167. return false;
  7168. }
  7169. /**
  7170. * Check if an i18n block is in a skip hydration section by looking at a parent TNode
  7171. * to determine if this TNode is in a skip hydration section or the TNode has
  7172. * the `ngSkipHydration` attribute.
  7173. */
  7174. function isI18nInSkipHydrationBlock(parentTNode) {
  7175. return (hasInSkipHydrationBlockFlag(parentTNode) ||
  7176. hasSkipHydrationAttrOnTNode(parentTNode) ||
  7177. isInSkipHydrationBlock(parentTNode));
  7178. }
  7179. /**
  7180. * The strategy that the default change detector uses to detect changes.
  7181. * When set, takes effect the next time change detection is triggered.
  7182. *
  7183. * @see {@link /api/core/ChangeDetectorRef?tab=usage-notes Change detection usage}
  7184. * @see {@link /best-practices/skipping-subtrees Skipping component subtrees}
  7185. *
  7186. * @publicApi
  7187. */
  7188. var ChangeDetectionStrategy;
  7189. (function (ChangeDetectionStrategy) {
  7190. /**
  7191. * Use the `CheckOnce` strategy, meaning that automatic change detection is deactivated
  7192. * until reactivated by setting the strategy to `Default` (`CheckAlways`).
  7193. * Change detection can still be explicitly invoked.
  7194. * This strategy applies to all child directives and cannot be overridden.
  7195. */
  7196. ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush";
  7197. /**
  7198. * Use the default `CheckAlways` strategy, in which change detection is automatic until
  7199. * explicitly deactivated.
  7200. */
  7201. ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default";
  7202. })(ChangeDetectionStrategy || (ChangeDetectionStrategy = {}));
  7203. // Keeps track of the currently-active LViews.
  7204. const TRACKED_LVIEWS = new Map();
  7205. // Used for generating unique IDs for LViews.
  7206. let uniqueIdCounter = 0;
  7207. /** Gets a unique ID that can be assigned to an LView. */
  7208. function getUniqueLViewId() {
  7209. return uniqueIdCounter++;
  7210. }
  7211. /** Starts tracking an LView. */
  7212. function registerLView(lView) {
  7213. ngDevMode && assertNumber(lView[ID], 'LView must have an ID in order to be registered');
  7214. TRACKED_LVIEWS.set(lView[ID], lView);
  7215. }
  7216. /** Gets an LView by its unique ID. */
  7217. function getLViewById(id) {
  7218. ngDevMode && assertNumber(id, 'ID used for LView lookup must be a number');
  7219. return TRACKED_LVIEWS.get(id) || null;
  7220. }
  7221. /** Stops tracking an LView. */
  7222. function unregisterLView(lView) {
  7223. ngDevMode && assertNumber(lView[ID], 'Cannot stop tracking an LView that does not have an ID');
  7224. TRACKED_LVIEWS.delete(lView[ID]);
  7225. }
  7226. /** Gets the currently-tracked views. */
  7227. function getTrackedLViews() {
  7228. return TRACKED_LVIEWS;
  7229. }
  7230. /**
  7231. * The internal view context which is specific to a given DOM element, directive or
  7232. * component instance. Each value in here (besides the LView and element node details)
  7233. * can be present, null or undefined. If undefined then it implies the value has not been
  7234. * looked up yet, otherwise, if null, then a lookup was executed and nothing was found.
  7235. *
  7236. * Each value will get filled when the respective value is examined within the getContext
  7237. * function. The component, element and each directive instance will share the same instance
  7238. * of the context.
  7239. */
  7240. class LContext {
  7241. lViewId;
  7242. nodeIndex;
  7243. native;
  7244. /**
  7245. * The instance of the Component node.
  7246. */
  7247. component;
  7248. /**
  7249. * The list of active directives that exist on this element.
  7250. */
  7251. directives;
  7252. /**
  7253. * The map of local references (local reference name => element or directive instance) that
  7254. * exist on this element.
  7255. */
  7256. localRefs;
  7257. /** Component's parent view data. */
  7258. get lView() {
  7259. return getLViewById(this.lViewId);
  7260. }
  7261. constructor(
  7262. /**
  7263. * ID of the component's parent view data.
  7264. */
  7265. lViewId,
  7266. /**
  7267. * The index instance of the node.
  7268. */
  7269. nodeIndex,
  7270. /**
  7271. * The instance of the DOM node that is attached to the lNode.
  7272. */
  7273. native) {
  7274. this.lViewId = lViewId;
  7275. this.nodeIndex = nodeIndex;
  7276. this.native = native;
  7277. }
  7278. }
  7279. /**
  7280. * Returns the matching `LContext` data for a given DOM node, directive or component instance.
  7281. *
  7282. * This function will examine the provided DOM element, component, or directive instance\'s
  7283. * monkey-patched property to derive the `LContext` data. Once called then the monkey-patched
  7284. * value will be that of the newly created `LContext`.
  7285. *
  7286. * If the monkey-patched value is the `LView` instance then the context value for that
  7287. * target will be created and the monkey-patch reference will be updated. Therefore when this
  7288. * function is called it may mutate the provided element\'s, component\'s or any of the associated
  7289. * directive\'s monkey-patch values.
  7290. *
  7291. * If the monkey-patch value is not detected then the code will walk up the DOM until an element
  7292. * is found which contains a monkey-patch reference. When that occurs then the provided element
  7293. * will be updated with a new context (which is then returned). If the monkey-patch value is not
  7294. * detected for a component/directive instance then it will throw an error (all components and
  7295. * directives should be automatically monkey-patched by ivy).
  7296. *
  7297. * @param target Component, Directive or DOM Node.
  7298. */
  7299. function getLContext(target) {
  7300. let mpValue = readPatchedData(target);
  7301. if (mpValue) {
  7302. // only when it's an array is it considered an LView instance
  7303. // ... otherwise it's an already constructed LContext instance
  7304. if (isLView(mpValue)) {
  7305. const lView = mpValue;
  7306. let nodeIndex;
  7307. let component = undefined;
  7308. let directives = undefined;
  7309. if (isComponentInstance(target)) {
  7310. nodeIndex = findViaComponent(lView, target);
  7311. if (nodeIndex == -1) {
  7312. throw new Error('The provided component was not found in the application');
  7313. }
  7314. component = target;
  7315. }
  7316. else if (isDirectiveInstance(target)) {
  7317. nodeIndex = findViaDirective(lView, target);
  7318. if (nodeIndex == -1) {
  7319. throw new Error('The provided directive was not found in the application');
  7320. }
  7321. directives = getDirectivesAtNodeIndex(nodeIndex, lView);
  7322. }
  7323. else {
  7324. nodeIndex = findViaNativeElement(lView, target);
  7325. if (nodeIndex == -1) {
  7326. return null;
  7327. }
  7328. }
  7329. // the goal is not to fill the entire context full of data because the lookups
  7330. // are expensive. Instead, only the target data (the element, component, container, ICU
  7331. // expression or directive details) are filled into the context. If called multiple times
  7332. // with different target values then the missing target data will be filled in.
  7333. const native = unwrapRNode(lView[nodeIndex]);
  7334. const existingCtx = readPatchedData(native);
  7335. const context = existingCtx && !Array.isArray(existingCtx)
  7336. ? existingCtx
  7337. : createLContext(lView, nodeIndex, native);
  7338. // only when the component has been discovered then update the monkey-patch
  7339. if (component && context.component === undefined) {
  7340. context.component = component;
  7341. attachPatchData(context.component, context);
  7342. }
  7343. // only when the directives have been discovered then update the monkey-patch
  7344. if (directives && context.directives === undefined) {
  7345. context.directives = directives;
  7346. for (let i = 0; i < directives.length; i++) {
  7347. attachPatchData(directives[i], context);
  7348. }
  7349. }
  7350. attachPatchData(context.native, context);
  7351. mpValue = context;
  7352. }
  7353. }
  7354. else {
  7355. const rElement = target;
  7356. ngDevMode && assertDomNode(rElement);
  7357. // if the context is not found then we need to traverse upwards up the DOM
  7358. // to find the nearest element that has already been monkey patched with data
  7359. let parent = rElement;
  7360. while ((parent = parent.parentNode)) {
  7361. const parentContext = readPatchedData(parent);
  7362. if (parentContext) {
  7363. const lView = Array.isArray(parentContext) ? parentContext : parentContext.lView;
  7364. // the edge of the app was also reached here through another means
  7365. // (maybe because the DOM was changed manually).
  7366. if (!lView) {
  7367. return null;
  7368. }
  7369. const index = findViaNativeElement(lView, rElement);
  7370. if (index >= 0) {
  7371. const native = unwrapRNode(lView[index]);
  7372. const context = createLContext(lView, index, native);
  7373. attachPatchData(native, context);
  7374. mpValue = context;
  7375. break;
  7376. }
  7377. }
  7378. }
  7379. }
  7380. return mpValue || null;
  7381. }
  7382. /**
  7383. * Creates an empty instance of a `LContext` context
  7384. */
  7385. function createLContext(lView, nodeIndex, native) {
  7386. return new LContext(lView[ID], nodeIndex, native);
  7387. }
  7388. /**
  7389. * Takes a component instance and returns the view for that component.
  7390. *
  7391. * @param componentInstance
  7392. * @returns The component's view
  7393. */
  7394. function getComponentViewByInstance(componentInstance) {
  7395. let patchedData = readPatchedData(componentInstance);
  7396. let lView;
  7397. if (isLView(patchedData)) {
  7398. const contextLView = patchedData;
  7399. const nodeIndex = findViaComponent(contextLView, componentInstance);
  7400. lView = getComponentLViewByIndex(nodeIndex, contextLView);
  7401. const context = createLContext(contextLView, nodeIndex, lView[HOST]);
  7402. context.component = componentInstance;
  7403. attachPatchData(componentInstance, context);
  7404. attachPatchData(context.native, context);
  7405. }
  7406. else {
  7407. const context = patchedData;
  7408. const contextLView = context.lView;
  7409. ngDevMode && assertLView(contextLView);
  7410. lView = getComponentLViewByIndex(context.nodeIndex, contextLView);
  7411. }
  7412. return lView;
  7413. }
  7414. /**
  7415. * This property will be monkey-patched on elements, components and directives.
  7416. */
  7417. const MONKEY_PATCH_KEY_NAME = '__ngContext__';
  7418. /**
  7419. * Assigns the given data to the given target (which could be a component,
  7420. * directive or DOM node instance) using monkey-patching.
  7421. */
  7422. function attachPatchData(target, data) {
  7423. ngDevMode && assertDefined(target, 'Target expected');
  7424. // Only attach the ID of the view in order to avoid memory leaks (see #41047). We only do this
  7425. // for `LView`, because we have control over when an `LView` is created and destroyed, whereas
  7426. // we can't know when to remove an `LContext`.
  7427. if (isLView(data)) {
  7428. target[MONKEY_PATCH_KEY_NAME] = data[ID];
  7429. registerLView(data);
  7430. }
  7431. else {
  7432. target[MONKEY_PATCH_KEY_NAME] = data;
  7433. }
  7434. }
  7435. /**
  7436. * Returns the monkey-patch value data present on the target (which could be
  7437. * a component, directive or a DOM node).
  7438. */
  7439. function readPatchedData(target) {
  7440. ngDevMode && assertDefined(target, 'Target expected');
  7441. const data = target[MONKEY_PATCH_KEY_NAME];
  7442. return typeof data === 'number' ? getLViewById(data) : data || null;
  7443. }
  7444. function readPatchedLView(target) {
  7445. const value = readPatchedData(target);
  7446. if (value) {
  7447. return (isLView(value) ? value : value.lView);
  7448. }
  7449. return null;
  7450. }
  7451. function isComponentInstance(instance) {
  7452. return instance && instance.constructor && instance.constructor.ɵcmp;
  7453. }
  7454. function isDirectiveInstance(instance) {
  7455. return instance && instance.constructor && instance.constructor.ɵdir;
  7456. }
  7457. /**
  7458. * Locates the element within the given LView and returns the matching index
  7459. */
  7460. function findViaNativeElement(lView, target) {
  7461. const tView = lView[TVIEW];
  7462. for (let i = HEADER_OFFSET; i < tView.bindingStartIndex; i++) {
  7463. if (unwrapRNode(lView[i]) === target) {
  7464. return i;
  7465. }
  7466. }
  7467. return -1;
  7468. }
  7469. /**
  7470. * Locates the next tNode (child, sibling or parent).
  7471. */
  7472. function traverseNextElement(tNode) {
  7473. if (tNode.child) {
  7474. return tNode.child;
  7475. }
  7476. else if (tNode.next) {
  7477. return tNode.next;
  7478. }
  7479. else {
  7480. // Let's take the following template: <div><span>text</span></div><component/>
  7481. // After checking the text node, we need to find the next parent that has a "next" TNode,
  7482. // in this case the parent `div`, so that we can find the component.
  7483. while (tNode.parent && !tNode.parent.next) {
  7484. tNode = tNode.parent;
  7485. }
  7486. return tNode.parent && tNode.parent.next;
  7487. }
  7488. }
  7489. /**
  7490. * Locates the component within the given LView and returns the matching index
  7491. */
  7492. function findViaComponent(lView, componentInstance) {
  7493. const componentIndices = lView[TVIEW].components;
  7494. if (componentIndices) {
  7495. for (let i = 0; i < componentIndices.length; i++) {
  7496. const elementComponentIndex = componentIndices[i];
  7497. const componentView = getComponentLViewByIndex(elementComponentIndex, lView);
  7498. if (componentView[CONTEXT] === componentInstance) {
  7499. return elementComponentIndex;
  7500. }
  7501. }
  7502. }
  7503. else {
  7504. const rootComponentView = getComponentLViewByIndex(HEADER_OFFSET, lView);
  7505. const rootComponent = rootComponentView[CONTEXT];
  7506. if (rootComponent === componentInstance) {
  7507. // we are dealing with the root element here therefore we know that the
  7508. // element is the very first element after the HEADER data in the lView
  7509. return HEADER_OFFSET;
  7510. }
  7511. }
  7512. return -1;
  7513. }
  7514. /**
  7515. * Locates the directive within the given LView and returns the matching index
  7516. */
  7517. function findViaDirective(lView, directiveInstance) {
  7518. // if a directive is monkey patched then it will (by default)
  7519. // have a reference to the LView of the current view. The
  7520. // element bound to the directive being search lives somewhere
  7521. // in the view data. We loop through the nodes and check their
  7522. // list of directives for the instance.
  7523. let tNode = lView[TVIEW].firstChild;
  7524. while (tNode) {
  7525. const directiveIndexStart = tNode.directiveStart;
  7526. const directiveIndexEnd = tNode.directiveEnd;
  7527. for (let i = directiveIndexStart; i < directiveIndexEnd; i++) {
  7528. if (lView[i] === directiveInstance) {
  7529. return tNode.index;
  7530. }
  7531. }
  7532. tNode = traverseNextElement(tNode);
  7533. }
  7534. return -1;
  7535. }
  7536. /**
  7537. * Returns a list of directives applied to a node at a specific index. The list includes
  7538. * directives matched by selector and any host directives, but it excludes components.
  7539. * Use `getComponentAtNodeIndex` to find the component applied to a node.
  7540. *
  7541. * @param nodeIndex The node index
  7542. * @param lView The target view data
  7543. */
  7544. function getDirectivesAtNodeIndex(nodeIndex, lView) {
  7545. const tNode = lView[TVIEW].data[nodeIndex];
  7546. if (tNode.directiveStart === 0)
  7547. return EMPTY_ARRAY;
  7548. const results = [];
  7549. for (let i = tNode.directiveStart; i < tNode.directiveEnd; i++) {
  7550. const directiveInstance = lView[i];
  7551. if (!isComponentInstance(directiveInstance)) {
  7552. results.push(directiveInstance);
  7553. }
  7554. }
  7555. return results;
  7556. }
  7557. function getComponentAtNodeIndex(nodeIndex, lView) {
  7558. const tNode = lView[TVIEW].data[nodeIndex];
  7559. return isComponentHost(tNode) ? lView[tNode.directiveStart + tNode.componentOffset] : null;
  7560. }
  7561. /**
  7562. * Returns a map of local references (local reference name => element or directive instance) that
  7563. * exist on a given element.
  7564. */
  7565. function discoverLocalRefs(lView, nodeIndex) {
  7566. const tNode = lView[TVIEW].data[nodeIndex];
  7567. if (tNode && tNode.localNames) {
  7568. const result = {};
  7569. let localIndex = tNode.index + 1;
  7570. for (let i = 0; i < tNode.localNames.length; i += 2) {
  7571. result[tNode.localNames[i]] = lView[localIndex];
  7572. localIndex++;
  7573. }
  7574. return result;
  7575. }
  7576. return null;
  7577. }
  7578. /**
  7579. * Retrieve the root view from any component or `LView` by walking the parent `LView` until
  7580. * reaching the root `LView`.
  7581. *
  7582. * @param componentOrLView any component or `LView`
  7583. */
  7584. function getRootView(componentOrLView) {
  7585. ngDevMode && assertDefined(componentOrLView, 'component');
  7586. let lView = isLView(componentOrLView) ? componentOrLView : readPatchedLView(componentOrLView);
  7587. while (lView && !isRootView(lView)) {
  7588. lView = getLViewParent(lView);
  7589. }
  7590. ngDevMode && assertLView(lView);
  7591. return lView;
  7592. }
  7593. /**
  7594. * Returns the context information associated with the application where the target is situated. It
  7595. * does this by walking the parent views until it gets to the root view, then getting the context
  7596. * off of that.
  7597. *
  7598. * @param viewOrComponent the `LView` or component to get the root context for.
  7599. */
  7600. function getRootContext(viewOrComponent) {
  7601. const rootView = getRootView(viewOrComponent);
  7602. ngDevMode &&
  7603. assertDefined(rootView[CONTEXT], 'Root view has no context. Perhaps it is disconnected?');
  7604. return rootView[CONTEXT];
  7605. }
  7606. /**
  7607. * Gets the first `LContainer` in the LView or `null` if none exists.
  7608. */
  7609. function getFirstLContainer(lView) {
  7610. return getNearestLContainer(lView[CHILD_HEAD]);
  7611. }
  7612. /**
  7613. * Gets the next `LContainer` that is a sibling of the given container.
  7614. */
  7615. function getNextLContainer(container) {
  7616. return getNearestLContainer(container[NEXT]);
  7617. }
  7618. function getNearestLContainer(viewOrContainer) {
  7619. while (viewOrContainer !== null && !isLContainer(viewOrContainer)) {
  7620. viewOrContainer = viewOrContainer[NEXT];
  7621. }
  7622. return viewOrContainer;
  7623. }
  7624. /**
  7625. * Retrieves the component instance associated with a given DOM element.
  7626. *
  7627. * @usageNotes
  7628. * Given the following DOM structure:
  7629. *
  7630. * ```html
  7631. * <app-root>
  7632. * <div>
  7633. * <child-comp></child-comp>
  7634. * </div>
  7635. * </app-root>
  7636. * ```
  7637. *
  7638. * Calling `getComponent` on `<child-comp>` will return the instance of `ChildComponent`
  7639. * associated with this DOM element.
  7640. *
  7641. * Calling the function on `<app-root>` will return the `MyApp` instance.
  7642. *
  7643. *
  7644. * @param element DOM element from which the component should be retrieved.
  7645. * @returns Component instance associated with the element or `null` if there
  7646. * is no component associated with it.
  7647. *
  7648. * @publicApi
  7649. */
  7650. function getComponent(element) {
  7651. ngDevMode && assertDomElement(element);
  7652. const context = getLContext(element);
  7653. if (context === null)
  7654. return null;
  7655. if (context.component === undefined) {
  7656. const lView = context.lView;
  7657. if (lView === null) {
  7658. return null;
  7659. }
  7660. context.component = getComponentAtNodeIndex(context.nodeIndex, lView);
  7661. }
  7662. return context.component;
  7663. }
  7664. /**
  7665. * If inside an embedded view (e.g. `*ngIf` or `*ngFor`), retrieves the context of the embedded
  7666. * view that the element is part of. Otherwise retrieves the instance of the component whose view
  7667. * owns the element (in this case, the result is the same as calling `getOwningComponent`).
  7668. *
  7669. * @param element Element for which to get the surrounding component instance.
  7670. * @returns Instance of the component that is around the element or null if the element isn't
  7671. * inside any component.
  7672. *
  7673. * @publicApi
  7674. */
  7675. function getContext(element) {
  7676. assertDomElement(element);
  7677. const context = getLContext(element);
  7678. const lView = context ? context.lView : null;
  7679. return lView === null ? null : lView[CONTEXT];
  7680. }
  7681. /**
  7682. * Retrieves the component instance whose view contains the DOM element.
  7683. *
  7684. * For example, if `<child-comp>` is used in the template of `<app-comp>`
  7685. * (i.e. a `ViewChild` of `<app-comp>`), calling `getOwningComponent` on `<child-comp>`
  7686. * would return `<app-comp>`.
  7687. *
  7688. * @param elementOrDir DOM element, component or directive instance
  7689. * for which to retrieve the root components.
  7690. * @returns Component instance whose view owns the DOM element or null if the element is not
  7691. * part of a component view.
  7692. *
  7693. * @publicApi
  7694. */
  7695. function getOwningComponent(elementOrDir) {
  7696. const context = getLContext(elementOrDir);
  7697. let lView = context ? context.lView : null;
  7698. if (lView === null)
  7699. return null;
  7700. let parent;
  7701. while (lView[TVIEW].type === 2 /* TViewType.Embedded */ && (parent = getLViewParent(lView))) {
  7702. lView = parent;
  7703. }
  7704. return isRootView(lView) ? null : lView[CONTEXT];
  7705. }
  7706. /**
  7707. * Retrieves all root components associated with a DOM element, directive or component instance.
  7708. * Root components are those which have been bootstrapped by Angular.
  7709. *
  7710. * @param elementOrDir DOM element, component or directive instance
  7711. * for which to retrieve the root components.
  7712. * @returns Root components associated with the target object.
  7713. *
  7714. * @publicApi
  7715. */
  7716. function getRootComponents(elementOrDir) {
  7717. const lView = readPatchedLView(elementOrDir);
  7718. return lView !== null ? [getRootContext(lView)] : [];
  7719. }
  7720. /**
  7721. * Retrieves an `Injector` associated with an element, component or directive instance.
  7722. *
  7723. * @param elementOrDir DOM element, component or directive instance for which to
  7724. * retrieve the injector.
  7725. * @returns Injector associated with the element, component or directive instance.
  7726. *
  7727. * @publicApi
  7728. */
  7729. function getInjector(elementOrDir) {
  7730. const context = getLContext(elementOrDir);
  7731. const lView = context ? context.lView : null;
  7732. if (lView === null)
  7733. return Injector.NULL;
  7734. const tNode = lView[TVIEW].data[context.nodeIndex];
  7735. return new NodeInjector(tNode, lView);
  7736. }
  7737. /**
  7738. * Retrieve a set of injection tokens at a given DOM node.
  7739. *
  7740. * @param element Element for which the injection tokens should be retrieved.
  7741. */
  7742. function getInjectionTokens(element) {
  7743. const context = getLContext(element);
  7744. const lView = context ? context.lView : null;
  7745. if (lView === null)
  7746. return [];
  7747. const tView = lView[TVIEW];
  7748. const tNode = tView.data[context.nodeIndex];
  7749. const providerTokens = [];
  7750. const startIndex = tNode.providerIndexes & 1048575 /* TNodeProviderIndexes.ProvidersStartIndexMask */;
  7751. const endIndex = tNode.directiveEnd;
  7752. for (let i = startIndex; i < endIndex; i++) {
  7753. let value = tView.data[i];
  7754. if (isDirectiveDefHack(value)) {
  7755. // The fact that we sometimes store Type and sometimes DirectiveDef in this location is a
  7756. // design flaw. We should always store same type so that we can be monomorphic. The issue
  7757. // is that for Components/Directives we store the def instead the type. The correct behavior
  7758. // is that we should always be storing injectable type in this location.
  7759. value = value.type;
  7760. }
  7761. providerTokens.push(value);
  7762. }
  7763. return providerTokens;
  7764. }
  7765. /**
  7766. * Retrieves directive instances associated with a given DOM node. Does not include
  7767. * component instances.
  7768. *
  7769. * @usageNotes
  7770. * Given the following DOM structure:
  7771. *
  7772. * ```html
  7773. * <app-root>
  7774. * <button my-button></button>
  7775. * <my-comp></my-comp>
  7776. * </app-root>
  7777. * ```
  7778. *
  7779. * Calling `getDirectives` on `<button>` will return an array with an instance of the `MyButton`
  7780. * directive that is associated with the DOM node.
  7781. *
  7782. * Calling `getDirectives` on `<my-comp>` will return an empty array.
  7783. *
  7784. * @param node DOM node for which to get the directives.
  7785. * @returns Array of directives associated with the node.
  7786. *
  7787. * @publicApi
  7788. */
  7789. function getDirectives(node) {
  7790. // Skip text nodes because we can't have directives associated with them.
  7791. if (node instanceof Text) {
  7792. return [];
  7793. }
  7794. const context = getLContext(node);
  7795. const lView = context ? context.lView : null;
  7796. if (lView === null) {
  7797. return [];
  7798. }
  7799. const tView = lView[TVIEW];
  7800. const nodeIndex = context.nodeIndex;
  7801. if (!tView?.data[nodeIndex]) {
  7802. return [];
  7803. }
  7804. if (context.directives === undefined) {
  7805. context.directives = getDirectivesAtNodeIndex(nodeIndex, lView);
  7806. }
  7807. // The `directives` in this case are a named array called `LComponentView`. Clone the
  7808. // result so we don't expose an internal data structure in the user's console.
  7809. return context.directives === null ? [] : [...context.directives];
  7810. }
  7811. /**
  7812. * Returns the debug (partial) metadata for a particular directive or component instance.
  7813. * The function accepts an instance of a directive or component and returns the corresponding
  7814. * metadata.
  7815. *
  7816. * @param directiveOrComponentInstance Instance of a directive or component
  7817. * @returns metadata of the passed directive or component
  7818. *
  7819. * @publicApi
  7820. */
  7821. function getDirectiveMetadata$1(directiveOrComponentInstance) {
  7822. const { constructor } = directiveOrComponentInstance;
  7823. if (!constructor) {
  7824. throw new Error('Unable to find the instance constructor');
  7825. }
  7826. // In case a component inherits from a directive, we may have component and directive metadata
  7827. // To ensure we don't get the metadata of the directive, we want to call `getComponentDef` first.
  7828. const componentDef = getComponentDef(constructor);
  7829. if (componentDef) {
  7830. const inputs = extractInputDebugMetadata(componentDef.inputs);
  7831. return {
  7832. inputs,
  7833. outputs: componentDef.outputs,
  7834. encapsulation: componentDef.encapsulation,
  7835. changeDetection: componentDef.onPush
  7836. ? ChangeDetectionStrategy.OnPush
  7837. : ChangeDetectionStrategy.Default,
  7838. };
  7839. }
  7840. const directiveDef = getDirectiveDef(constructor);
  7841. if (directiveDef) {
  7842. const inputs = extractInputDebugMetadata(directiveDef.inputs);
  7843. return { inputs, outputs: directiveDef.outputs };
  7844. }
  7845. return null;
  7846. }
  7847. /**
  7848. * Retrieve map of local references.
  7849. *
  7850. * The references are retrieved as a map of local reference name to element or directive instance.
  7851. *
  7852. * @param target DOM element, component or directive instance for which to retrieve
  7853. * the local references.
  7854. */
  7855. function getLocalRefs(target) {
  7856. const context = getLContext(target);
  7857. if (context === null)
  7858. return {};
  7859. if (context.localRefs === undefined) {
  7860. const lView = context.lView;
  7861. if (lView === null) {
  7862. return {};
  7863. }
  7864. context.localRefs = discoverLocalRefs(lView, context.nodeIndex);
  7865. }
  7866. return context.localRefs || {};
  7867. }
  7868. /**
  7869. * Retrieves the host element of a component or directive instance.
  7870. * The host element is the DOM element that matched the selector of the directive.
  7871. *
  7872. * @param componentOrDirective Component or directive instance for which the host
  7873. * element should be retrieved.
  7874. * @returns Host element of the target.
  7875. *
  7876. * @publicApi
  7877. */
  7878. function getHostElement(componentOrDirective) {
  7879. return getLContext(componentOrDirective).native;
  7880. }
  7881. /**
  7882. * Retrieves a list of event listeners associated with a DOM element. The list does include host
  7883. * listeners, but it does not include event listeners defined outside of the Angular context
  7884. * (e.g. through `addEventListener`).
  7885. *
  7886. * @usageNotes
  7887. * Given the following DOM structure:
  7888. *
  7889. * ```html
  7890. * <app-root>
  7891. * <div (click)="doSomething()"></div>
  7892. * </app-root>
  7893. * ```
  7894. *
  7895. * Calling `getListeners` on `<div>` will return an object that looks as follows:
  7896. *
  7897. * ```ts
  7898. * {
  7899. * name: 'click',
  7900. * element: <div>,
  7901. * callback: () => doSomething(),
  7902. * useCapture: false
  7903. * }
  7904. * ```
  7905. *
  7906. * @param element Element for which the DOM listeners should be retrieved.
  7907. * @returns Array of event listeners on the DOM element.
  7908. *
  7909. * @publicApi
  7910. */
  7911. function getListeners(element) {
  7912. ngDevMode && assertDomElement(element);
  7913. const lContext = getLContext(element);
  7914. const lView = lContext === null ? null : lContext.lView;
  7915. if (lView === null)
  7916. return [];
  7917. const tView = lView[TVIEW];
  7918. const lCleanup = lView[CLEANUP];
  7919. const tCleanup = tView.cleanup;
  7920. const listeners = [];
  7921. if (tCleanup && lCleanup) {
  7922. for (let i = 0; i < tCleanup.length;) {
  7923. const firstParam = tCleanup[i++];
  7924. const secondParam = tCleanup[i++];
  7925. if (typeof firstParam === 'string') {
  7926. const name = firstParam;
  7927. const listenerElement = unwrapRNode(lView[secondParam]);
  7928. const callback = lCleanup[tCleanup[i++]];
  7929. const useCaptureOrIndx = tCleanup[i++];
  7930. // if useCaptureOrIndx is boolean then report it as is.
  7931. // if useCaptureOrIndx is positive number then it in unsubscribe method
  7932. // if useCaptureOrIndx is negative number then it is a Subscription
  7933. const type = typeof useCaptureOrIndx === 'boolean' || useCaptureOrIndx >= 0 ? 'dom' : 'output';
  7934. const useCapture = typeof useCaptureOrIndx === 'boolean' ? useCaptureOrIndx : false;
  7935. if (element == listenerElement) {
  7936. listeners.push({ element, name, callback, useCapture, type });
  7937. }
  7938. }
  7939. }
  7940. }
  7941. listeners.sort(sortListeners);
  7942. return listeners;
  7943. }
  7944. function sortListeners(a, b) {
  7945. if (a.name == b.name)
  7946. return 0;
  7947. return a.name < b.name ? -1 : 1;
  7948. }
  7949. /**
  7950. * This function should not exist because it is megamorphic and only mostly correct.
  7951. *
  7952. * See call site for more info.
  7953. */
  7954. function isDirectiveDefHack(obj) {
  7955. return (obj.type !== undefined &&
  7956. obj.declaredInputs !== undefined &&
  7957. obj.findHostDirectiveDefs !== undefined);
  7958. }
  7959. /** Asserts that a value is a DOM Element. */
  7960. function assertDomElement(value) {
  7961. if (typeof Element !== 'undefined' && !(value instanceof Element)) {
  7962. throw new Error('Expecting instance of DOM Element');
  7963. }
  7964. }
  7965. /**
  7966. * A directive definition holds additional metadata using bitwise flags to indicate
  7967. * for example whether it is signal based.
  7968. *
  7969. * This information needs to be separate from the `publicName -> minifiedName`
  7970. * mappings for backwards compatibility.
  7971. */
  7972. function extractInputDebugMetadata(inputs) {
  7973. const res = {};
  7974. for (const key in inputs) {
  7975. if (inputs.hasOwnProperty(key)) {
  7976. const value = inputs[key];
  7977. if (value !== undefined) {
  7978. res[key] = value[0];
  7979. }
  7980. }
  7981. }
  7982. return res;
  7983. }
  7984. /**
  7985. * Most of the use of `document` in Angular is from within the DI system so it is possible to simply
  7986. * inject the `DOCUMENT` token and are done.
  7987. *
  7988. * Ivy is special because it does not rely upon the DI and must get hold of the document some other
  7989. * way.
  7990. *
  7991. * The solution is to define `getDocument()` and `setDocument()` top-level functions for ivy.
  7992. * Wherever ivy needs the global document, it calls `getDocument()` instead.
  7993. *
  7994. * When running ivy outside of a browser environment, it is necessary to call `setDocument()` to
  7995. * tell ivy what the global `document` is.
  7996. *
  7997. * Angular does this for us in each of the standard platforms (`Browser` and `Server`)
  7998. * by calling `setDocument()` when providing the `DOCUMENT` token.
  7999. */
  8000. let DOCUMENT = undefined;
  8001. /**
  8002. * Tell ivy what the `document` is for this platform.
  8003. *
  8004. * It is only necessary to call this if the current platform is not a browser.
  8005. *
  8006. * @param document The object representing the global `document` in this environment.
  8007. */
  8008. function setDocument(document) {
  8009. DOCUMENT = document;
  8010. }
  8011. /**
  8012. * Access the object that represents the `document` for this platform.
  8013. *
  8014. * Ivy calls this whenever it needs to access the `document` object.
  8015. * For example to create the renderer or to do sanitization.
  8016. */
  8017. function getDocument() {
  8018. if (DOCUMENT !== undefined) {
  8019. return DOCUMENT;
  8020. }
  8021. else if (typeof document !== 'undefined') {
  8022. return document;
  8023. }
  8024. throw new RuntimeError(210 /* RuntimeErrorCode.MISSING_DOCUMENT */, (typeof ngDevMode === 'undefined' || ngDevMode) &&
  8025. `The document object is not available in this context. Make sure the DOCUMENT injection token is provided.`);
  8026. // No "document" can be found. This should only happen if we are running ivy outside Angular and
  8027. // the current platform is not a browser. Since this is not a supported scenario at the moment
  8028. // this should not happen in Angular apps.
  8029. // Once we support running ivy outside of Angular we will need to publish `setDocument()` as a
  8030. // public API.
  8031. }
  8032. /**
  8033. * A DI token representing a string ID, used
  8034. * primarily for prefixing application attributes and CSS styles when
  8035. * {@link ViewEncapsulation#Emulated} is being used.
  8036. *
  8037. * The token is needed in cases when multiple applications are bootstrapped on a page
  8038. * (for example, using `bootstrapApplication` calls). In this case, ensure that those applications
  8039. * have different `APP_ID` value setup. For example:
  8040. *
  8041. * ```ts
  8042. * bootstrapApplication(ComponentA, {
  8043. * providers: [
  8044. * { provide: APP_ID, useValue: 'app-a' },
  8045. * // ... other providers ...
  8046. * ]
  8047. * });
  8048. *
  8049. * bootstrapApplication(ComponentB, {
  8050. * providers: [
  8051. * { provide: APP_ID, useValue: 'app-b' },
  8052. * // ... other providers ...
  8053. * ]
  8054. * });
  8055. * ```
  8056. *
  8057. * By default, when there is only one application bootstrapped, you don't need to provide the
  8058. * `APP_ID` token (the `ng` will be used as an app ID).
  8059. *
  8060. * @publicApi
  8061. */
  8062. const APP_ID = new InjectionToken(ngDevMode ? 'AppId' : '', {
  8063. providedIn: 'root',
  8064. factory: () => DEFAULT_APP_ID,
  8065. });
  8066. /** Default value of the `APP_ID` token. */
  8067. const DEFAULT_APP_ID = 'ng';
  8068. /**
  8069. * A function that is executed when a platform is initialized.
  8070. *
  8071. * @deprecated from v19.0.0, use providePlatformInitializer instead
  8072. *
  8073. * @see {@link providePlatformInitializer}
  8074. *
  8075. * @publicApi
  8076. */
  8077. const PLATFORM_INITIALIZER = new InjectionToken(ngDevMode ? 'Platform Initializer' : '');
  8078. /**
  8079. * A token that indicates an opaque platform ID.
  8080. * @publicApi
  8081. */
  8082. const PLATFORM_ID = new InjectionToken(ngDevMode ? 'Platform ID' : '', {
  8083. providedIn: 'platform',
  8084. factory: () => 'unknown', // set a default platform name, when none set explicitly
  8085. });
  8086. /**
  8087. * A DI token that indicates the root directory of
  8088. * the application
  8089. * @publicApi
  8090. * @deprecated
  8091. */
  8092. const PACKAGE_ROOT_URL = new InjectionToken(ngDevMode ? 'Application Packages Root URL' : '');
  8093. // We keep this token here, rather than the animations package, so that modules that only care
  8094. // about which animations module is loaded (e.g. the CDK) can retrieve it without having to
  8095. // include extra dependencies. See #44970 for more context.
  8096. /**
  8097. * A [DI token](api/core/InjectionToken) that indicates which animations
  8098. * module has been loaded.
  8099. * @publicApi
  8100. */
  8101. const ANIMATION_MODULE_TYPE = new InjectionToken(ngDevMode ? 'AnimationModuleType' : '');
  8102. // TODO(crisbeto): link to CSP guide here.
  8103. /**
  8104. * Token used to configure the [Content Security Policy](https://web.dev/strict-csp/) nonce that
  8105. * Angular will apply when inserting inline styles. If not provided, Angular will look up its value
  8106. * from the `ngCspNonce` attribute of the application root node.
  8107. *
  8108. * @publicApi
  8109. */
  8110. const CSP_NONCE = new InjectionToken(ngDevMode ? 'CSP nonce' : '', {
  8111. providedIn: 'root',
  8112. factory: () => {
  8113. // Ideally we wouldn't have to use `querySelector` here since we know that the nonce will be on
  8114. // the root node, but because the token value is used in renderers, it has to be available
  8115. // *very* early in the bootstrapping process. This should be a fairly shallow search, because
  8116. // the app won't have been added to the DOM yet. Some approaches that were considered:
  8117. // 1. Find the root node through `ApplicationRef.components[i].location` - normally this would
  8118. // be enough for our purposes, but the token is injected very early so the `components` array
  8119. // isn't populated yet.
  8120. // 2. Find the root `LView` through the current `LView` - renderers are a prerequisite to
  8121. // creating the `LView`. This means that no `LView` will have been entered when this factory is
  8122. // invoked for the root component.
  8123. // 3. Have the token factory return `() => string` which is invoked when a nonce is requested -
  8124. // the slightly later execution does allow us to get an `LView` reference, but the fact that
  8125. // it is a function means that it could be executed at *any* time (including immediately) which
  8126. // may lead to weird bugs.
  8127. // 4. Have the `ComponentFactory` read the attribute and provide it to the injector under the
  8128. // hood - has the same problem as #1 and #2 in that the renderer is used to query for the root
  8129. // node and the nonce value needs to be available when the renderer is created.
  8130. return getDocument().body?.querySelector('[ngCspNonce]')?.getAttribute('ngCspNonce') || null;
  8131. },
  8132. });
  8133. const IMAGE_CONFIG_DEFAULTS = {
  8134. breakpoints: [16, 32, 48, 64, 96, 128, 256, 384, 640, 750, 828, 1080, 1200, 1920, 2048, 3840],
  8135. placeholderResolution: 30,
  8136. disableImageSizeWarning: false,
  8137. disableImageLazyLoadWarning: false,
  8138. };
  8139. /**
  8140. * Injection token that configures the image optimized image functionality.
  8141. * See {@link ImageConfig} for additional information about parameters that
  8142. * can be used.
  8143. *
  8144. * @see {@link NgOptimizedImage}
  8145. * @see {@link ImageConfig}
  8146. * @publicApi
  8147. */
  8148. const IMAGE_CONFIG = new InjectionToken(ngDevMode ? 'ImageConfig' : '', {
  8149. providedIn: 'root',
  8150. factory: () => IMAGE_CONFIG_DEFAULTS,
  8151. });
  8152. /**
  8153. * Create a `StateKey<T>` that can be used to store value of type T with `TransferState`.
  8154. *
  8155. * Example:
  8156. *
  8157. * ```ts
  8158. * const COUNTER_KEY = makeStateKey<number>('counter');
  8159. * let value = 10;
  8160. *
  8161. * transferState.set(COUNTER_KEY, value);
  8162. * ```
  8163. *
  8164. * @publicApi
  8165. */
  8166. function makeStateKey(key) {
  8167. return key;
  8168. }
  8169. function initTransferState() {
  8170. const transferState = new TransferState();
  8171. if (typeof ngServerMode === 'undefined' || !ngServerMode) {
  8172. transferState.store = retrieveTransferredState(getDocument(), inject(APP_ID));
  8173. }
  8174. return transferState;
  8175. }
  8176. /**
  8177. * A key value store that is transferred from the application on the server side to the application
  8178. * on the client side.
  8179. *
  8180. * The `TransferState` is available as an injectable token.
  8181. * On the client, just inject this token using DI and use it, it will be lazily initialized.
  8182. * On the server it's already included if `renderApplication` function is used. Otherwise, import
  8183. * the `ServerTransferStateModule` module to make the `TransferState` available.
  8184. *
  8185. * The values in the store are serialized/deserialized using JSON.stringify/JSON.parse. So only
  8186. * boolean, number, string, null and non-class objects will be serialized and deserialized in a
  8187. * non-lossy manner.
  8188. *
  8189. * @publicApi
  8190. */
  8191. class TransferState {
  8192. /** @nocollapse */
  8193. static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
  8194. token: TransferState,
  8195. providedIn: 'root',
  8196. factory: initTransferState,
  8197. });
  8198. /** @internal */
  8199. store = {};
  8200. onSerializeCallbacks = {};
  8201. /**
  8202. * Get the value corresponding to a key. Return `defaultValue` if key is not found.
  8203. */
  8204. get(key, defaultValue) {
  8205. return this.store[key] !== undefined ? this.store[key] : defaultValue;
  8206. }
  8207. /**
  8208. * Set the value corresponding to a key.
  8209. */
  8210. set(key, value) {
  8211. this.store[key] = value;
  8212. }
  8213. /**
  8214. * Remove a key from the store.
  8215. */
  8216. remove(key) {
  8217. delete this.store[key];
  8218. }
  8219. /**
  8220. * Test whether a key exists in the store.
  8221. */
  8222. hasKey(key) {
  8223. return this.store.hasOwnProperty(key);
  8224. }
  8225. /**
  8226. * Indicates whether the state is empty.
  8227. */
  8228. get isEmpty() {
  8229. return Object.keys(this.store).length === 0;
  8230. }
  8231. /**
  8232. * Register a callback to provide the value for a key when `toJson` is called.
  8233. */
  8234. onSerialize(key, callback) {
  8235. this.onSerializeCallbacks[key] = callback;
  8236. }
  8237. /**
  8238. * Serialize the current state of the store to JSON.
  8239. */
  8240. toJson() {
  8241. // Call the onSerialize callbacks and put those values into the store.
  8242. for (const key in this.onSerializeCallbacks) {
  8243. if (this.onSerializeCallbacks.hasOwnProperty(key)) {
  8244. try {
  8245. this.store[key] = this.onSerializeCallbacks[key]();
  8246. }
  8247. catch (e) {
  8248. console.warn('Exception in onSerialize callback: ', e);
  8249. }
  8250. }
  8251. }
  8252. // Escape script tag to avoid break out of <script> tag in serialized output.
  8253. // Encoding of `<` is the same behaviour as G3 script_builders.
  8254. return JSON.stringify(this.store).replace(/</g, '\\u003C');
  8255. }
  8256. }
  8257. function retrieveTransferredState(doc, appId) {
  8258. // Locate the script tag with the JSON data transferred from the server.
  8259. // The id of the script tag is set to the Angular appId + 'state'.
  8260. const script = doc.getElementById(appId + '-state');
  8261. if (script?.textContent) {
  8262. try {
  8263. // Avoid using any here as it triggers lint errors in google3 (any is not allowed).
  8264. // Decoding of `<` is done of the box by browsers and node.js, same behaviour as G3
  8265. // script_builders.
  8266. return JSON.parse(script.textContent);
  8267. }
  8268. catch (e) {
  8269. console.warn('Exception while restoring TransferState for app ' + appId, e);
  8270. }
  8271. }
  8272. return {};
  8273. }
  8274. /** Encodes that the node lookup should start from the host node of this component. */
  8275. const REFERENCE_NODE_HOST = 'h';
  8276. /** Encodes that the node lookup should start from the document body node. */
  8277. const REFERENCE_NODE_BODY = 'b';
  8278. const NODE_NAVIGATION_STEP_FIRST_CHILD = 'f';
  8279. const NODE_NAVIGATION_STEP_NEXT_SIBLING = 'n';
  8280. /**
  8281. * Keys within serialized view data structure to represent various
  8282. * parts. See the `SerializedView` interface below for additional information.
  8283. */
  8284. const ELEMENT_CONTAINERS = 'e';
  8285. const TEMPLATES = 't';
  8286. const CONTAINERS = 'c';
  8287. const MULTIPLIER = 'x';
  8288. const NUM_ROOT_NODES = 'r';
  8289. const TEMPLATE_ID = 'i'; // as it's also an "id"
  8290. const NODES = 'n';
  8291. const DISCONNECTED_NODES = 'd';
  8292. const I18N_DATA = 'l';
  8293. const DEFER_BLOCK_ID = 'di';
  8294. const DEFER_BLOCK_STATE$1 = 's';
  8295. const DEFER_PARENT_BLOCK_ID = 'p';
  8296. const DEFER_HYDRATE_TRIGGERS = 't';
  8297. /**
  8298. * Internal token that specifies whether DOM reuse logic
  8299. * during hydration is enabled.
  8300. */
  8301. const IS_HYDRATION_DOM_REUSE_ENABLED = new InjectionToken(typeof ngDevMode === 'undefined' || !!ngDevMode ? 'IS_HYDRATION_DOM_REUSE_ENABLED' : '');
  8302. // By default (in client rendering mode), we remove all the contents
  8303. // of the host element and render an application after that.
  8304. const PRESERVE_HOST_CONTENT_DEFAULT = false;
  8305. /**
  8306. * Internal token that indicates whether host element content should be
  8307. * retained during the bootstrap.
  8308. */
  8309. const PRESERVE_HOST_CONTENT = new InjectionToken(typeof ngDevMode === 'undefined' || !!ngDevMode ? 'PRESERVE_HOST_CONTENT' : '', {
  8310. providedIn: 'root',
  8311. factory: () => PRESERVE_HOST_CONTENT_DEFAULT,
  8312. });
  8313. /**
  8314. * Internal token that indicates whether hydration support for i18n
  8315. * is enabled.
  8316. */
  8317. const IS_I18N_HYDRATION_ENABLED = new InjectionToken(typeof ngDevMode === 'undefined' || !!ngDevMode ? 'IS_I18N_HYDRATION_ENABLED' : '');
  8318. /**
  8319. * Internal token that indicates whether event replay support for SSR
  8320. * is enabled.
  8321. */
  8322. const IS_EVENT_REPLAY_ENABLED = new InjectionToken(typeof ngDevMode === 'undefined' || !!ngDevMode ? 'IS_EVENT_REPLAY_ENABLED' : '');
  8323. const EVENT_REPLAY_ENABLED_DEFAULT = false;
  8324. /**
  8325. * Internal token that indicates whether incremental hydration support
  8326. * is enabled.
  8327. */
  8328. const IS_INCREMENTAL_HYDRATION_ENABLED = new InjectionToken(typeof ngDevMode === 'undefined' || !!ngDevMode ? 'IS_INCREMENTAL_HYDRATION_ENABLED' : '');
  8329. /**
  8330. * A map of DOM elements with `jsaction` attributes grouped by action names.
  8331. */
  8332. const JSACTION_BLOCK_ELEMENT_MAP = new InjectionToken(ngDevMode ? 'JSACTION_BLOCK_ELEMENT_MAP' : '', {
  8333. providedIn: 'root',
  8334. factory: () => new Map(),
  8335. });
  8336. /** Actions that are supported by the tracing framework. */
  8337. var TracingAction;
  8338. (function (TracingAction) {
  8339. TracingAction[TracingAction["CHANGE_DETECTION"] = 0] = "CHANGE_DETECTION";
  8340. TracingAction[TracingAction["AFTER_NEXT_RENDER"] = 1] = "AFTER_NEXT_RENDER";
  8341. })(TracingAction || (TracingAction = {}));
  8342. /**
  8343. * Injection token for a `TracingService`, optionally provided.
  8344. */
  8345. const TracingService = new InjectionToken(ngDevMode ? 'TracingService' : '');
  8346. const markedFeatures = new Set();
  8347. // tslint:disable:ban
  8348. /**
  8349. * A guarded `performance.mark` for feature marking.
  8350. *
  8351. * This method exists because while all supported browser and node.js version supported by Angular
  8352. * support performance.mark API. This is not the case for other environments such as JSDOM and
  8353. * Cloudflare workers.
  8354. */
  8355. function performanceMarkFeature(feature) {
  8356. if (markedFeatures.has(feature)) {
  8357. return;
  8358. }
  8359. markedFeatures.add(feature);
  8360. performance?.mark?.('mark_feature_usage', { detail: { feature } });
  8361. }
  8362. /**
  8363. * Asserts that the current stack frame is not within a reactive context. Useful
  8364. * to disallow certain code from running inside a reactive context (see {@link /api/core/rxjs/toSignal toSignal})
  8365. *
  8366. * @param debugFn a reference to the function making the assertion (used for the error message).
  8367. *
  8368. * @publicApi
  8369. */
  8370. function assertNotInReactiveContext(debugFn, extraContext) {
  8371. // Taking a `Function` instead of a string name here prevents the un-minified name of the function
  8372. // from being retained in the bundle regardless of minification.
  8373. if (getActiveConsumer() !== null) {
  8374. throw new RuntimeError(-602 /* RuntimeErrorCode.ASSERTION_NOT_INSIDE_REACTIVE_CONTEXT */, ngDevMode &&
  8375. `${debugFn.name}() cannot be called from within a reactive context.${extraContext ? ` ${extraContext}` : ''}`);
  8376. }
  8377. }
  8378. class ViewContext {
  8379. view;
  8380. node;
  8381. constructor(view, node) {
  8382. this.view = view;
  8383. this.node = node;
  8384. }
  8385. /**
  8386. * @internal
  8387. * @nocollapse
  8388. */
  8389. static __NG_ELEMENT_ID__ = injectViewContext;
  8390. }
  8391. function injectViewContext() {
  8392. return new ViewContext(getLView(), getCurrentTNode());
  8393. }
  8394. /**
  8395. * The phase to run an `afterRender` or `afterNextRender` callback in.
  8396. *
  8397. * Callbacks in the same phase run in the order they are registered. Phases run in the
  8398. * following order after each render:
  8399. *
  8400. * 1. `AfterRenderPhase.EarlyRead`
  8401. * 2. `AfterRenderPhase.Write`
  8402. * 3. `AfterRenderPhase.MixedReadWrite`
  8403. * 4. `AfterRenderPhase.Read`
  8404. *
  8405. * Angular is unable to verify or enforce that phases are used correctly, and instead
  8406. * relies on each developer to follow the guidelines documented for each value and
  8407. * carefully choose the appropriate one, refactoring their code if necessary. By doing
  8408. * so, Angular is better able to minimize the performance degradation associated with
  8409. * manual DOM access, ensuring the best experience for the end users of your application
  8410. * or library.
  8411. *
  8412. * @deprecated Specify the phase for your callback to run in by passing a spec-object as the first
  8413. * parameter to `afterRender` or `afterNextRender` instead of a function.
  8414. */
  8415. var AfterRenderPhase;
  8416. (function (AfterRenderPhase) {
  8417. /**
  8418. * Use `AfterRenderPhase.EarlyRead` for callbacks that only need to **read** from the
  8419. * DOM before a subsequent `AfterRenderPhase.Write` callback, for example to perform
  8420. * custom layout that the browser doesn't natively support. Prefer the
  8421. * `AfterRenderPhase.EarlyRead` phase if reading can wait until after the write phase.
  8422. * **Never** write to the DOM in this phase.
  8423. *
  8424. * <div class="docs-alert docs-alert-important">
  8425. *
  8426. * Using this value can degrade performance.
  8427. * Instead, prefer using built-in browser functionality when possible.
  8428. *
  8429. * </div>
  8430. */
  8431. AfterRenderPhase[AfterRenderPhase["EarlyRead"] = 0] = "EarlyRead";
  8432. /**
  8433. * Use `AfterRenderPhase.Write` for callbacks that only **write** to the DOM. **Never**
  8434. * read from the DOM in this phase.
  8435. */
  8436. AfterRenderPhase[AfterRenderPhase["Write"] = 1] = "Write";
  8437. /**
  8438. * Use `AfterRenderPhase.MixedReadWrite` for callbacks that read from or write to the
  8439. * DOM, that haven't been refactored to use a different phase. **Never** use this phase if
  8440. * it is possible to divide the work among the other phases instead.
  8441. *
  8442. * <div class="docs-alert docs-alert-critical">
  8443. *
  8444. * Using this value can **significantly** degrade performance.
  8445. * Instead, prefer dividing work into the appropriate phase callbacks.
  8446. *
  8447. * </div>
  8448. */
  8449. AfterRenderPhase[AfterRenderPhase["MixedReadWrite"] = 2] = "MixedReadWrite";
  8450. /**
  8451. * Use `AfterRenderPhase.Read` for callbacks that only **read** from the DOM. **Never**
  8452. * write to the DOM in this phase.
  8453. */
  8454. AfterRenderPhase[AfterRenderPhase["Read"] = 3] = "Read";
  8455. })(AfterRenderPhase || (AfterRenderPhase = {}));
  8456. class AfterRenderManager {
  8457. impl = null;
  8458. execute() {
  8459. this.impl?.execute();
  8460. }
  8461. /** @nocollapse */
  8462. static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
  8463. token: AfterRenderManager,
  8464. providedIn: 'root',
  8465. factory: () => new AfterRenderManager(),
  8466. });
  8467. }
  8468. const AFTER_RENDER_PHASES = /* @__PURE__ **/ (() => [
  8469. AfterRenderPhase.EarlyRead,
  8470. AfterRenderPhase.Write,
  8471. AfterRenderPhase.MixedReadWrite,
  8472. AfterRenderPhase.Read,
  8473. ])();
  8474. class AfterRenderImpl {
  8475. ngZone = inject(NgZone);
  8476. scheduler = inject(ChangeDetectionScheduler);
  8477. errorHandler = inject(ErrorHandler, { optional: true });
  8478. /** Current set of active sequences. */
  8479. sequences = new Set();
  8480. /** Tracks registrations made during the current set of executions. */
  8481. deferredRegistrations = new Set();
  8482. /** Whether the `AfterRenderManager` is currently executing hooks. */
  8483. executing = false;
  8484. constructor() {
  8485. // Inject the tracing service to make sure it's initialized.
  8486. inject(TracingService, { optional: true });
  8487. }
  8488. /**
  8489. * Run the sequence of phases of hooks, once through. As a result of executing some hooks, more
  8490. * might be scheduled.
  8491. */
  8492. execute() {
  8493. const hasSequencesToExecute = this.sequences.size > 0;
  8494. if (hasSequencesToExecute) {
  8495. profiler(16 /* ProfilerEvent.AfterRenderHooksStart */);
  8496. }
  8497. this.executing = true;
  8498. for (const phase of AFTER_RENDER_PHASES) {
  8499. for (const sequence of this.sequences) {
  8500. if (sequence.erroredOrDestroyed || !sequence.hooks[phase]) {
  8501. continue;
  8502. }
  8503. try {
  8504. sequence.pipelinedValue = this.ngZone.runOutsideAngular(() => this.maybeTrace(() => {
  8505. const hookFn = sequence.hooks[phase];
  8506. const value = hookFn(sequence.pipelinedValue);
  8507. return value;
  8508. }, sequence.snapshot));
  8509. }
  8510. catch (err) {
  8511. sequence.erroredOrDestroyed = true;
  8512. this.errorHandler?.handleError(err);
  8513. }
  8514. }
  8515. }
  8516. this.executing = false;
  8517. // Cleanup step to reset sequence state and also collect one-shot sequences for removal.
  8518. for (const sequence of this.sequences) {
  8519. sequence.afterRun();
  8520. if (sequence.once) {
  8521. this.sequences.delete(sequence);
  8522. // Destroy the sequence so its on destroy callbacks can be cleaned up
  8523. // immediately, instead of waiting until the injector is destroyed.
  8524. sequence.destroy();
  8525. }
  8526. }
  8527. for (const sequence of this.deferredRegistrations) {
  8528. this.sequences.add(sequence);
  8529. }
  8530. if (this.deferredRegistrations.size > 0) {
  8531. this.scheduler.notify(7 /* NotificationSource.RenderHook */);
  8532. }
  8533. this.deferredRegistrations.clear();
  8534. if (hasSequencesToExecute) {
  8535. profiler(17 /* ProfilerEvent.AfterRenderHooksEnd */);
  8536. }
  8537. }
  8538. register(sequence) {
  8539. const { view } = sequence;
  8540. if (view !== undefined) {
  8541. // Delay adding it to the manager, add it to the view instead.
  8542. (view[AFTER_RENDER_SEQUENCES_TO_ADD] ??= []).push(sequence);
  8543. // Mark the view for traversal to ensure we eventually schedule the afterNextRender.
  8544. markAncestorsForTraversal(view);
  8545. view[FLAGS] |= 8192 /* LViewFlags.HasChildViewsToRefresh */;
  8546. }
  8547. else if (!this.executing) {
  8548. this.addSequence(sequence);
  8549. }
  8550. else {
  8551. this.deferredRegistrations.add(sequence);
  8552. }
  8553. }
  8554. addSequence(sequence) {
  8555. this.sequences.add(sequence);
  8556. // Trigger an `ApplicationRef.tick()` if one is not already pending/running, because we have a
  8557. // new render hook that needs to run.
  8558. this.scheduler.notify(7 /* NotificationSource.RenderHook */);
  8559. }
  8560. unregister(sequence) {
  8561. if (this.executing && this.sequences.has(sequence)) {
  8562. // We can't remove an `AfterRenderSequence` in the middle of iteration.
  8563. // Instead, mark it as destroyed so it doesn't run any more, and mark it as one-shot so it'll
  8564. // be removed at the end of the current execution.
  8565. sequence.erroredOrDestroyed = true;
  8566. sequence.pipelinedValue = undefined;
  8567. sequence.once = true;
  8568. }
  8569. else {
  8570. // It's safe to directly remove this sequence.
  8571. this.sequences.delete(sequence);
  8572. this.deferredRegistrations.delete(sequence);
  8573. }
  8574. }
  8575. maybeTrace(fn, snapshot) {
  8576. // Only trace the execution if the snapshot is defined.
  8577. return snapshot ? snapshot.run(TracingAction.AFTER_NEXT_RENDER, fn) : fn();
  8578. }
  8579. /** @nocollapse */
  8580. static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
  8581. token: AfterRenderImpl,
  8582. providedIn: 'root',
  8583. factory: () => new AfterRenderImpl(),
  8584. });
  8585. }
  8586. class AfterRenderSequence {
  8587. impl;
  8588. hooks;
  8589. view;
  8590. once;
  8591. snapshot;
  8592. /**
  8593. * Whether this sequence errored or was destroyed during this execution, and hooks should no
  8594. * longer run for it.
  8595. */
  8596. erroredOrDestroyed = false;
  8597. /**
  8598. * The value returned by the last hook execution (if any), ready to be pipelined into the next
  8599. * one.
  8600. */
  8601. pipelinedValue = undefined;
  8602. unregisterOnDestroy;
  8603. constructor(impl, hooks, view, once, destroyRef, snapshot = null) {
  8604. this.impl = impl;
  8605. this.hooks = hooks;
  8606. this.view = view;
  8607. this.once = once;
  8608. this.snapshot = snapshot;
  8609. this.unregisterOnDestroy = destroyRef?.onDestroy(() => this.destroy());
  8610. }
  8611. afterRun() {
  8612. this.erroredOrDestroyed = false;
  8613. this.pipelinedValue = undefined;
  8614. // Clear the tracing snapshot after the initial run. This snapshot only
  8615. // associates the initial run of the hook with the context that created it.
  8616. // Follow-up runs are independent of that initial context and have different
  8617. // triggers.
  8618. this.snapshot?.dispose();
  8619. this.snapshot = null;
  8620. }
  8621. destroy() {
  8622. this.impl.unregister(this);
  8623. this.unregisterOnDestroy?.();
  8624. const scheduled = this.view?.[AFTER_RENDER_SEQUENCES_TO_ADD];
  8625. if (scheduled) {
  8626. this.view[AFTER_RENDER_SEQUENCES_TO_ADD] = scheduled.filter((s) => s !== this);
  8627. }
  8628. }
  8629. }
  8630. function afterRender(callbackOrSpec, options) {
  8631. ngDevMode &&
  8632. assertNotInReactiveContext(afterRender, 'Call `afterRender` outside of a reactive context. For example, schedule the render ' +
  8633. 'callback inside the component constructor`.');
  8634. !options?.injector && assertInInjectionContext(afterRender);
  8635. const injector = options?.injector ?? inject(Injector);
  8636. if (typeof ngServerMode !== 'undefined' && ngServerMode) {
  8637. return NOOP_AFTER_RENDER_REF;
  8638. }
  8639. performanceMarkFeature('NgAfterRender');
  8640. return afterRenderImpl(callbackOrSpec, injector, options, /* once */ false);
  8641. }
  8642. function afterNextRender(callbackOrSpec, options) {
  8643. !options?.injector && assertInInjectionContext(afterNextRender);
  8644. const injector = options?.injector ?? inject(Injector);
  8645. if (typeof ngServerMode !== 'undefined' && ngServerMode) {
  8646. return NOOP_AFTER_RENDER_REF;
  8647. }
  8648. performanceMarkFeature('NgAfterNextRender');
  8649. return afterRenderImpl(callbackOrSpec, injector, options, /* once */ true);
  8650. }
  8651. function getHooks(callbackOrSpec, phase) {
  8652. if (callbackOrSpec instanceof Function) {
  8653. const hooks = [undefined, undefined, undefined, undefined];
  8654. hooks[phase] = callbackOrSpec;
  8655. return hooks;
  8656. }
  8657. else {
  8658. return [
  8659. callbackOrSpec.earlyRead,
  8660. callbackOrSpec.write,
  8661. callbackOrSpec.mixedReadWrite,
  8662. callbackOrSpec.read,
  8663. ];
  8664. }
  8665. }
  8666. /**
  8667. * Shared implementation for `afterRender` and `afterNextRender`.
  8668. */
  8669. function afterRenderImpl(callbackOrSpec, injector, options, once) {
  8670. const manager = injector.get(AfterRenderManager);
  8671. // Lazily initialize the handler implementation, if necessary. This is so that it can be
  8672. // tree-shaken if `afterRender` and `afterNextRender` aren't used.
  8673. manager.impl ??= injector.get(AfterRenderImpl);
  8674. const tracing = injector.get(TracingService, null, { optional: true });
  8675. const hooks = options?.phase ?? AfterRenderPhase.MixedReadWrite;
  8676. const destroyRef = options?.manualCleanup !== true ? injector.get(DestroyRef) : null;
  8677. const viewContext = injector.get(ViewContext, null, { optional: true });
  8678. const sequence = new AfterRenderSequence(manager.impl, getHooks(callbackOrSpec, hooks), viewContext?.view, once, destroyRef, tracing?.snapshot(null));
  8679. manager.impl.register(sequence);
  8680. return sequence;
  8681. }
  8682. /** `AfterRenderRef` that does nothing. */
  8683. const NOOP_AFTER_RENDER_REF = {
  8684. destroy() { },
  8685. };
  8686. /**
  8687. * Describes the state of defer block dependency loading.
  8688. */
  8689. var DeferDependenciesLoadingState;
  8690. (function (DeferDependenciesLoadingState) {
  8691. /** Initial state, dependency loading is not yet triggered */
  8692. DeferDependenciesLoadingState[DeferDependenciesLoadingState["NOT_STARTED"] = 0] = "NOT_STARTED";
  8693. /** Dependency loading is in progress */
  8694. DeferDependenciesLoadingState[DeferDependenciesLoadingState["IN_PROGRESS"] = 1] = "IN_PROGRESS";
  8695. /** Dependency loading has completed successfully */
  8696. DeferDependenciesLoadingState[DeferDependenciesLoadingState["COMPLETE"] = 2] = "COMPLETE";
  8697. /** Dependency loading has failed */
  8698. DeferDependenciesLoadingState[DeferDependenciesLoadingState["FAILED"] = 3] = "FAILED";
  8699. })(DeferDependenciesLoadingState || (DeferDependenciesLoadingState = {}));
  8700. /** Slot index where `minimum` parameter value is stored. */
  8701. const MINIMUM_SLOT = 0;
  8702. /** Slot index where `after` parameter value is stored. */
  8703. const LOADING_AFTER_SLOT = 1;
  8704. /**
  8705. * Describes the current state of this defer block instance.
  8706. *
  8707. * @publicApi
  8708. */
  8709. var DeferBlockState;
  8710. (function (DeferBlockState) {
  8711. /** The placeholder block content is rendered */
  8712. DeferBlockState[DeferBlockState["Placeholder"] = 0] = "Placeholder";
  8713. /** The loading block content is rendered */
  8714. DeferBlockState[DeferBlockState["Loading"] = 1] = "Loading";
  8715. /** The main content block content is rendered */
  8716. DeferBlockState[DeferBlockState["Complete"] = 2] = "Complete";
  8717. /** The error block content is rendered */
  8718. DeferBlockState[DeferBlockState["Error"] = 3] = "Error";
  8719. })(DeferBlockState || (DeferBlockState = {}));
  8720. /**
  8721. * Describes the initial state of this defer block instance.
  8722. *
  8723. * Note: this state is internal only and *must* be represented
  8724. * with a number lower than any value in the `DeferBlockState` enum.
  8725. */
  8726. var DeferBlockInternalState;
  8727. (function (DeferBlockInternalState) {
  8728. /** Initial state. Nothing is rendered yet. */
  8729. DeferBlockInternalState[DeferBlockInternalState["Initial"] = -1] = "Initial";
  8730. })(DeferBlockInternalState || (DeferBlockInternalState = {}));
  8731. const NEXT_DEFER_BLOCK_STATE = 0;
  8732. // Note: it's *important* to keep the state in this slot, because this slot
  8733. // is used by runtime logic to differentiate between LViews, LContainers and
  8734. // other types (see `isLView` and `isLContainer` functions). In case of defer
  8735. // blocks, this slot would always be a number.
  8736. const DEFER_BLOCK_STATE = 1;
  8737. const STATE_IS_FROZEN_UNTIL = 2;
  8738. const LOADING_AFTER_CLEANUP_FN = 3;
  8739. const TRIGGER_CLEANUP_FNS = 4;
  8740. const PREFETCH_TRIGGER_CLEANUP_FNS = 5;
  8741. const SSR_UNIQUE_ID = 6;
  8742. const SSR_BLOCK_STATE = 7;
  8743. const ON_COMPLETE_FNS = 8;
  8744. const HYDRATE_TRIGGER_CLEANUP_FNS = 9;
  8745. /**
  8746. * Options for configuring defer blocks behavior.
  8747. * @publicApi
  8748. */
  8749. var DeferBlockBehavior;
  8750. (function (DeferBlockBehavior) {
  8751. /**
  8752. * Manual triggering mode for defer blocks. Provides control over when defer blocks render
  8753. * and which state they render.
  8754. */
  8755. DeferBlockBehavior[DeferBlockBehavior["Manual"] = 0] = "Manual";
  8756. /**
  8757. * Playthrough mode for defer blocks. This mode behaves like defer blocks would in a browser.
  8758. * This is the default behavior in test environments.
  8759. */
  8760. DeferBlockBehavior[DeferBlockBehavior["Playthrough"] = 1] = "Playthrough";
  8761. })(DeferBlockBehavior || (DeferBlockBehavior = {}));
  8762. /*!
  8763. * @license
  8764. * Copyright Google LLC All Rights Reserved.
  8765. *
  8766. * Use of this source code is governed by an MIT-style license that can be
  8767. * found in the LICENSE file at https://angular.dev/license
  8768. */
  8769. /**
  8770. * Registers a cleanup function associated with a prefetching trigger
  8771. * or a regular trigger of a defer block.
  8772. */
  8773. function storeTriggerCleanupFn(type, lDetails, cleanupFn) {
  8774. const key = getCleanupFnKeyByType(type);
  8775. if (lDetails[key] === null) {
  8776. lDetails[key] = [];
  8777. }
  8778. lDetails[key].push(cleanupFn);
  8779. }
  8780. /**
  8781. * Invokes registered cleanup functions either for prefetch or for regular triggers.
  8782. */
  8783. function invokeTriggerCleanupFns(type, lDetails) {
  8784. const key = getCleanupFnKeyByType(type);
  8785. const cleanupFns = lDetails[key];
  8786. if (cleanupFns !== null) {
  8787. for (const cleanupFn of cleanupFns) {
  8788. cleanupFn();
  8789. }
  8790. lDetails[key] = null;
  8791. }
  8792. }
  8793. /**
  8794. * Invokes registered cleanup functions for prefetch, hydrate, and regular triggers.
  8795. */
  8796. function invokeAllTriggerCleanupFns(lDetails) {
  8797. invokeTriggerCleanupFns(1 /* TriggerType.Prefetch */, lDetails);
  8798. invokeTriggerCleanupFns(0 /* TriggerType.Regular */, lDetails);
  8799. invokeTriggerCleanupFns(2 /* TriggerType.Hydrate */, lDetails);
  8800. }
  8801. function getCleanupFnKeyByType(type) {
  8802. let key = TRIGGER_CLEANUP_FNS;
  8803. if (type === 1 /* TriggerType.Prefetch */) {
  8804. key = PREFETCH_TRIGGER_CLEANUP_FNS;
  8805. }
  8806. else if (type === 2 /* TriggerType.Hydrate */) {
  8807. key = HYDRATE_TRIGGER_CLEANUP_FNS;
  8808. }
  8809. return key;
  8810. }
  8811. /**
  8812. * Calculates a data slot index for defer block info (either static or
  8813. * instance-specific), given an index of a defer instruction.
  8814. */
  8815. function getDeferBlockDataIndex(deferBlockIndex) {
  8816. // Instance state is located at the *next* position
  8817. // after the defer block slot in an LView or TView.data.
  8818. return deferBlockIndex + 1;
  8819. }
  8820. /** Retrieves a defer block state from an LView, given a TNode that represents a block. */
  8821. function getLDeferBlockDetails(lView, tNode) {
  8822. const tView = lView[TVIEW];
  8823. const slotIndex = getDeferBlockDataIndex(tNode.index);
  8824. ngDevMode && assertIndexInDeclRange(tView, slotIndex);
  8825. return lView[slotIndex];
  8826. }
  8827. /** Stores a defer block instance state in LView. */
  8828. function setLDeferBlockDetails(lView, deferBlockIndex, lDetails) {
  8829. const tView = lView[TVIEW];
  8830. const slotIndex = getDeferBlockDataIndex(deferBlockIndex);
  8831. ngDevMode && assertIndexInDeclRange(tView, slotIndex);
  8832. lView[slotIndex] = lDetails;
  8833. }
  8834. /** Retrieves static info about a defer block, given a TView and a TNode that represents a block. */
  8835. function getTDeferBlockDetails(tView, tNode) {
  8836. const slotIndex = getDeferBlockDataIndex(tNode.index);
  8837. ngDevMode && assertIndexInDeclRange(tView, slotIndex);
  8838. return tView.data[slotIndex];
  8839. }
  8840. /** Stores a defer block static info in `TView.data`. */
  8841. function setTDeferBlockDetails(tView, deferBlockIndex, deferBlockConfig) {
  8842. const slotIndex = getDeferBlockDataIndex(deferBlockIndex);
  8843. ngDevMode && assertIndexInDeclRange(tView, slotIndex);
  8844. tView.data[slotIndex] = deferBlockConfig;
  8845. }
  8846. function getTemplateIndexForState(newState, hostLView, tNode) {
  8847. const tView = hostLView[TVIEW];
  8848. const tDetails = getTDeferBlockDetails(tView, tNode);
  8849. switch (newState) {
  8850. case DeferBlockState.Complete:
  8851. return tDetails.primaryTmplIndex;
  8852. case DeferBlockState.Loading:
  8853. return tDetails.loadingTmplIndex;
  8854. case DeferBlockState.Error:
  8855. return tDetails.errorTmplIndex;
  8856. case DeferBlockState.Placeholder:
  8857. return tDetails.placeholderTmplIndex;
  8858. default:
  8859. ngDevMode && throwError(`Unexpected defer block state: ${newState}`);
  8860. return null;
  8861. }
  8862. }
  8863. /**
  8864. * Returns a minimum amount of time that a given state should be rendered for,
  8865. * taking into account `minimum` parameter value. If the `minimum` value is
  8866. * not specified - returns `null`.
  8867. */
  8868. function getMinimumDurationForState(tDetails, currentState) {
  8869. if (currentState === DeferBlockState.Placeholder) {
  8870. return tDetails.placeholderBlockConfig?.[MINIMUM_SLOT] ?? null;
  8871. }
  8872. else if (currentState === DeferBlockState.Loading) {
  8873. return tDetails.loadingBlockConfig?.[MINIMUM_SLOT] ?? null;
  8874. }
  8875. return null;
  8876. }
  8877. /** Retrieves the value of the `after` parameter on the @loading block. */
  8878. function getLoadingBlockAfter(tDetails) {
  8879. return tDetails.loadingBlockConfig?.[LOADING_AFTER_SLOT] ?? null;
  8880. }
  8881. /**
  8882. * Adds downloaded dependencies into a directive or a pipe registry,
  8883. * making sure that a dependency doesn't yet exist in the registry.
  8884. */
  8885. function addDepsToRegistry(currentDeps, newDeps) {
  8886. if (!currentDeps || currentDeps.length === 0) {
  8887. return newDeps;
  8888. }
  8889. const currentDepSet = new Set(currentDeps);
  8890. for (const dep of newDeps) {
  8891. currentDepSet.add(dep);
  8892. }
  8893. // If `currentDeps` is the same length, there were no new deps and can
  8894. // return the original array.
  8895. return currentDeps.length === currentDepSet.size ? currentDeps : Array.from(currentDepSet);
  8896. }
  8897. /** Retrieves a TNode that represents main content of a defer block. */
  8898. function getPrimaryBlockTNode(tView, tDetails) {
  8899. const adjustedIndex = tDetails.primaryTmplIndex + HEADER_OFFSET;
  8900. return getTNode(tView, adjustedIndex);
  8901. }
  8902. /**
  8903. * Asserts whether all dependencies for a defer block are loaded.
  8904. * Always run this function (in dev mode) before rendering a defer
  8905. * block in completed state.
  8906. */
  8907. function assertDeferredDependenciesLoaded(tDetails) {
  8908. assertEqual(tDetails.loadingState, DeferDependenciesLoadingState.COMPLETE, 'Expecting all deferred dependencies to be loaded.');
  8909. }
  8910. /**
  8911. * Determines if a given value matches the expected structure of a defer block
  8912. *
  8913. * We can safely rely on the primaryTmplIndex because every defer block requires
  8914. * that a primary template exists. All the other template options are optional.
  8915. */
  8916. function isTDeferBlockDetails(value) {
  8917. return (value !== null &&
  8918. typeof value === 'object' &&
  8919. typeof value.primaryTmplIndex === 'number');
  8920. }
  8921. /**
  8922. * Whether a given TNode represents a defer block.
  8923. */
  8924. function isDeferBlock(tView, tNode) {
  8925. let tDetails = null;
  8926. const slotIndex = getDeferBlockDataIndex(tNode.index);
  8927. // Check if a slot index is in the reasonable range.
  8928. // Note: we do `-1` on the right border, since defer block details are stored
  8929. // in the `n+1` slot, see `getDeferBlockDataIndex` for more info.
  8930. if (HEADER_OFFSET < slotIndex && slotIndex < tView.bindingStartIndex) {
  8931. tDetails = getTDeferBlockDetails(tView, tNode);
  8932. }
  8933. return !!tDetails && isTDeferBlockDetails(tDetails);
  8934. }
  8935. /**
  8936. * Tracks debugging information about a trigger.
  8937. * @param tView TView in which the trigger is declared.
  8938. * @param tNode TNode on which the trigger is declared.
  8939. * @param textRepresentation Text representation of the trigger to be used for debugging purposes.
  8940. */
  8941. function trackTriggerForDebugging(tView, tNode, textRepresentation) {
  8942. const tDetails = getTDeferBlockDetails(tView, tNode);
  8943. tDetails.debug ??= {};
  8944. tDetails.debug.triggers ??= new Set();
  8945. tDetails.debug.triggers.add(textRepresentation);
  8946. }
  8947. /*!
  8948. * @license
  8949. * Copyright Google LLC All Rights Reserved.
  8950. *
  8951. * Use of this source code is governed by an MIT-style license that can be
  8952. * found in the LICENSE file at https://angular.dev/license
  8953. */
  8954. /** Configuration object used to register passive and capturing events. */
  8955. const eventListenerOptions = {
  8956. passive: true,
  8957. capture: true,
  8958. };
  8959. /** Keeps track of the currently-registered `on hover` triggers. */
  8960. const hoverTriggers = new WeakMap();
  8961. /** Keeps track of the currently-registered `on interaction` triggers. */
  8962. const interactionTriggers = new WeakMap();
  8963. /** Currently-registered `viewport` triggers. */
  8964. const viewportTriggers = new WeakMap();
  8965. /** Names of the events considered as interaction events. */
  8966. const interactionEventNames = ['click', 'keydown'];
  8967. /** Names of the events considered as hover events. */
  8968. const hoverEventNames = ['mouseenter', 'mouseover', 'focusin'];
  8969. /** `IntersectionObserver` used to observe `viewport` triggers. */
  8970. let intersectionObserver = null;
  8971. /** Number of elements currently observed with `viewport` triggers. */
  8972. let observedViewportElements = 0;
  8973. /** Object keeping track of registered callbacks for a deferred block trigger. */
  8974. class DeferEventEntry {
  8975. callbacks = new Set();
  8976. listener = () => {
  8977. for (const callback of this.callbacks) {
  8978. callback();
  8979. }
  8980. };
  8981. }
  8982. /**
  8983. * Registers an interaction trigger.
  8984. * @param trigger Element that is the trigger.
  8985. * @param callback Callback to be invoked when the trigger is interacted with.
  8986. */
  8987. function onInteraction(trigger, callback) {
  8988. let entry = interactionTriggers.get(trigger);
  8989. // If this is the first entry for this element, add the listeners.
  8990. if (!entry) {
  8991. // Note that managing events centrally like this lends itself well to using global
  8992. // event delegation. It currently does delegation at the element level, rather than the
  8993. // document level, because:
  8994. // 1. Global delegation is the most effective when there are a lot of events being registered
  8995. // at the same time. Deferred blocks are unlikely to be used in such a way.
  8996. // 2. Matching events to their target isn't free. For each `click` and `keydown` event we
  8997. // would have look through all the triggers and check if the target either is the element
  8998. // itself or it's contained within the element. Given that `click` and `keydown` are some
  8999. // of the most common events, this may end up introducing a lot of runtime overhead.
  9000. // 3. We're still registering only two events per element, no matter how many deferred blocks
  9001. // are referencing it.
  9002. entry = new DeferEventEntry();
  9003. interactionTriggers.set(trigger, entry);
  9004. for (const name of interactionEventNames) {
  9005. trigger.addEventListener(name, entry.listener, eventListenerOptions);
  9006. }
  9007. }
  9008. entry.callbacks.add(callback);
  9009. return () => {
  9010. const { callbacks, listener } = entry;
  9011. callbacks.delete(callback);
  9012. if (callbacks.size === 0) {
  9013. interactionTriggers.delete(trigger);
  9014. for (const name of interactionEventNames) {
  9015. trigger.removeEventListener(name, listener, eventListenerOptions);
  9016. }
  9017. }
  9018. };
  9019. }
  9020. /**
  9021. * Registers a hover trigger.
  9022. * @param trigger Element that is the trigger.
  9023. * @param callback Callback to be invoked when the trigger is hovered over.
  9024. */
  9025. function onHover(trigger, callback) {
  9026. let entry = hoverTriggers.get(trigger);
  9027. // If this is the first entry for this element, add the listener.
  9028. if (!entry) {
  9029. entry = new DeferEventEntry();
  9030. hoverTriggers.set(trigger, entry);
  9031. for (const name of hoverEventNames) {
  9032. trigger.addEventListener(name, entry.listener, eventListenerOptions);
  9033. }
  9034. }
  9035. entry.callbacks.add(callback);
  9036. return () => {
  9037. const { callbacks, listener } = entry;
  9038. callbacks.delete(callback);
  9039. if (callbacks.size === 0) {
  9040. for (const name of hoverEventNames) {
  9041. trigger.removeEventListener(name, listener, eventListenerOptions);
  9042. }
  9043. hoverTriggers.delete(trigger);
  9044. }
  9045. };
  9046. }
  9047. /**
  9048. * Registers a viewport trigger.
  9049. * @param trigger Element that is the trigger.
  9050. * @param callback Callback to be invoked when the trigger comes into the viewport.
  9051. * @param injector Injector that can be used by the trigger to resolve DI tokens.
  9052. */
  9053. function onViewport(trigger, callback, injector) {
  9054. const ngZone = injector.get(NgZone);
  9055. let entry = viewportTriggers.get(trigger);
  9056. intersectionObserver =
  9057. intersectionObserver ||
  9058. ngZone.runOutsideAngular(() => {
  9059. return new IntersectionObserver((entries) => {
  9060. for (const current of entries) {
  9061. // Only invoke the callbacks if the specific element is intersecting.
  9062. if (current.isIntersecting && viewportTriggers.has(current.target)) {
  9063. ngZone.run(viewportTriggers.get(current.target).listener);
  9064. }
  9065. }
  9066. });
  9067. });
  9068. if (!entry) {
  9069. entry = new DeferEventEntry();
  9070. ngZone.runOutsideAngular(() => intersectionObserver.observe(trigger));
  9071. viewportTriggers.set(trigger, entry);
  9072. observedViewportElements++;
  9073. }
  9074. entry.callbacks.add(callback);
  9075. return () => {
  9076. // It's possible that a different cleanup callback fully removed this element already.
  9077. if (!viewportTriggers.has(trigger)) {
  9078. return;
  9079. }
  9080. entry.callbacks.delete(callback);
  9081. if (entry.callbacks.size === 0) {
  9082. intersectionObserver?.unobserve(trigger);
  9083. viewportTriggers.delete(trigger);
  9084. observedViewportElements--;
  9085. }
  9086. if (observedViewportElements === 0) {
  9087. intersectionObserver?.disconnect();
  9088. intersectionObserver = null;
  9089. }
  9090. };
  9091. }
  9092. /**
  9093. * Helper function to get the LView in which a deferred block's trigger is rendered.
  9094. * @param deferredHostLView LView in which the deferred block is defined.
  9095. * @param deferredTNode TNode defining the deferred block.
  9096. * @param walkUpTimes Number of times to go up in the view hierarchy to find the trigger's view.
  9097. * A negative value means that the trigger is inside the block's placeholder, while an undefined
  9098. * value means that the trigger is in the same LView as the deferred block.
  9099. */
  9100. function getTriggerLView(deferredHostLView, deferredTNode, walkUpTimes) {
  9101. // The trigger is in the same view, we don't need to traverse.
  9102. if (walkUpTimes == null) {
  9103. return deferredHostLView;
  9104. }
  9105. // A positive value or zero means that the trigger is in a parent view.
  9106. if (walkUpTimes >= 0) {
  9107. return walkUpViews(walkUpTimes, deferredHostLView);
  9108. }
  9109. // If the value is negative, it means that the trigger is inside the placeholder.
  9110. const deferredContainer = deferredHostLView[deferredTNode.index];
  9111. ngDevMode && assertLContainer(deferredContainer);
  9112. const triggerLView = deferredContainer[CONTAINER_HEADER_OFFSET] ?? null;
  9113. // We need to null check, because the placeholder might not have been rendered yet.
  9114. if (ngDevMode && triggerLView !== null) {
  9115. const lDetails = getLDeferBlockDetails(deferredHostLView, deferredTNode);
  9116. const renderedState = lDetails[DEFER_BLOCK_STATE];
  9117. assertEqual(renderedState, DeferBlockState.Placeholder, 'Expected a placeholder to be rendered in this defer block.');
  9118. assertLView(triggerLView);
  9119. }
  9120. return triggerLView;
  9121. }
  9122. /**
  9123. * Gets the element that a deferred block's trigger is pointing to.
  9124. * @param triggerLView LView in which the trigger is defined.
  9125. * @param triggerIndex Index at which the trigger element should've been rendered.
  9126. */
  9127. function getTriggerElement(triggerLView, triggerIndex) {
  9128. const element = getNativeByIndex(HEADER_OFFSET + triggerIndex, triggerLView);
  9129. ngDevMode && assertElement(element);
  9130. return element;
  9131. }
  9132. /**
  9133. * Registers a DOM-node based trigger.
  9134. * @param initialLView LView in which the defer block is rendered.
  9135. * @param tNode TNode representing the defer block.
  9136. * @param triggerIndex Index at which to find the trigger element.
  9137. * @param walkUpTimes Number of times to go up/down in the view hierarchy to find the trigger.
  9138. * @param registerFn Function that will register the DOM events.
  9139. * @param callback Callback to be invoked when the trigger receives the event that should render
  9140. * the deferred block.
  9141. * @param type Trigger type to distinguish between regular and prefetch triggers.
  9142. */
  9143. function registerDomTrigger(initialLView, tNode, triggerIndex, walkUpTimes, registerFn, callback, type) {
  9144. const injector = initialLView[INJECTOR];
  9145. const zone = injector.get(NgZone);
  9146. let poll;
  9147. function pollDomTrigger() {
  9148. // If the initial view was destroyed, we don't need to do anything.
  9149. if (isDestroyed(initialLView)) {
  9150. poll.destroy();
  9151. return;
  9152. }
  9153. const lDetails = getLDeferBlockDetails(initialLView, tNode);
  9154. const renderedState = lDetails[DEFER_BLOCK_STATE];
  9155. // If the block was loaded before the trigger was resolved, we don't need to do anything.
  9156. if (renderedState !== DeferBlockInternalState.Initial &&
  9157. renderedState !== DeferBlockState.Placeholder) {
  9158. poll.destroy();
  9159. return;
  9160. }
  9161. const triggerLView = getTriggerLView(initialLView, tNode, walkUpTimes);
  9162. // Keep polling until we resolve the trigger's LView.
  9163. if (!triggerLView) {
  9164. // Keep polling.
  9165. return;
  9166. }
  9167. poll.destroy();
  9168. // It's possible that the trigger's view was destroyed before we resolved the trigger element.
  9169. if (isDestroyed(triggerLView)) {
  9170. return;
  9171. }
  9172. const element = getTriggerElement(triggerLView, triggerIndex);
  9173. const cleanup = registerFn(element, () => {
  9174. // `pollDomTrigger` runs outside the zone (because of `afterNextRender`) and registers its
  9175. // listeners outside the zone, so we jump back into the zone prior to running the callback.
  9176. zone.run(() => {
  9177. if (initialLView !== triggerLView) {
  9178. removeLViewOnDestroy(triggerLView, cleanup);
  9179. }
  9180. callback();
  9181. });
  9182. }, injector);
  9183. // The trigger and deferred block might be in different LViews.
  9184. // For the main LView the cleanup would happen as a part of
  9185. // `storeTriggerCleanupFn` logic. For trigger LView we register
  9186. // a cleanup function there to remove event handlers in case an
  9187. // LView gets destroyed before a trigger is invoked.
  9188. if (initialLView !== triggerLView) {
  9189. storeLViewOnDestroy(triggerLView, cleanup);
  9190. }
  9191. storeTriggerCleanupFn(type, lDetails, cleanup);
  9192. }
  9193. // Begin polling for the trigger.
  9194. poll = afterRender({ read: pollDomTrigger }, { injector });
  9195. }
  9196. const DEFER_BLOCK_SSR_ID_ATTRIBUTE = 'ngb';
  9197. function setJSActionAttributes(nativeElement, eventTypes, parentDeferBlockId = null) {
  9198. // jsaction attributes specifically should be applied to elements and not comment nodes.
  9199. // Comment nodes also have no setAttribute function. So this avoids errors.
  9200. if (eventTypes.length === 0 || nativeElement.nodeType !== Node.ELEMENT_NODE) {
  9201. return;
  9202. }
  9203. const existingAttr = nativeElement.getAttribute(Attribute$1.JSACTION);
  9204. // we dedupe cases where hydrate triggers are used as it's possible that
  9205. // someone may have added an event binding to the root node that matches what the
  9206. // hydrate trigger adds.
  9207. const parts = eventTypes.reduce((prev, curr) => {
  9208. // if there is no existing attribute OR it's not in the existing one, we need to add it
  9209. return (existingAttr?.indexOf(curr) ?? -1) === -1 ? prev + curr + ':;' : prev;
  9210. }, '');
  9211. // This is required to be a module accessor to appease security tests on setAttribute.
  9212. nativeElement.setAttribute(Attribute$1.JSACTION, `${existingAttr ?? ''}${parts}`);
  9213. const blockName = parentDeferBlockId ?? '';
  9214. if (blockName !== '' && parts.length > 0) {
  9215. nativeElement.setAttribute(DEFER_BLOCK_SSR_ID_ATTRIBUTE, blockName);
  9216. }
  9217. }
  9218. const sharedStashFunction = (rEl, eventType, listenerFn) => {
  9219. const el = rEl;
  9220. const eventListenerMap = el.__jsaction_fns ?? new Map();
  9221. const eventListeners = eventListenerMap.get(eventType) ?? [];
  9222. eventListeners.push(listenerFn);
  9223. eventListenerMap.set(eventType, eventListeners);
  9224. el.__jsaction_fns = eventListenerMap;
  9225. };
  9226. const sharedMapFunction = (rEl, jsActionMap) => {
  9227. const el = rEl;
  9228. let blockName = el.getAttribute(DEFER_BLOCK_SSR_ID_ATTRIBUTE) ?? '';
  9229. const blockSet = jsActionMap.get(blockName) ?? new Set();
  9230. if (!blockSet.has(el)) {
  9231. blockSet.add(el);
  9232. }
  9233. jsActionMap.set(blockName, blockSet);
  9234. };
  9235. function removeListenersFromBlocks(blockNames, jsActionMap) {
  9236. if (blockNames.length > 0) {
  9237. let blockList = [];
  9238. for (let blockName of blockNames) {
  9239. if (jsActionMap.has(blockName)) {
  9240. blockList = [...blockList, ...jsActionMap.get(blockName)];
  9241. }
  9242. }
  9243. const replayList = new Set(blockList);
  9244. replayList.forEach(removeListeners);
  9245. }
  9246. }
  9247. const removeListeners = (el) => {
  9248. el.removeAttribute(Attribute$1.JSACTION);
  9249. el.removeAttribute(DEFER_BLOCK_SSR_ID_ATTRIBUTE);
  9250. el.__jsaction_fns = undefined;
  9251. };
  9252. const JSACTION_EVENT_CONTRACT = new InjectionToken(ngDevMode ? 'EVENT_CONTRACT_DETAILS' : '', {
  9253. providedIn: 'root',
  9254. factory: () => ({}),
  9255. });
  9256. function invokeListeners(event, currentTarget) {
  9257. const handlerFns = currentTarget?.__jsaction_fns?.get(event.type);
  9258. if (!handlerFns || !currentTarget?.isConnected) {
  9259. return;
  9260. }
  9261. for (const handler of handlerFns) {
  9262. handler(event);
  9263. }
  9264. }
  9265. /**
  9266. * An internal injection token to reference `DehydratedBlockRegistry` implementation
  9267. * in a tree-shakable way.
  9268. */
  9269. const DEHYDRATED_BLOCK_REGISTRY = new InjectionToken(ngDevMode ? 'DEHYDRATED_BLOCK_REGISTRY' : '');
  9270. /**
  9271. * The DehydratedBlockRegistry is used for incremental hydration purposes. It keeps
  9272. * track of the Defer Blocks that need hydration so we can effectively
  9273. * navigate up to the top dehydrated defer block and fire appropriate cleanup
  9274. * functions post hydration.
  9275. */
  9276. class DehydratedBlockRegistry {
  9277. registry = new Map();
  9278. cleanupFns = new Map();
  9279. jsActionMap = inject(JSACTION_BLOCK_ELEMENT_MAP);
  9280. contract = inject(JSACTION_EVENT_CONTRACT);
  9281. add(blockId, info) {
  9282. this.registry.set(blockId, info);
  9283. // It's possible that hydration is queued that's waiting for the
  9284. // resolution of a lazy loaded route. In this case, we ensure
  9285. // the callback function is called to continue the hydration process
  9286. // for the queued block set.
  9287. if (this.awaitingCallbacks.has(blockId)) {
  9288. const awaitingCallbacks = this.awaitingCallbacks.get(blockId);
  9289. for (const cb of awaitingCallbacks) {
  9290. cb();
  9291. }
  9292. }
  9293. }
  9294. get(blockId) {
  9295. return this.registry.get(blockId) ?? null;
  9296. }
  9297. has(blockId) {
  9298. return this.registry.has(blockId);
  9299. }
  9300. cleanup(hydratedBlocks) {
  9301. removeListenersFromBlocks(hydratedBlocks, this.jsActionMap);
  9302. for (let blockId of hydratedBlocks) {
  9303. this.registry.delete(blockId);
  9304. this.jsActionMap.delete(blockId);
  9305. this.invokeTriggerCleanupFns(blockId);
  9306. this.hydrating.delete(blockId);
  9307. this.awaitingCallbacks.delete(blockId);
  9308. }
  9309. if (this.size === 0) {
  9310. this.contract.instance?.cleanUp();
  9311. }
  9312. }
  9313. get size() {
  9314. return this.registry.size;
  9315. }
  9316. // we have to leave the lowest block Id in the registry
  9317. // unless that block has no children
  9318. addCleanupFn(blockId, fn) {
  9319. let cleanupFunctions = [];
  9320. if (this.cleanupFns.has(blockId)) {
  9321. cleanupFunctions = this.cleanupFns.get(blockId);
  9322. }
  9323. cleanupFunctions.push(fn);
  9324. this.cleanupFns.set(blockId, cleanupFunctions);
  9325. }
  9326. invokeTriggerCleanupFns(blockId) {
  9327. const fns = this.cleanupFns.get(blockId) ?? [];
  9328. for (let fn of fns) {
  9329. fn();
  9330. }
  9331. this.cleanupFns.delete(blockId);
  9332. }
  9333. // Blocks that are being hydrated.
  9334. hydrating = new Map();
  9335. // Blocks that are awaiting a defer instruction finish.
  9336. awaitingCallbacks = new Map();
  9337. awaitParentBlock(topmostParentBlock, callback) {
  9338. const parentBlockAwaitCallbacks = this.awaitingCallbacks.get(topmostParentBlock) ?? [];
  9339. parentBlockAwaitCallbacks.push(callback);
  9340. this.awaitingCallbacks.set(topmostParentBlock, parentBlockAwaitCallbacks);
  9341. }
  9342. /** @nocollapse */
  9343. static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
  9344. token: DehydratedBlockRegistry,
  9345. providedIn: null,
  9346. factory: () => new DehydratedBlockRegistry(),
  9347. });
  9348. }
  9349. /**
  9350. * The name of the key used in the TransferState collection,
  9351. * where hydration information is located.
  9352. */
  9353. const TRANSFER_STATE_TOKEN_ID = '__nghData__';
  9354. /**
  9355. * Lookup key used to reference DOM hydration data (ngh) in `TransferState`.
  9356. */
  9357. const NGH_DATA_KEY = makeStateKey(TRANSFER_STATE_TOKEN_ID);
  9358. /**
  9359. * The name of the key used in the TransferState collection,
  9360. * where serialized defer block information is located.
  9361. */
  9362. const TRANSFER_STATE_DEFER_BLOCKS_INFO = '__nghDeferData__';
  9363. /**
  9364. * Lookup key used to retrieve defer block datain `TransferState`.
  9365. */
  9366. const NGH_DEFER_BLOCKS_KEY = makeStateKey(TRANSFER_STATE_DEFER_BLOCKS_INFO);
  9367. /**
  9368. * The name of the attribute that would be added to host component
  9369. * nodes and contain a reference to a particular slot in transferred
  9370. * state that contains the necessary hydration info for this component.
  9371. */
  9372. const NGH_ATTR_NAME = 'ngh';
  9373. /**
  9374. * Marker used in a comment node to ensure hydration content integrity
  9375. */
  9376. const SSR_CONTENT_INTEGRITY_MARKER = 'nghm';
  9377. /**
  9378. * Reference to a function that reads `ngh` attribute value from a given RNode
  9379. * and retrieves hydration information from the TransferState using that value
  9380. * as an index. Returns `null` by default, when hydration is not enabled.
  9381. *
  9382. * @param rNode Component's host element.
  9383. * @param injector Injector that this component has access to.
  9384. * @param isRootView Specifies whether we trying to read hydration info for the root view.
  9385. */
  9386. let _retrieveHydrationInfoImpl = () => null;
  9387. function retrieveHydrationInfoImpl(rNode, injector, isRootView = false) {
  9388. let nghAttrValue = rNode.getAttribute(NGH_ATTR_NAME);
  9389. if (nghAttrValue == null)
  9390. return null;
  9391. // For cases when a root component also acts as an anchor node for a ViewContainerRef
  9392. // (for example, when ViewContainerRef is injected in a root component), there is a need
  9393. // to serialize information about the component itself, as well as an LContainer that
  9394. // represents this ViewContainerRef. Effectively, we need to serialize 2 pieces of info:
  9395. // (1) hydration info for the root component itself and (2) hydration info for the
  9396. // ViewContainerRef instance (an LContainer). Each piece of information is included into
  9397. // the hydration data (in the TransferState object) separately, thus we end up with 2 ids.
  9398. // Since we only have 1 root element, we encode both bits of info into a single string:
  9399. // ids are separated by the `|` char (e.g. `10|25`, where `10` is the ngh for a component view
  9400. // and 25 is the `ngh` for a root view which holds LContainer).
  9401. const [componentViewNgh, rootViewNgh] = nghAttrValue.split('|');
  9402. nghAttrValue = isRootView ? rootViewNgh : componentViewNgh;
  9403. if (!nghAttrValue)
  9404. return null;
  9405. // We've read one of the ngh ids, keep the remaining one, so that
  9406. // we can set it back on the DOM element.
  9407. const rootNgh = rootViewNgh ? `|${rootViewNgh}` : '';
  9408. const remainingNgh = isRootView ? componentViewNgh : rootNgh;
  9409. let data = {};
  9410. // An element might have an empty `ngh` attribute value (e.g. `<comp ngh="" />`),
  9411. // which means that no special annotations are required. Do not attempt to read
  9412. // from the TransferState in this case.
  9413. if (nghAttrValue !== '') {
  9414. const transferState = injector.get(TransferState, null, { optional: true });
  9415. if (transferState !== null) {
  9416. const nghData = transferState.get(NGH_DATA_KEY, []);
  9417. // The nghAttrValue is always a number referencing an index
  9418. // in the hydration TransferState data.
  9419. data = nghData[Number(nghAttrValue)];
  9420. // If the `ngh` attribute exists and has a non-empty value,
  9421. // the hydration info *must* be present in the TransferState.
  9422. // If there is no data for some reasons, this is an error.
  9423. ngDevMode && assertDefined(data, 'Unable to retrieve hydration info from the TransferState.');
  9424. }
  9425. }
  9426. const dehydratedView = {
  9427. data,
  9428. firstChild: rNode.firstChild ?? null,
  9429. };
  9430. if (isRootView) {
  9431. // If there is hydration info present for the root view, it means that there was
  9432. // a ViewContainerRef injected in the root component. The root component host element
  9433. // acted as an anchor node in this scenario. As a result, the DOM nodes that represent
  9434. // embedded views in this ViewContainerRef are located as siblings to the host node,
  9435. // i.e. `<app-root /><#VIEW1><#VIEW2>...<!--container-->`. In this case, the current
  9436. // node becomes the first child of this root view and the next sibling is the first
  9437. // element in the DOM segment.
  9438. dehydratedView.firstChild = rNode;
  9439. // We use `0` here, since this is the slot (right after the HEADER_OFFSET)
  9440. // where a component LView or an LContainer is located in a root LView.
  9441. setSegmentHead(dehydratedView, 0, rNode.nextSibling);
  9442. }
  9443. if (remainingNgh) {
  9444. // If we have only used one of the ngh ids, store the remaining one
  9445. // back on this RNode.
  9446. rNode.setAttribute(NGH_ATTR_NAME, remainingNgh);
  9447. }
  9448. else {
  9449. // The `ngh` attribute is cleared from the DOM node now
  9450. // that the data has been retrieved for all indices.
  9451. rNode.removeAttribute(NGH_ATTR_NAME);
  9452. }
  9453. // Note: don't check whether this node was claimed for hydration,
  9454. // because this node might've been previously claimed while processing
  9455. // template instructions.
  9456. ngDevMode && markRNodeAsClaimedByHydration(rNode, /* checkIfAlreadyClaimed */ false);
  9457. ngDevMode && ngDevMode.hydratedComponents++;
  9458. return dehydratedView;
  9459. }
  9460. /**
  9461. * Sets the implementation for the `retrieveHydrationInfo` function.
  9462. */
  9463. function enableRetrieveHydrationInfoImpl() {
  9464. _retrieveHydrationInfoImpl = retrieveHydrationInfoImpl;
  9465. }
  9466. /**
  9467. * Retrieves hydration info by reading the value from the `ngh` attribute
  9468. * and accessing a corresponding slot in TransferState storage.
  9469. */
  9470. function retrieveHydrationInfo(rNode, injector, isRootView = false) {
  9471. return _retrieveHydrationInfoImpl(rNode, injector, isRootView);
  9472. }
  9473. /**
  9474. * Retrieves the necessary object from a given ViewRef to serialize:
  9475. * - an LView for component views
  9476. * - an LContainer for cases when component acts as a ViewContainerRef anchor
  9477. * - `null` in case of an embedded view
  9478. */
  9479. function getLNodeForHydration(viewRef) {
  9480. // Reading an internal field from `ViewRef` instance.
  9481. let lView = viewRef._lView;
  9482. const tView = lView[TVIEW];
  9483. // A registered ViewRef might represent an instance of an
  9484. // embedded view, in which case we do not need to annotate it.
  9485. if (tView.type === 2 /* TViewType.Embedded */) {
  9486. return null;
  9487. }
  9488. // Check if it's a root view and if so, retrieve component's
  9489. // LView from the first slot after the header.
  9490. if (isRootView(lView)) {
  9491. lView = lView[HEADER_OFFSET];
  9492. }
  9493. return lView;
  9494. }
  9495. function getTextNodeContent(node) {
  9496. return node.textContent?.replace(/\s/gm, '');
  9497. }
  9498. /**
  9499. * Restores text nodes and separators into the DOM that were lost during SSR
  9500. * serialization. The hydration process replaces empty text nodes and text
  9501. * nodes that are immediately adjacent to other text nodes with comment nodes
  9502. * that this method filters on to restore those missing nodes that the
  9503. * hydration process is expecting to be present.
  9504. *
  9505. * @param node The app's root HTML Element
  9506. */
  9507. function processTextNodeMarkersBeforeHydration(node) {
  9508. const doc = getDocument();
  9509. const commentNodesIterator = doc.createNodeIterator(node, NodeFilter.SHOW_COMMENT, {
  9510. acceptNode(node) {
  9511. const content = getTextNodeContent(node);
  9512. const isTextNodeMarker = content === "ngetn" /* TextNodeMarker.EmptyNode */ || content === "ngtns" /* TextNodeMarker.Separator */;
  9513. return isTextNodeMarker ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
  9514. },
  9515. });
  9516. let currentNode;
  9517. // We cannot modify the DOM while using the commentIterator,
  9518. // because it throws off the iterator state.
  9519. // So we collect all marker nodes first and then follow up with
  9520. // applying the changes to the DOM: either inserting an empty node
  9521. // or just removing the marker if it was used as a separator.
  9522. const nodes = [];
  9523. while ((currentNode = commentNodesIterator.nextNode())) {
  9524. nodes.push(currentNode);
  9525. }
  9526. for (const node of nodes) {
  9527. if (node.textContent === "ngetn" /* TextNodeMarker.EmptyNode */) {
  9528. node.replaceWith(doc.createTextNode(''));
  9529. }
  9530. else {
  9531. node.remove();
  9532. }
  9533. }
  9534. }
  9535. /**
  9536. * Internal type that represents a claimed node.
  9537. * Only used in dev mode.
  9538. */
  9539. var HydrationStatus;
  9540. (function (HydrationStatus) {
  9541. HydrationStatus["Hydrated"] = "hydrated";
  9542. HydrationStatus["Skipped"] = "skipped";
  9543. HydrationStatus["Mismatched"] = "mismatched";
  9544. })(HydrationStatus || (HydrationStatus = {}));
  9545. const HYDRATION_INFO_KEY = '__ngDebugHydrationInfo__';
  9546. function patchHydrationInfo(node, info) {
  9547. node[HYDRATION_INFO_KEY] = info;
  9548. }
  9549. function readHydrationInfo(node) {
  9550. return node[HYDRATION_INFO_KEY] ?? null;
  9551. }
  9552. /**
  9553. * Marks a node as "claimed" by hydration process.
  9554. * This is needed to make assessments in tests whether
  9555. * the hydration process handled all nodes.
  9556. */
  9557. function markRNodeAsClaimedByHydration(node, checkIfAlreadyClaimed = true) {
  9558. if (!ngDevMode) {
  9559. throw new Error('Calling `markRNodeAsClaimedByHydration` in prod mode ' +
  9560. 'is not supported and likely a mistake.');
  9561. }
  9562. if (checkIfAlreadyClaimed && isRNodeClaimedForHydration(node)) {
  9563. throw new Error('Trying to claim a node, which was claimed already.');
  9564. }
  9565. patchHydrationInfo(node, { status: HydrationStatus.Hydrated });
  9566. ngDevMode.hydratedNodes++;
  9567. }
  9568. function markRNodeAsSkippedByHydration(node) {
  9569. if (!ngDevMode) {
  9570. throw new Error('Calling `markRNodeAsSkippedByHydration` in prod mode ' +
  9571. 'is not supported and likely a mistake.');
  9572. }
  9573. patchHydrationInfo(node, { status: HydrationStatus.Skipped });
  9574. ngDevMode.componentsSkippedHydration++;
  9575. }
  9576. function countBlocksSkippedByHydration(injector) {
  9577. const transferState = injector.get(TransferState);
  9578. const nghDeferData = transferState.get(NGH_DEFER_BLOCKS_KEY, {});
  9579. if (ngDevMode) {
  9580. ngDevMode.deferBlocksWithIncrementalHydration = Object.keys(nghDeferData).length;
  9581. }
  9582. }
  9583. function markRNodeAsHavingHydrationMismatch(node, expectedNodeDetails = null, actualNodeDetails = null) {
  9584. if (!ngDevMode) {
  9585. throw new Error('Calling `markRNodeAsMismatchedByHydration` in prod mode ' +
  9586. 'is not supported and likely a mistake.');
  9587. }
  9588. // The RNode can be a standard HTMLElement (not an Angular component or directive)
  9589. // The devtools component tree only displays Angular components & directives
  9590. // Therefore we attach the debug info to the closest component/directive
  9591. while (node && !getComponent(node)) {
  9592. node = node?.parentNode;
  9593. }
  9594. if (node) {
  9595. patchHydrationInfo(node, {
  9596. status: HydrationStatus.Mismatched,
  9597. expectedNodeDetails,
  9598. actualNodeDetails,
  9599. });
  9600. }
  9601. }
  9602. function isRNodeClaimedForHydration(node) {
  9603. return readHydrationInfo(node)?.status === HydrationStatus.Hydrated;
  9604. }
  9605. function setSegmentHead(hydrationInfo, index, node) {
  9606. hydrationInfo.segmentHeads ??= {};
  9607. hydrationInfo.segmentHeads[index] = node;
  9608. }
  9609. function getSegmentHead(hydrationInfo, index) {
  9610. return hydrationInfo.segmentHeads?.[index] ?? null;
  9611. }
  9612. function isIncrementalHydrationEnabled(injector) {
  9613. return injector.get(IS_INCREMENTAL_HYDRATION_ENABLED, false, {
  9614. optional: true,
  9615. });
  9616. }
  9617. /** Throws an error if the incremental hydration is not enabled */
  9618. function assertIncrementalHydrationIsConfigured(injector) {
  9619. if (!isIncrementalHydrationEnabled(injector)) {
  9620. throw new RuntimeError(508 /* RuntimeErrorCode.MISCONFIGURED_INCREMENTAL_HYDRATION */, 'Angular has detected that some `@defer` blocks use `hydrate` triggers, ' +
  9621. 'but incremental hydration was not enabled. Please ensure that the `withIncrementalHydration()` ' +
  9622. 'call is added as an argument for the `provideClientHydration()` function call ' +
  9623. 'in your application config.');
  9624. }
  9625. }
  9626. /** Throws an error if the ssrUniqueId on the LDeferBlockDetails is not present */
  9627. function assertSsrIdDefined(ssrUniqueId) {
  9628. assertDefined(ssrUniqueId, 'Internal error: expecting an SSR id for a defer block that should be hydrated, but the id is not present');
  9629. }
  9630. /**
  9631. * Returns the size of an <ng-container>, using either the information
  9632. * serialized in `ELEMENT_CONTAINERS` (element container size) or by
  9633. * computing the sum of root nodes in all dehydrated views in a given
  9634. * container (in case this `<ng-container>` was also used as a view
  9635. * container host node, e.g. <ng-container *ngIf>).
  9636. */
  9637. function getNgContainerSize(hydrationInfo, index) {
  9638. const data = hydrationInfo.data;
  9639. let size = data[ELEMENT_CONTAINERS]?.[index] ?? null;
  9640. // If there is no serialized information available in the `ELEMENT_CONTAINERS` slot,
  9641. // check if we have info about view containers at this location (e.g.
  9642. // `<ng-container *ngIf>`) and use container size as a number of root nodes in this
  9643. // element container.
  9644. if (size === null && data[CONTAINERS]?.[index]) {
  9645. size = calcSerializedContainerSize(hydrationInfo, index);
  9646. }
  9647. return size;
  9648. }
  9649. function isSerializedElementContainer(hydrationInfo, index) {
  9650. return hydrationInfo.data[ELEMENT_CONTAINERS]?.[index] !== undefined;
  9651. }
  9652. function getSerializedContainerViews(hydrationInfo, index) {
  9653. return hydrationInfo.data[CONTAINERS]?.[index] ?? null;
  9654. }
  9655. /**
  9656. * Computes the size of a serialized container (the number of root nodes)
  9657. * by calculating the sum of root nodes in all dehydrated views in this container.
  9658. */
  9659. function calcSerializedContainerSize(hydrationInfo, index) {
  9660. const views = getSerializedContainerViews(hydrationInfo, index) ?? [];
  9661. let numNodes = 0;
  9662. for (let view of views) {
  9663. numNodes += view[NUM_ROOT_NODES] * (view[MULTIPLIER] ?? 1);
  9664. }
  9665. return numNodes;
  9666. }
  9667. /**
  9668. * Attempt to initialize the `disconnectedNodes` field of the given
  9669. * `DehydratedView`. Returns the initialized value.
  9670. */
  9671. function initDisconnectedNodes(hydrationInfo) {
  9672. // Check if we are processing disconnected info for the first time.
  9673. if (typeof hydrationInfo.disconnectedNodes === 'undefined') {
  9674. const nodeIds = hydrationInfo.data[DISCONNECTED_NODES];
  9675. hydrationInfo.disconnectedNodes = nodeIds ? new Set(nodeIds) : null;
  9676. }
  9677. return hydrationInfo.disconnectedNodes;
  9678. }
  9679. /**
  9680. * Checks whether a node is annotated as "disconnected", i.e. not present
  9681. * in the DOM at serialization time. We should not attempt hydration for
  9682. * such nodes and instead, use a regular "creation mode".
  9683. */
  9684. function isDisconnectedNode$1(hydrationInfo, index) {
  9685. // Check if we are processing disconnected info for the first time.
  9686. if (typeof hydrationInfo.disconnectedNodes === 'undefined') {
  9687. const nodeIds = hydrationInfo.data[DISCONNECTED_NODES];
  9688. hydrationInfo.disconnectedNodes = nodeIds ? new Set(nodeIds) : null;
  9689. }
  9690. return !!initDisconnectedNodes(hydrationInfo)?.has(index);
  9691. }
  9692. /**
  9693. * Helper function to prepare text nodes for serialization by ensuring
  9694. * that seperate logical text blocks in the DOM remain separate after
  9695. * serialization.
  9696. */
  9697. function processTextNodeBeforeSerialization(context, node) {
  9698. // Handle cases where text nodes can be lost after DOM serialization:
  9699. // 1. When there is an *empty text node* in DOM: in this case, this
  9700. // node would not make it into the serialized string and as a result,
  9701. // this node wouldn't be created in a browser. This would result in
  9702. // a mismatch during the hydration, where the runtime logic would expect
  9703. // a text node to be present in live DOM, but no text node would exist.
  9704. // Example: `<span>{{ name }}</span>` when the `name` is an empty string.
  9705. // This would result in `<span></span>` string after serialization and
  9706. // in a browser only the `span` element would be created. To resolve that,
  9707. // an extra comment node is appended in place of an empty text node and
  9708. // that special comment node is replaced with an empty text node *before*
  9709. // hydration.
  9710. // 2. When there are 2 consecutive text nodes present in the DOM.
  9711. // Example: `<div>Hello <ng-container *ngIf="true">world</ng-container></div>`.
  9712. // In this scenario, the live DOM would look like this:
  9713. // <div>#text('Hello ') #text('world') #comment('container')</div>
  9714. // Serialized string would look like this: `<div>Hello world<!--container--></div>`.
  9715. // The live DOM in a browser after that would be:
  9716. // <div>#text('Hello world') #comment('container')</div>
  9717. // Notice how 2 text nodes are now "merged" into one. This would cause hydration
  9718. // logic to fail, since it'd expect 2 text nodes being present, not one.
  9719. // To fix this, we insert a special comment node in between those text nodes, so
  9720. // serialized representation is: `<div>Hello <!--ngtns-->world<!--container--></div>`.
  9721. // This forces browser to create 2 text nodes separated by a comment node.
  9722. // Before running a hydration process, this special comment node is removed, so the
  9723. // live DOM has exactly the same state as it was before serialization.
  9724. // Collect this node as required special annotation only when its
  9725. // contents is empty. Otherwise, such text node would be present on
  9726. // the client after server-side rendering and no special handling needed.
  9727. const el = node;
  9728. const corruptedTextNodes = context.corruptedTextNodes;
  9729. if (el.textContent === '') {
  9730. corruptedTextNodes.set(el, "ngetn" /* TextNodeMarker.EmptyNode */);
  9731. }
  9732. else if (el.nextSibling?.nodeType === Node.TEXT_NODE) {
  9733. corruptedTextNodes.set(el, "ngtns" /* TextNodeMarker.Separator */);
  9734. }
  9735. }
  9736. function convertHydrateTriggersToJsAction(triggers) {
  9737. let actionList = [];
  9738. if (triggers !== null) {
  9739. if (triggers.has(4 /* DeferBlockTrigger.Hover */)) {
  9740. actionList.push(...hoverEventNames);
  9741. }
  9742. if (triggers.has(3 /* DeferBlockTrigger.Interaction */)) {
  9743. actionList.push(...interactionEventNames);
  9744. }
  9745. }
  9746. return actionList;
  9747. }
  9748. /**
  9749. * Builds a queue of blocks that need to be hydrated, looking up the
  9750. * tree to the topmost defer block that exists in the tree that hasn't
  9751. * been hydrated, but exists in the registry. This queue is in top down
  9752. * hierarchical order as a list of defer block ids.
  9753. * Note: This is utilizing serialized information to navigate up the tree
  9754. */
  9755. function getParentBlockHydrationQueue(deferBlockId, injector) {
  9756. const dehydratedBlockRegistry = injector.get(DEHYDRATED_BLOCK_REGISTRY);
  9757. const transferState = injector.get(TransferState);
  9758. const deferBlockParents = transferState.get(NGH_DEFER_BLOCKS_KEY, {});
  9759. let isTopMostDeferBlock = false;
  9760. let currentBlockId = deferBlockId;
  9761. let parentBlockPromise = null;
  9762. const hydrationQueue = [];
  9763. while (!isTopMostDeferBlock && currentBlockId) {
  9764. ngDevMode &&
  9765. assertEqual(hydrationQueue.indexOf(currentBlockId), -1, 'Internal error: defer block hierarchy has a cycle.');
  9766. isTopMostDeferBlock = dehydratedBlockRegistry.has(currentBlockId);
  9767. const hydratingParentBlock = dehydratedBlockRegistry.hydrating.get(currentBlockId);
  9768. if (parentBlockPromise === null && hydratingParentBlock != null) {
  9769. parentBlockPromise = hydratingParentBlock.promise;
  9770. break;
  9771. }
  9772. hydrationQueue.unshift(currentBlockId);
  9773. currentBlockId = deferBlockParents[currentBlockId][DEFER_PARENT_BLOCK_ID];
  9774. }
  9775. return { parentBlockPromise, hydrationQueue };
  9776. }
  9777. function gatherDeferBlocksByJSActionAttribute(doc) {
  9778. const jsactionNodes = doc.body.querySelectorAll('[jsaction]');
  9779. const blockMap = new Set();
  9780. for (let node of jsactionNodes) {
  9781. const attr = node.getAttribute('jsaction');
  9782. const blockId = node.getAttribute('ngb');
  9783. const eventTypes = [...hoverEventNames.join(':;'), ...interactionEventNames.join(':;')].join('|');
  9784. if (attr?.match(eventTypes) && blockId !== null) {
  9785. blockMap.add(node);
  9786. }
  9787. }
  9788. return blockMap;
  9789. }
  9790. function appendDeferBlocksToJSActionMap(doc, injector) {
  9791. const blockMap = gatherDeferBlocksByJSActionAttribute(doc);
  9792. for (let rNode of blockMap) {
  9793. const jsActionMap = injector.get(JSACTION_BLOCK_ELEMENT_MAP);
  9794. sharedMapFunction(rNode, jsActionMap);
  9795. }
  9796. }
  9797. /**
  9798. * Retrieves defer block hydration information from the TransferState.
  9799. *
  9800. * @param injector Injector that this component has access to.
  9801. */
  9802. let _retrieveDeferBlockDataImpl = () => {
  9803. return {};
  9804. };
  9805. function retrieveDeferBlockDataImpl(injector) {
  9806. const transferState = injector.get(TransferState, null, { optional: true });
  9807. if (transferState !== null) {
  9808. const nghDeferData = transferState.get(NGH_DEFER_BLOCKS_KEY, {});
  9809. ngDevMode &&
  9810. assertDefined(nghDeferData, 'Unable to retrieve defer block info from the TransferState.');
  9811. return nghDeferData;
  9812. }
  9813. return {};
  9814. }
  9815. /**
  9816. * Sets the implementation for the `retrieveDeferBlockData` function.
  9817. */
  9818. function enableRetrieveDeferBlockDataImpl() {
  9819. _retrieveDeferBlockDataImpl = retrieveDeferBlockDataImpl;
  9820. }
  9821. /**
  9822. * Retrieves defer block data from TransferState storage
  9823. */
  9824. function retrieveDeferBlockData(injector) {
  9825. return _retrieveDeferBlockDataImpl(injector);
  9826. }
  9827. function isTimerTrigger(triggerInfo) {
  9828. return typeof triggerInfo === 'object' && triggerInfo.trigger === 5 /* DeferBlockTrigger.Timer */;
  9829. }
  9830. function getHydrateTimerTrigger(blockData) {
  9831. const trigger = blockData[DEFER_HYDRATE_TRIGGERS]?.find((t) => isTimerTrigger(t));
  9832. return trigger?.delay ?? null;
  9833. }
  9834. function hasHydrateTrigger(blockData, trigger) {
  9835. return blockData[DEFER_HYDRATE_TRIGGERS]?.includes(trigger) ?? false;
  9836. }
  9837. /**
  9838. * Creates a summary of the given serialized defer block, which is used later to properly initialize
  9839. * specific triggers.
  9840. */
  9841. function createBlockSummary(blockInfo) {
  9842. return {
  9843. data: blockInfo,
  9844. hydrate: {
  9845. idle: hasHydrateTrigger(blockInfo, 0 /* DeferBlockTrigger.Idle */),
  9846. immediate: hasHydrateTrigger(blockInfo, 1 /* DeferBlockTrigger.Immediate */),
  9847. timer: getHydrateTimerTrigger(blockInfo),
  9848. viewport: hasHydrateTrigger(blockInfo, 2 /* DeferBlockTrigger.Viewport */),
  9849. },
  9850. };
  9851. }
  9852. /**
  9853. * Processes all of the defer block data in the transfer state and creates a map of the summaries
  9854. */
  9855. function processBlockData(injector) {
  9856. const blockData = retrieveDeferBlockData(injector);
  9857. let blockDetails = new Map();
  9858. for (let blockId in blockData) {
  9859. blockDetails.set(blockId, createBlockSummary(blockData[blockId]));
  9860. }
  9861. return blockDetails;
  9862. }
  9863. function isSsrContentsIntegrity(node) {
  9864. return (!!node &&
  9865. node.nodeType === Node.COMMENT_NODE &&
  9866. node.textContent?.trim() === SSR_CONTENT_INTEGRITY_MARKER);
  9867. }
  9868. function skipTextNodes(node) {
  9869. // Ignore whitespace. Before the <body>, we shouldn't find text nodes that aren't whitespace.
  9870. while (node && node.nodeType === Node.TEXT_NODE) {
  9871. node = node.previousSibling;
  9872. }
  9873. return node;
  9874. }
  9875. /**
  9876. * Verifies whether the DOM contains a special marker added during SSR time to make sure
  9877. * there is no SSR'ed contents transformations happen after SSR is completed. Typically that
  9878. * happens either by CDN or during the build process as an optimization to remove comment nodes.
  9879. * Hydration process requires comment nodes produced by Angular to locate correct DOM segments.
  9880. * When this special marker is *not* present - throw an error and do not proceed with hydration,
  9881. * since it will not be able to function correctly.
  9882. *
  9883. * Note: this function is invoked only on the client, so it's safe to use DOM APIs.
  9884. */
  9885. function verifySsrContentsIntegrity(doc) {
  9886. for (const node of doc.body.childNodes) {
  9887. if (isSsrContentsIntegrity(node)) {
  9888. return;
  9889. }
  9890. }
  9891. // Check if the HTML parser may have moved the marker to just before the <body> tag,
  9892. // e.g. because the body tag was implicit and not present in the markup. An implicit body
  9893. // tag is unlikely to interfer with whitespace/comments inside of the app's root element.
  9894. // Case 1: Implicit body. Example:
  9895. // <!doctype html><head><title>Hi</title></head><!--nghm--><app-root></app-root>
  9896. const beforeBody = skipTextNodes(doc.body.previousSibling);
  9897. if (isSsrContentsIntegrity(beforeBody)) {
  9898. return;
  9899. }
  9900. // Case 2: Implicit body & head. Example:
  9901. // <!doctype html><head><title>Hi</title><!--nghm--><app-root></app-root>
  9902. let endOfHead = skipTextNodes(doc.head.lastChild);
  9903. if (isSsrContentsIntegrity(endOfHead)) {
  9904. return;
  9905. }
  9906. throw new RuntimeError(-507 /* RuntimeErrorCode.MISSING_SSR_CONTENT_INTEGRITY_MARKER */, typeof ngDevMode !== 'undefined' &&
  9907. ngDevMode &&
  9908. 'Angular hydration logic detected that HTML content of this page was modified after it ' +
  9909. 'was produced during server side rendering. Make sure that there are no optimizations ' +
  9910. 'that remove comment nodes from HTML enabled on your CDN. Angular hydration ' +
  9911. 'relies on HTML produced by the server, including whitespaces and comment nodes.');
  9912. }
  9913. /** Refreshes all content queries declared by directives in a given view */
  9914. function refreshContentQueries(tView, lView) {
  9915. const contentQueries = tView.contentQueries;
  9916. if (contentQueries !== null) {
  9917. const prevConsumer = setActiveConsumer$1(null);
  9918. try {
  9919. for (let i = 0; i < contentQueries.length; i += 2) {
  9920. const queryStartIdx = contentQueries[i];
  9921. const directiveDefIdx = contentQueries[i + 1];
  9922. if (directiveDefIdx !== -1) {
  9923. const directiveDef = tView.data[directiveDefIdx];
  9924. ngDevMode && assertDefined(directiveDef, 'DirectiveDef not found.');
  9925. ngDevMode &&
  9926. assertDefined(directiveDef.contentQueries, 'contentQueries function should be defined');
  9927. setCurrentQueryIndex(queryStartIdx);
  9928. directiveDef.contentQueries(2 /* RenderFlags.Update */, lView[directiveDefIdx], directiveDefIdx);
  9929. }
  9930. }
  9931. }
  9932. finally {
  9933. setActiveConsumer$1(prevConsumer);
  9934. }
  9935. }
  9936. }
  9937. function executeViewQueryFn(flags, viewQueryFn, component) {
  9938. ngDevMode && assertDefined(viewQueryFn, 'View queries function to execute must be defined.');
  9939. setCurrentQueryIndex(0);
  9940. const prevConsumer = setActiveConsumer$1(null);
  9941. try {
  9942. viewQueryFn(flags, component);
  9943. }
  9944. finally {
  9945. setActiveConsumer$1(prevConsumer);
  9946. }
  9947. }
  9948. function executeContentQueries(tView, tNode, lView) {
  9949. if (isContentQueryHost(tNode)) {
  9950. const prevConsumer = setActiveConsumer$1(null);
  9951. try {
  9952. const start = tNode.directiveStart;
  9953. const end = tNode.directiveEnd;
  9954. for (let directiveIndex = start; directiveIndex < end; directiveIndex++) {
  9955. const def = tView.data[directiveIndex];
  9956. if (def.contentQueries) {
  9957. const directiveInstance = lView[directiveIndex];
  9958. ngDevMode &&
  9959. assertDefined(directiveIndex, 'Incorrect reference to a directive defining a content query');
  9960. def.contentQueries(1 /* RenderFlags.Create */, directiveInstance, directiveIndex);
  9961. }
  9962. }
  9963. }
  9964. finally {
  9965. setActiveConsumer$1(prevConsumer);
  9966. }
  9967. }
  9968. }
  9969. /**
  9970. * Defines the CSS styles encapsulation policies for the {@link /api/core/Component Component} decorator's
  9971. * `encapsulation` option.
  9972. *
  9973. * See {@link Component#encapsulation encapsulation}.
  9974. *
  9975. * @usageNotes
  9976. * ### Example
  9977. *
  9978. * {@example core/ts/metadata/encapsulation.ts region='longform'}
  9979. *
  9980. * @publicApi
  9981. */
  9982. var ViewEncapsulation;
  9983. (function (ViewEncapsulation) {
  9984. // TODO: consider making `ViewEncapsulation` a `const enum` instead. See
  9985. // https://github.com/angular/angular/issues/44119 for additional information.
  9986. /**
  9987. * Emulates a native Shadow DOM encapsulation behavior by adding a specific attribute to the
  9988. * component's host element and applying the same attribute to all the CSS selectors provided
  9989. * via {@link Component#styles styles} or {@link Component#styleUrls styleUrls}.
  9990. *
  9991. * This is the default option.
  9992. */
  9993. ViewEncapsulation[ViewEncapsulation["Emulated"] = 0] = "Emulated";
  9994. // Historically the 1 value was for `Native` encapsulation which has been removed as of v11.
  9995. /**
  9996. * Doesn't provide any sort of CSS style encapsulation, meaning that all the styles provided
  9997. * via {@link Component#styles styles} or {@link Component#styleUrls styleUrls} are applicable
  9998. * to any HTML element of the application regardless of their host Component.
  9999. */
  10000. ViewEncapsulation[ViewEncapsulation["None"] = 2] = "None";
  10001. /**
  10002. * Uses the browser's native Shadow DOM API to encapsulate CSS styles, meaning that it creates
  10003. * a ShadowRoot for the component's host element which is then used to encapsulate
  10004. * all the Component's styling.
  10005. */
  10006. ViewEncapsulation[ViewEncapsulation["ShadowDom"] = 3] = "ShadowDom";
  10007. })(ViewEncapsulation || (ViewEncapsulation = {}));
  10008. /**
  10009. * @fileoverview
  10010. * A module to facilitate use of a Trusted Types policy internally within
  10011. * Angular. It lazily constructs the Trusted Types policy, providing helper
  10012. * utilities for promoting strings to Trusted Types. When Trusted Types are not
  10013. * available, strings are used as a fallback.
  10014. * @security All use of this module is security-sensitive and should go through
  10015. * security review.
  10016. */
  10017. /**
  10018. * The Trusted Types policy, or null if Trusted Types are not
  10019. * enabled/supported, or undefined if the policy has not been created yet.
  10020. */
  10021. let policy$1;
  10022. /**
  10023. * Returns the Trusted Types policy, or null if Trusted Types are not
  10024. * enabled/supported. The first call to this function will create the policy.
  10025. */
  10026. function getPolicy$1() {
  10027. if (policy$1 === undefined) {
  10028. policy$1 = null;
  10029. if (_global.trustedTypes) {
  10030. try {
  10031. policy$1 = _global.trustedTypes.createPolicy('angular', {
  10032. createHTML: (s) => s,
  10033. createScript: (s) => s,
  10034. createScriptURL: (s) => s,
  10035. });
  10036. }
  10037. catch {
  10038. // trustedTypes.createPolicy throws if called with a name that is
  10039. // already registered, even in report-only mode. Until the API changes,
  10040. // catch the error not to break the applications functionally. In such
  10041. // cases, the code will fall back to using strings.
  10042. }
  10043. }
  10044. }
  10045. return policy$1;
  10046. }
  10047. /**
  10048. * Unsafely promote a string to a TrustedHTML, falling back to strings when
  10049. * Trusted Types are not available.
  10050. * @security This is a security-sensitive function; any use of this function
  10051. * must go through security review. In particular, it must be assured that the
  10052. * provided string will never cause an XSS vulnerability if used in a context
  10053. * that will be interpreted as HTML by a browser, e.g. when assigning to
  10054. * element.innerHTML.
  10055. */
  10056. function trustedHTMLFromString(html) {
  10057. return getPolicy$1()?.createHTML(html) || html;
  10058. }
  10059. /**
  10060. * Unsafely promote a string to a TrustedScriptURL, falling back to strings
  10061. * when Trusted Types are not available.
  10062. * @security This is a security-sensitive function; any use of this function
  10063. * must go through security review. In particular, it must be assured that the
  10064. * provided string will never cause an XSS vulnerability if used in a context
  10065. * that will cause a browser to load and execute a resource, e.g. when
  10066. * assigning to script.src.
  10067. */
  10068. function trustedScriptURLFromString(url) {
  10069. return getPolicy$1()?.createScriptURL(url) || url;
  10070. }
  10071. /**
  10072. * @fileoverview
  10073. * A module to facilitate use of a Trusted Types policy internally within
  10074. * Angular specifically for bypassSecurityTrust* and custom sanitizers. It
  10075. * lazily constructs the Trusted Types policy, providing helper utilities for
  10076. * promoting strings to Trusted Types. When Trusted Types are not available,
  10077. * strings are used as a fallback.
  10078. * @security All use of this module is security-sensitive and should go through
  10079. * security review.
  10080. */
  10081. /**
  10082. * The Trusted Types policy, or null if Trusted Types are not
  10083. * enabled/supported, or undefined if the policy has not been created yet.
  10084. */
  10085. let policy;
  10086. /**
  10087. * Returns the Trusted Types policy, or null if Trusted Types are not
  10088. * enabled/supported. The first call to this function will create the policy.
  10089. */
  10090. function getPolicy() {
  10091. if (policy === undefined) {
  10092. policy = null;
  10093. if (_global.trustedTypes) {
  10094. try {
  10095. policy = _global.trustedTypes.createPolicy('angular#unsafe-bypass', {
  10096. createHTML: (s) => s,
  10097. createScript: (s) => s,
  10098. createScriptURL: (s) => s,
  10099. });
  10100. }
  10101. catch {
  10102. // trustedTypes.createPolicy throws if called with a name that is
  10103. // already registered, even in report-only mode. Until the API changes,
  10104. // catch the error not to break the applications functionally. In such
  10105. // cases, the code will fall back to using strings.
  10106. }
  10107. }
  10108. }
  10109. return policy;
  10110. }
  10111. /**
  10112. * Unsafely promote a string to a TrustedHTML, falling back to strings when
  10113. * Trusted Types are not available.
  10114. * @security This is a security-sensitive function; any use of this function
  10115. * must go through security review. In particular, it must be assured that it
  10116. * is only passed strings that come directly from custom sanitizers or the
  10117. * bypassSecurityTrust* functions.
  10118. */
  10119. function trustedHTMLFromStringBypass(html) {
  10120. return getPolicy()?.createHTML(html) || html;
  10121. }
  10122. /**
  10123. * Unsafely promote a string to a TrustedScript, falling back to strings when
  10124. * Trusted Types are not available.
  10125. * @security This is a security-sensitive function; any use of this function
  10126. * must go through security review. In particular, it must be assured that it
  10127. * is only passed strings that come directly from custom sanitizers or the
  10128. * bypassSecurityTrust* functions.
  10129. */
  10130. function trustedScriptFromStringBypass(script) {
  10131. return getPolicy()?.createScript(script) || script;
  10132. }
  10133. /**
  10134. * Unsafely promote a string to a TrustedScriptURL, falling back to strings
  10135. * when Trusted Types are not available.
  10136. * @security This is a security-sensitive function; any use of this function
  10137. * must go through security review. In particular, it must be assured that it
  10138. * is only passed strings that come directly from custom sanitizers or the
  10139. * bypassSecurityTrust* functions.
  10140. */
  10141. function trustedScriptURLFromStringBypass(url) {
  10142. return getPolicy()?.createScriptURL(url) || url;
  10143. }
  10144. class SafeValueImpl {
  10145. changingThisBreaksApplicationSecurity;
  10146. constructor(changingThisBreaksApplicationSecurity) {
  10147. this.changingThisBreaksApplicationSecurity = changingThisBreaksApplicationSecurity;
  10148. }
  10149. toString() {
  10150. return (`SafeValue must use [property]=binding: ${this.changingThisBreaksApplicationSecurity}` +
  10151. ` (see ${XSS_SECURITY_URL})`);
  10152. }
  10153. }
  10154. class SafeHtmlImpl extends SafeValueImpl {
  10155. getTypeName() {
  10156. return "HTML" /* BypassType.Html */;
  10157. }
  10158. }
  10159. class SafeStyleImpl extends SafeValueImpl {
  10160. getTypeName() {
  10161. return "Style" /* BypassType.Style */;
  10162. }
  10163. }
  10164. class SafeScriptImpl extends SafeValueImpl {
  10165. getTypeName() {
  10166. return "Script" /* BypassType.Script */;
  10167. }
  10168. }
  10169. class SafeUrlImpl extends SafeValueImpl {
  10170. getTypeName() {
  10171. return "URL" /* BypassType.Url */;
  10172. }
  10173. }
  10174. class SafeResourceUrlImpl extends SafeValueImpl {
  10175. getTypeName() {
  10176. return "ResourceURL" /* BypassType.ResourceUrl */;
  10177. }
  10178. }
  10179. function unwrapSafeValue(value) {
  10180. return value instanceof SafeValueImpl
  10181. ? value.changingThisBreaksApplicationSecurity
  10182. : value;
  10183. }
  10184. function allowSanitizationBypassAndThrow(value, type) {
  10185. const actualType = getSanitizationBypassType(value);
  10186. if (actualType != null && actualType !== type) {
  10187. // Allow ResourceURLs in URL contexts, they are strictly more trusted.
  10188. if (actualType === "ResourceURL" /* BypassType.ResourceUrl */ && type === "URL" /* BypassType.Url */)
  10189. return true;
  10190. throw new Error(`Required a safe ${type}, got a ${actualType} (see ${XSS_SECURITY_URL})`);
  10191. }
  10192. return actualType === type;
  10193. }
  10194. function getSanitizationBypassType(value) {
  10195. return (value instanceof SafeValueImpl && value.getTypeName()) || null;
  10196. }
  10197. /**
  10198. * Mark `html` string as trusted.
  10199. *
  10200. * This function wraps the trusted string in `String` and brands it in a way which makes it
  10201. * recognizable to {@link htmlSanitizer} to be trusted implicitly.
  10202. *
  10203. * @param trustedHtml `html` string which needs to be implicitly trusted.
  10204. * @returns a `html` which has been branded to be implicitly trusted.
  10205. */
  10206. function bypassSanitizationTrustHtml(trustedHtml) {
  10207. return new SafeHtmlImpl(trustedHtml);
  10208. }
  10209. /**
  10210. * Mark `style` string as trusted.
  10211. *
  10212. * This function wraps the trusted string in `String` and brands it in a way which makes it
  10213. * recognizable to {@link styleSanitizer} to be trusted implicitly.
  10214. *
  10215. * @param trustedStyle `style` string which needs to be implicitly trusted.
  10216. * @returns a `style` hich has been branded to be implicitly trusted.
  10217. */
  10218. function bypassSanitizationTrustStyle(trustedStyle) {
  10219. return new SafeStyleImpl(trustedStyle);
  10220. }
  10221. /**
  10222. * Mark `script` string as trusted.
  10223. *
  10224. * This function wraps the trusted string in `String` and brands it in a way which makes it
  10225. * recognizable to {@link scriptSanitizer} to be trusted implicitly.
  10226. *
  10227. * @param trustedScript `script` string which needs to be implicitly trusted.
  10228. * @returns a `script` which has been branded to be implicitly trusted.
  10229. */
  10230. function bypassSanitizationTrustScript(trustedScript) {
  10231. return new SafeScriptImpl(trustedScript);
  10232. }
  10233. /**
  10234. * Mark `url` string as trusted.
  10235. *
  10236. * This function wraps the trusted string in `String` and brands it in a way which makes it
  10237. * recognizable to {@link urlSanitizer} to be trusted implicitly.
  10238. *
  10239. * @param trustedUrl `url` string which needs to be implicitly trusted.
  10240. * @returns a `url` which has been branded to be implicitly trusted.
  10241. */
  10242. function bypassSanitizationTrustUrl(trustedUrl) {
  10243. return new SafeUrlImpl(trustedUrl);
  10244. }
  10245. /**
  10246. * Mark `url` string as trusted.
  10247. *
  10248. * This function wraps the trusted string in `String` and brands it in a way which makes it
  10249. * recognizable to {@link resourceUrlSanitizer} to be trusted implicitly.
  10250. *
  10251. * @param trustedResourceUrl `url` string which needs to be implicitly trusted.
  10252. * @returns a `url` which has been branded to be implicitly trusted.
  10253. */
  10254. function bypassSanitizationTrustResourceUrl(trustedResourceUrl) {
  10255. return new SafeResourceUrlImpl(trustedResourceUrl);
  10256. }
  10257. /**
  10258. * This helper is used to get hold of an inert tree of DOM elements containing dirty HTML
  10259. * that needs sanitizing.
  10260. * Depending upon browser support we use one of two strategies for doing this.
  10261. * Default: DOMParser strategy
  10262. * Fallback: InertDocument strategy
  10263. */
  10264. function getInertBodyHelper(defaultDoc) {
  10265. const inertDocumentHelper = new InertDocumentHelper(defaultDoc);
  10266. return isDOMParserAvailable() ? new DOMParserHelper(inertDocumentHelper) : inertDocumentHelper;
  10267. }
  10268. /**
  10269. * Uses DOMParser to create and fill an inert body element.
  10270. * This is the default strategy used in browsers that support it.
  10271. */
  10272. class DOMParserHelper {
  10273. inertDocumentHelper;
  10274. constructor(inertDocumentHelper) {
  10275. this.inertDocumentHelper = inertDocumentHelper;
  10276. }
  10277. getInertBodyElement(html) {
  10278. // We add these extra elements to ensure that the rest of the content is parsed as expected
  10279. // e.g. leading whitespace is maintained and tags like `<meta>` do not get hoisted to the
  10280. // `<head>` tag. Note that the `<body>` tag is closed implicitly to prevent unclosed tags
  10281. // in `html` from consuming the otherwise explicit `</body>` tag.
  10282. html = '<body><remove></remove>' + html;
  10283. try {
  10284. const body = new window.DOMParser().parseFromString(trustedHTMLFromString(html), 'text/html').body;
  10285. if (body === null) {
  10286. // In some browsers (e.g. Mozilla/5.0 iPad AppleWebKit Mobile) the `body` property only
  10287. // becomes available in the following tick of the JS engine. In that case we fall back to
  10288. // the `inertDocumentHelper` instead.
  10289. return this.inertDocumentHelper.getInertBodyElement(html);
  10290. }
  10291. body.firstChild?.remove();
  10292. return body;
  10293. }
  10294. catch {
  10295. return null;
  10296. }
  10297. }
  10298. }
  10299. /**
  10300. * Use an HTML5 `template` element to create and fill an inert DOM element.
  10301. * This is the fallback strategy if the browser does not support DOMParser.
  10302. */
  10303. class InertDocumentHelper {
  10304. defaultDoc;
  10305. inertDocument;
  10306. constructor(defaultDoc) {
  10307. this.defaultDoc = defaultDoc;
  10308. this.inertDocument = this.defaultDoc.implementation.createHTMLDocument('sanitization-inert');
  10309. }
  10310. getInertBodyElement(html) {
  10311. const templateEl = this.inertDocument.createElement('template');
  10312. templateEl.innerHTML = trustedHTMLFromString(html);
  10313. return templateEl;
  10314. }
  10315. }
  10316. /**
  10317. * We need to determine whether the DOMParser exists in the global context and
  10318. * supports parsing HTML; HTML parsing support is not as wide as other formats, see
  10319. * https://developer.mozilla.org/en-US/docs/Web/API/DOMParser#Browser_compatibility.
  10320. *
  10321. * @suppress {uselessCode}
  10322. */
  10323. function isDOMParserAvailable() {
  10324. try {
  10325. return !!new window.DOMParser().parseFromString(trustedHTMLFromString(''), 'text/html');
  10326. }
  10327. catch {
  10328. return false;
  10329. }
  10330. }
  10331. /**
  10332. * A pattern that recognizes URLs that are safe wrt. XSS in URL navigation
  10333. * contexts.
  10334. *
  10335. * This regular expression matches a subset of URLs that will not cause script
  10336. * execution if used in URL context within a HTML document. Specifically, this
  10337. * regular expression matches if:
  10338. * (1) Either a protocol that is not javascript:, and that has valid characters
  10339. * (alphanumeric or [+-.]).
  10340. * (2) or no protocol. A protocol must be followed by a colon. The below
  10341. * allows that by allowing colons only after one of the characters [/?#].
  10342. * A colon after a hash (#) must be in the fragment.
  10343. * Otherwise, a colon after a (?) must be in a query.
  10344. * Otherwise, a colon after a single solidus (/) must be in a path.
  10345. * Otherwise, a colon after a double solidus (//) must be in the authority
  10346. * (before port).
  10347. *
  10348. * The pattern disallows &, used in HTML entity declarations before
  10349. * one of the characters in [/?#]. This disallows HTML entities used in the
  10350. * protocol name, which should never happen, e.g. "h&#116;tp" for "http".
  10351. * It also disallows HTML entities in the first path part of a relative path,
  10352. * e.g. "foo&lt;bar/baz". Our existing escaping functions should not produce
  10353. * that. More importantly, it disallows masking of a colon,
  10354. * e.g. "javascript&#58;...".
  10355. *
  10356. * This regular expression was taken from the Closure sanitization library.
  10357. */
  10358. const SAFE_URL_PATTERN = /^(?!javascript:)(?:[a-z0-9+.-]+:|[^&:\/?#]*(?:[\/?#]|$))/i;
  10359. function _sanitizeUrl(url) {
  10360. url = String(url);
  10361. if (url.match(SAFE_URL_PATTERN))
  10362. return url;
  10363. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  10364. console.warn(`WARNING: sanitizing unsafe URL value ${url} (see ${XSS_SECURITY_URL})`);
  10365. }
  10366. return 'unsafe:' + url;
  10367. }
  10368. function tagSet(tags) {
  10369. const res = {};
  10370. for (const t of tags.split(','))
  10371. res[t] = true;
  10372. return res;
  10373. }
  10374. function merge(...sets) {
  10375. const res = {};
  10376. for (const s of sets) {
  10377. for (const v in s) {
  10378. if (s.hasOwnProperty(v))
  10379. res[v] = true;
  10380. }
  10381. }
  10382. return res;
  10383. }
  10384. // Good source of info about elements and attributes
  10385. // https://html.spec.whatwg.org/#semantics
  10386. // https://simon.html5.org/html-elements
  10387. // Safe Void Elements - HTML5
  10388. // https://html.spec.whatwg.org/#void-elements
  10389. const VOID_ELEMENTS = tagSet('area,br,col,hr,img,wbr');
  10390. // Elements that you can, intentionally, leave open (and which close themselves)
  10391. // https://html.spec.whatwg.org/#optional-tags
  10392. const OPTIONAL_END_TAG_BLOCK_ELEMENTS = tagSet('colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr');
  10393. const OPTIONAL_END_TAG_INLINE_ELEMENTS = tagSet('rp,rt');
  10394. const OPTIONAL_END_TAG_ELEMENTS = merge(OPTIONAL_END_TAG_INLINE_ELEMENTS, OPTIONAL_END_TAG_BLOCK_ELEMENTS);
  10395. // Safe Block Elements - HTML5
  10396. const BLOCK_ELEMENTS = merge(OPTIONAL_END_TAG_BLOCK_ELEMENTS, tagSet('address,article,' +
  10397. 'aside,blockquote,caption,center,del,details,dialog,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,' +
  10398. 'h6,header,hgroup,hr,ins,main,map,menu,nav,ol,pre,section,summary,table,ul'));
  10399. // Inline Elements - HTML5
  10400. const INLINE_ELEMENTS = merge(OPTIONAL_END_TAG_INLINE_ELEMENTS, tagSet('a,abbr,acronym,audio,b,' +
  10401. 'bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,picture,q,ruby,rp,rt,s,' +
  10402. 'samp,small,source,span,strike,strong,sub,sup,time,track,tt,u,var,video'));
  10403. const VALID_ELEMENTS = merge(VOID_ELEMENTS, BLOCK_ELEMENTS, INLINE_ELEMENTS, OPTIONAL_END_TAG_ELEMENTS);
  10404. // Attributes that have href and hence need to be sanitized
  10405. const URI_ATTRS = tagSet('background,cite,href,itemtype,longdesc,poster,src,xlink:href');
  10406. const HTML_ATTRS = tagSet('abbr,accesskey,align,alt,autoplay,axis,bgcolor,border,cellpadding,cellspacing,class,clear,color,cols,colspan,' +
  10407. 'compact,controls,coords,datetime,default,dir,download,face,headers,height,hidden,hreflang,hspace,' +
  10408. 'ismap,itemscope,itemprop,kind,label,lang,language,loop,media,muted,nohref,nowrap,open,preload,rel,rev,role,rows,rowspan,rules,' +
  10409. 'scope,scrolling,shape,size,sizes,span,srclang,srcset,start,summary,tabindex,target,title,translate,type,usemap,' +
  10410. 'valign,value,vspace,width');
  10411. // Accessibility attributes as per WAI-ARIA 1.1 (W3C Working Draft 14 December 2018)
  10412. const ARIA_ATTRS = tagSet('aria-activedescendant,aria-atomic,aria-autocomplete,aria-busy,aria-checked,aria-colcount,aria-colindex,' +
  10413. 'aria-colspan,aria-controls,aria-current,aria-describedby,aria-details,aria-disabled,aria-dropeffect,' +
  10414. 'aria-errormessage,aria-expanded,aria-flowto,aria-grabbed,aria-haspopup,aria-hidden,aria-invalid,' +
  10415. 'aria-keyshortcuts,aria-label,aria-labelledby,aria-level,aria-live,aria-modal,aria-multiline,' +
  10416. 'aria-multiselectable,aria-orientation,aria-owns,aria-placeholder,aria-posinset,aria-pressed,aria-readonly,' +
  10417. 'aria-relevant,aria-required,aria-roledescription,aria-rowcount,aria-rowindex,aria-rowspan,aria-selected,' +
  10418. 'aria-setsize,aria-sort,aria-valuemax,aria-valuemin,aria-valuenow,aria-valuetext');
  10419. // NB: This currently consciously doesn't support SVG. SVG sanitization has had several security
  10420. // issues in the past, so it seems safer to leave it out if possible. If support for binding SVG via
  10421. // innerHTML is required, SVG attributes should be added here.
  10422. // NB: Sanitization does not allow <form> elements or other active elements (<button> etc). Those
  10423. // can be sanitized, but they increase security surface area without a legitimate use case, so they
  10424. // are left out here.
  10425. const VALID_ATTRS = merge(URI_ATTRS, HTML_ATTRS, ARIA_ATTRS);
  10426. // Elements whose content should not be traversed/preserved, if the elements themselves are invalid.
  10427. //
  10428. // Typically, `<invalid>Some content</invalid>` would traverse (and in this case preserve)
  10429. // `Some content`, but strip `invalid-element` opening/closing tags. For some elements, though, we
  10430. // don't want to preserve the content, if the elements themselves are going to be removed.
  10431. const SKIP_TRAVERSING_CONTENT_IF_INVALID_ELEMENTS = tagSet('script,style,template');
  10432. /**
  10433. * SanitizingHtmlSerializer serializes a DOM fragment, stripping out any unsafe elements and unsafe
  10434. * attributes.
  10435. */
  10436. class SanitizingHtmlSerializer {
  10437. // Explicitly track if something was stripped, to avoid accidentally warning of sanitization just
  10438. // because characters were re-encoded.
  10439. sanitizedSomething = false;
  10440. buf = [];
  10441. sanitizeChildren(el) {
  10442. // This cannot use a TreeWalker, as it has to run on Angular's various DOM adapters.
  10443. // However this code never accesses properties off of `document` before deleting its contents
  10444. // again, so it shouldn't be vulnerable to DOM clobbering.
  10445. let current = el.firstChild;
  10446. let traverseContent = true;
  10447. let parentNodes = [];
  10448. while (current) {
  10449. if (current.nodeType === Node.ELEMENT_NODE) {
  10450. traverseContent = this.startElement(current);
  10451. }
  10452. else if (current.nodeType === Node.TEXT_NODE) {
  10453. this.chars(current.nodeValue);
  10454. }
  10455. else {
  10456. // Strip non-element, non-text nodes.
  10457. this.sanitizedSomething = true;
  10458. }
  10459. if (traverseContent && current.firstChild) {
  10460. // Push current node to the parent stack before entering its content.
  10461. parentNodes.push(current);
  10462. current = getFirstChild(current);
  10463. continue;
  10464. }
  10465. while (current) {
  10466. // Leaving the element.
  10467. // Walk up and to the right, closing tags as we go.
  10468. if (current.nodeType === Node.ELEMENT_NODE) {
  10469. this.endElement(current);
  10470. }
  10471. let next = getNextSibling(current);
  10472. if (next) {
  10473. current = next;
  10474. break;
  10475. }
  10476. // There was no next sibling, walk up to the parent node (extract it from the stack).
  10477. current = parentNodes.pop();
  10478. }
  10479. }
  10480. return this.buf.join('');
  10481. }
  10482. /**
  10483. * Sanitizes an opening element tag (if valid) and returns whether the element's contents should
  10484. * be traversed. Element content must always be traversed (even if the element itself is not
  10485. * valid/safe), unless the element is one of `SKIP_TRAVERSING_CONTENT_IF_INVALID_ELEMENTS`.
  10486. *
  10487. * @param element The element to sanitize.
  10488. * @return True if the element's contents should be traversed.
  10489. */
  10490. startElement(element) {
  10491. const tagName = getNodeName(element).toLowerCase();
  10492. if (!VALID_ELEMENTS.hasOwnProperty(tagName)) {
  10493. this.sanitizedSomething = true;
  10494. return !SKIP_TRAVERSING_CONTENT_IF_INVALID_ELEMENTS.hasOwnProperty(tagName);
  10495. }
  10496. this.buf.push('<');
  10497. this.buf.push(tagName);
  10498. const elAttrs = element.attributes;
  10499. for (let i = 0; i < elAttrs.length; i++) {
  10500. const elAttr = elAttrs.item(i);
  10501. const attrName = elAttr.name;
  10502. const lower = attrName.toLowerCase();
  10503. if (!VALID_ATTRS.hasOwnProperty(lower)) {
  10504. this.sanitizedSomething = true;
  10505. continue;
  10506. }
  10507. let value = elAttr.value;
  10508. // TODO(martinprobst): Special case image URIs for data:image/...
  10509. if (URI_ATTRS[lower])
  10510. value = _sanitizeUrl(value);
  10511. this.buf.push(' ', attrName, '="', encodeEntities(value), '"');
  10512. }
  10513. this.buf.push('>');
  10514. return true;
  10515. }
  10516. endElement(current) {
  10517. const tagName = getNodeName(current).toLowerCase();
  10518. if (VALID_ELEMENTS.hasOwnProperty(tagName) && !VOID_ELEMENTS.hasOwnProperty(tagName)) {
  10519. this.buf.push('</');
  10520. this.buf.push(tagName);
  10521. this.buf.push('>');
  10522. }
  10523. }
  10524. chars(chars) {
  10525. this.buf.push(encodeEntities(chars));
  10526. }
  10527. }
  10528. /**
  10529. * Verifies whether a given child node is a descendant of a given parent node.
  10530. * It may not be the case when properties like `.firstChild` are clobbered and
  10531. * accessing `.firstChild` results in an unexpected node returned.
  10532. */
  10533. function isClobberedElement(parentNode, childNode) {
  10534. return ((parentNode.compareDocumentPosition(childNode) & Node.DOCUMENT_POSITION_CONTAINED_BY) !==
  10535. Node.DOCUMENT_POSITION_CONTAINED_BY);
  10536. }
  10537. /**
  10538. * Retrieves next sibling node and makes sure that there is no
  10539. * clobbering of the `nextSibling` property happening.
  10540. */
  10541. function getNextSibling(node) {
  10542. const nextSibling = node.nextSibling;
  10543. // Make sure there is no `nextSibling` clobbering: navigating to
  10544. // the next sibling and going back to the previous one should result
  10545. // in the original node.
  10546. if (nextSibling && node !== nextSibling.previousSibling) {
  10547. throw clobberedElementError(nextSibling);
  10548. }
  10549. return nextSibling;
  10550. }
  10551. /**
  10552. * Retrieves first child node and makes sure that there is no
  10553. * clobbering of the `firstChild` property happening.
  10554. */
  10555. function getFirstChild(node) {
  10556. const firstChild = node.firstChild;
  10557. if (firstChild && isClobberedElement(node, firstChild)) {
  10558. throw clobberedElementError(firstChild);
  10559. }
  10560. return firstChild;
  10561. }
  10562. /** Gets a reasonable nodeName, even for clobbered nodes. */
  10563. function getNodeName(node) {
  10564. const nodeName = node.nodeName;
  10565. // If the property is clobbered, assume it is an `HTMLFormElement`.
  10566. return typeof nodeName === 'string' ? nodeName : 'FORM';
  10567. }
  10568. function clobberedElementError(node) {
  10569. return new Error(`Failed to sanitize html because the element is clobbered: ${node.outerHTML}`);
  10570. }
  10571. // Regular Expressions for parsing tags and attributes
  10572. const SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
  10573. // ! to ~ is the ASCII range.
  10574. const NON_ALPHANUMERIC_REGEXP = /([^\#-~ |!])/g;
  10575. /**
  10576. * Escapes all potentially dangerous characters, so that the
  10577. * resulting string can be safely inserted into attribute or
  10578. * element text.
  10579. * @param value
  10580. */
  10581. function encodeEntities(value) {
  10582. return value
  10583. .replace(/&/g, '&amp;')
  10584. .replace(SURROGATE_PAIR_REGEXP, function (match) {
  10585. const hi = match.charCodeAt(0);
  10586. const low = match.charCodeAt(1);
  10587. return '&#' + ((hi - 0xd800) * 0x400 + (low - 0xdc00) + 0x10000) + ';';
  10588. })
  10589. .replace(NON_ALPHANUMERIC_REGEXP, function (match) {
  10590. return '&#' + match.charCodeAt(0) + ';';
  10591. })
  10592. .replace(/</g, '&lt;')
  10593. .replace(/>/g, '&gt;');
  10594. }
  10595. let inertBodyHelper;
  10596. /**
  10597. * Sanitizes the given unsafe, untrusted HTML fragment, and returns HTML text that is safe to add to
  10598. * the DOM in a browser environment.
  10599. */
  10600. function _sanitizeHtml(defaultDoc, unsafeHtmlInput) {
  10601. let inertBodyElement = null;
  10602. try {
  10603. inertBodyHelper = inertBodyHelper || getInertBodyHelper(defaultDoc);
  10604. // Make sure unsafeHtml is actually a string (TypeScript types are not enforced at runtime).
  10605. let unsafeHtml = unsafeHtmlInput ? String(unsafeHtmlInput) : '';
  10606. inertBodyElement = inertBodyHelper.getInertBodyElement(unsafeHtml);
  10607. // mXSS protection. Repeatedly parse the document to make sure it stabilizes, so that a browser
  10608. // trying to auto-correct incorrect HTML cannot cause formerly inert HTML to become dangerous.
  10609. let mXSSAttempts = 5;
  10610. let parsedHtml = unsafeHtml;
  10611. do {
  10612. if (mXSSAttempts === 0) {
  10613. throw new Error('Failed to sanitize html because the input is unstable');
  10614. }
  10615. mXSSAttempts--;
  10616. unsafeHtml = parsedHtml;
  10617. parsedHtml = inertBodyElement.innerHTML;
  10618. inertBodyElement = inertBodyHelper.getInertBodyElement(unsafeHtml);
  10619. } while (unsafeHtml !== parsedHtml);
  10620. const sanitizer = new SanitizingHtmlSerializer();
  10621. const safeHtml = sanitizer.sanitizeChildren(getTemplateContent(inertBodyElement) || inertBodyElement);
  10622. if ((typeof ngDevMode === 'undefined' || ngDevMode) && sanitizer.sanitizedSomething) {
  10623. console.warn(`WARNING: sanitizing HTML stripped some content, see ${XSS_SECURITY_URL}`);
  10624. }
  10625. return trustedHTMLFromString(safeHtml);
  10626. }
  10627. finally {
  10628. // In case anything goes wrong, clear out inertElement to reset the entire DOM structure.
  10629. if (inertBodyElement) {
  10630. const parent = getTemplateContent(inertBodyElement) || inertBodyElement;
  10631. while (parent.firstChild) {
  10632. parent.firstChild.remove();
  10633. }
  10634. }
  10635. }
  10636. }
  10637. function getTemplateContent(el) {
  10638. return 'content' in el /** Microsoft/TypeScript#21517 */ && isTemplateElement(el)
  10639. ? el.content
  10640. : null;
  10641. }
  10642. function isTemplateElement(el) {
  10643. return el.nodeType === Node.ELEMENT_NODE && el.nodeName === 'TEMPLATE';
  10644. }
  10645. /**
  10646. * A SecurityContext marks a location that has dangerous security implications, e.g. a DOM property
  10647. * like `innerHTML` that could cause Cross Site Scripting (XSS) security bugs when improperly
  10648. * handled.
  10649. *
  10650. * See DomSanitizer for more details on security in Angular applications.
  10651. *
  10652. * @publicApi
  10653. */
  10654. var SecurityContext;
  10655. (function (SecurityContext) {
  10656. SecurityContext[SecurityContext["NONE"] = 0] = "NONE";
  10657. SecurityContext[SecurityContext["HTML"] = 1] = "HTML";
  10658. SecurityContext[SecurityContext["STYLE"] = 2] = "STYLE";
  10659. SecurityContext[SecurityContext["SCRIPT"] = 3] = "SCRIPT";
  10660. SecurityContext[SecurityContext["URL"] = 4] = "URL";
  10661. SecurityContext[SecurityContext["RESOURCE_URL"] = 5] = "RESOURCE_URL";
  10662. })(SecurityContext || (SecurityContext = {}));
  10663. /**
  10664. * An `html` sanitizer which converts untrusted `html` **string** into trusted string by removing
  10665. * dangerous content.
  10666. *
  10667. * This method parses the `html` and locates potentially dangerous content (such as urls and
  10668. * javascript) and removes it.
  10669. *
  10670. * It is possible to mark a string as trusted by calling {@link bypassSanitizationTrustHtml}.
  10671. *
  10672. * @param unsafeHtml untrusted `html`, typically from the user.
  10673. * @returns `html` string which is safe to display to user, because all of the dangerous javascript
  10674. * and urls have been removed.
  10675. *
  10676. * @codeGenApi
  10677. */
  10678. function ɵɵsanitizeHtml(unsafeHtml) {
  10679. const sanitizer = getSanitizer();
  10680. if (sanitizer) {
  10681. return trustedHTMLFromStringBypass(sanitizer.sanitize(SecurityContext.HTML, unsafeHtml) || '');
  10682. }
  10683. if (allowSanitizationBypassAndThrow(unsafeHtml, "HTML" /* BypassType.Html */)) {
  10684. return trustedHTMLFromStringBypass(unwrapSafeValue(unsafeHtml));
  10685. }
  10686. return _sanitizeHtml(getDocument(), renderStringify(unsafeHtml));
  10687. }
  10688. /**
  10689. * A `style` sanitizer which converts untrusted `style` **string** into trusted string by removing
  10690. * dangerous content.
  10691. *
  10692. * It is possible to mark a string as trusted by calling {@link bypassSanitizationTrustStyle}.
  10693. *
  10694. * @param unsafeStyle untrusted `style`, typically from the user.
  10695. * @returns `style` string which is safe to bind to the `style` properties.
  10696. *
  10697. * @codeGenApi
  10698. */
  10699. function ɵɵsanitizeStyle(unsafeStyle) {
  10700. const sanitizer = getSanitizer();
  10701. if (sanitizer) {
  10702. return sanitizer.sanitize(SecurityContext.STYLE, unsafeStyle) || '';
  10703. }
  10704. if (allowSanitizationBypassAndThrow(unsafeStyle, "Style" /* BypassType.Style */)) {
  10705. return unwrapSafeValue(unsafeStyle);
  10706. }
  10707. return renderStringify(unsafeStyle);
  10708. }
  10709. /**
  10710. * A `url` sanitizer which converts untrusted `url` **string** into trusted string by removing
  10711. * dangerous
  10712. * content.
  10713. *
  10714. * This method parses the `url` and locates potentially dangerous content (such as javascript) and
  10715. * removes it.
  10716. *
  10717. * It is possible to mark a string as trusted by calling {@link bypassSanitizationTrustUrl}.
  10718. *
  10719. * @param unsafeUrl untrusted `url`, typically from the user.
  10720. * @returns `url` string which is safe to bind to the `src` properties such as `<img src>`, because
  10721. * all of the dangerous javascript has been removed.
  10722. *
  10723. * @codeGenApi
  10724. */
  10725. function ɵɵsanitizeUrl(unsafeUrl) {
  10726. const sanitizer = getSanitizer();
  10727. if (sanitizer) {
  10728. return sanitizer.sanitize(SecurityContext.URL, unsafeUrl) || '';
  10729. }
  10730. if (allowSanitizationBypassAndThrow(unsafeUrl, "URL" /* BypassType.Url */)) {
  10731. return unwrapSafeValue(unsafeUrl);
  10732. }
  10733. return _sanitizeUrl(renderStringify(unsafeUrl));
  10734. }
  10735. /**
  10736. * A `url` sanitizer which only lets trusted `url`s through.
  10737. *
  10738. * This passes only `url`s marked trusted by calling {@link bypassSanitizationTrustResourceUrl}.
  10739. *
  10740. * @param unsafeResourceUrl untrusted `url`, typically from the user.
  10741. * @returns `url` string which is safe to bind to the `src` properties such as `<img src>`, because
  10742. * only trusted `url`s have been allowed to pass.
  10743. *
  10744. * @codeGenApi
  10745. */
  10746. function ɵɵsanitizeResourceUrl(unsafeResourceUrl) {
  10747. const sanitizer = getSanitizer();
  10748. if (sanitizer) {
  10749. return trustedScriptURLFromStringBypass(sanitizer.sanitize(SecurityContext.RESOURCE_URL, unsafeResourceUrl) || '');
  10750. }
  10751. if (allowSanitizationBypassAndThrow(unsafeResourceUrl, "ResourceURL" /* BypassType.ResourceUrl */)) {
  10752. return trustedScriptURLFromStringBypass(unwrapSafeValue(unsafeResourceUrl));
  10753. }
  10754. throw new RuntimeError(904 /* RuntimeErrorCode.UNSAFE_VALUE_IN_RESOURCE_URL */, ngDevMode && `unsafe value used in a resource URL context (see ${XSS_SECURITY_URL})`);
  10755. }
  10756. /**
  10757. * A `script` sanitizer which only lets trusted javascript through.
  10758. *
  10759. * This passes only `script`s marked trusted by calling {@link
  10760. * bypassSanitizationTrustScript}.
  10761. *
  10762. * @param unsafeScript untrusted `script`, typically from the user.
  10763. * @returns `url` string which is safe to bind to the `<script>` element such as `<img src>`,
  10764. * because only trusted `scripts` have been allowed to pass.
  10765. *
  10766. * @codeGenApi
  10767. */
  10768. function ɵɵsanitizeScript(unsafeScript) {
  10769. const sanitizer = getSanitizer();
  10770. if (sanitizer) {
  10771. return trustedScriptFromStringBypass(sanitizer.sanitize(SecurityContext.SCRIPT, unsafeScript) || '');
  10772. }
  10773. if (allowSanitizationBypassAndThrow(unsafeScript, "Script" /* BypassType.Script */)) {
  10774. return trustedScriptFromStringBypass(unwrapSafeValue(unsafeScript));
  10775. }
  10776. throw new RuntimeError(905 /* RuntimeErrorCode.UNSAFE_VALUE_IN_SCRIPT */, ngDevMode && 'unsafe value used in a script context');
  10777. }
  10778. /**
  10779. * A template tag function for promoting the associated constant literal to a
  10780. * TrustedHTML. Interpolation is explicitly not allowed.
  10781. *
  10782. * @param html constant template literal containing trusted HTML.
  10783. * @returns TrustedHTML wrapping `html`.
  10784. *
  10785. * @security This is a security-sensitive function and should only be used to
  10786. * convert constant values of attributes and properties found in
  10787. * application-provided Angular templates to TrustedHTML.
  10788. *
  10789. * @codeGenApi
  10790. */
  10791. function ɵɵtrustConstantHtml(html) {
  10792. // The following runtime check ensures that the function was called as a
  10793. // template tag (e.g. ɵɵtrustConstantHtml`content`), without any interpolation
  10794. // (e.g. not ɵɵtrustConstantHtml`content ${variable}`). A TemplateStringsArray
  10795. // is an array with a `raw` property that is also an array. The associated
  10796. // template literal has no interpolation if and only if the length of the
  10797. // TemplateStringsArray is 1.
  10798. if (ngDevMode && (!Array.isArray(html) || !Array.isArray(html.raw) || html.length !== 1)) {
  10799. throw new Error(`Unexpected interpolation in trusted HTML constant: ${html.join('?')}`);
  10800. }
  10801. return trustedHTMLFromString(html[0]);
  10802. }
  10803. /**
  10804. * A template tag function for promoting the associated constant literal to a
  10805. * TrustedScriptURL. Interpolation is explicitly not allowed.
  10806. *
  10807. * @param url constant template literal containing a trusted script URL.
  10808. * @returns TrustedScriptURL wrapping `url`.
  10809. *
  10810. * @security This is a security-sensitive function and should only be used to
  10811. * convert constant values of attributes and properties found in
  10812. * application-provided Angular templates to TrustedScriptURL.
  10813. *
  10814. * @codeGenApi
  10815. */
  10816. function ɵɵtrustConstantResourceUrl(url) {
  10817. // The following runtime check ensures that the function was called as a
  10818. // template tag (e.g. ɵɵtrustConstantResourceUrl`content`), without any
  10819. // interpolation (e.g. not ɵɵtrustConstantResourceUrl`content ${variable}`). A
  10820. // TemplateStringsArray is an array with a `raw` property that is also an
  10821. // array. The associated template literal has no interpolation if and only if
  10822. // the length of the TemplateStringsArray is 1.
  10823. if (ngDevMode && (!Array.isArray(url) || !Array.isArray(url.raw) || url.length !== 1)) {
  10824. throw new Error(`Unexpected interpolation in trusted URL constant: ${url.join('?')}`);
  10825. }
  10826. return trustedScriptURLFromString(url[0]);
  10827. }
  10828. /**
  10829. * Detects which sanitizer to use for URL property, based on tag name and prop name.
  10830. *
  10831. * The rules are based on the RESOURCE_URL context config from
  10832. * `packages/compiler/src/schema/dom_security_schema.ts`.
  10833. * If tag and prop names don't match Resource URL schema, use URL sanitizer.
  10834. */
  10835. function getUrlSanitizer(tag, prop) {
  10836. if ((prop === 'src' &&
  10837. (tag === 'embed' ||
  10838. tag === 'frame' ||
  10839. tag === 'iframe' ||
  10840. tag === 'media' ||
  10841. tag === 'script')) ||
  10842. (prop === 'href' && (tag === 'base' || tag === 'link'))) {
  10843. return ɵɵsanitizeResourceUrl;
  10844. }
  10845. return ɵɵsanitizeUrl;
  10846. }
  10847. /**
  10848. * Sanitizes URL, selecting sanitizer function based on tag and property names.
  10849. *
  10850. * This function is used in case we can't define security context at compile time, when only prop
  10851. * name is available. This happens when we generate host bindings for Directives/Components. The
  10852. * host element is unknown at compile time, so we defer calculation of specific sanitizer to
  10853. * runtime.
  10854. *
  10855. * @param unsafeUrl untrusted `url`, typically from the user.
  10856. * @param tag target element tag name.
  10857. * @param prop name of the property that contains the value.
  10858. * @returns `url` string which is safe to bind.
  10859. *
  10860. * @codeGenApi
  10861. */
  10862. function ɵɵsanitizeUrlOrResourceUrl(unsafeUrl, tag, prop) {
  10863. return getUrlSanitizer(tag, prop)(unsafeUrl);
  10864. }
  10865. function validateAgainstEventProperties(name) {
  10866. if (name.toLowerCase().startsWith('on')) {
  10867. const errorMessage = `Binding to event property '${name}' is disallowed for security reasons, ` +
  10868. `please use (${name.slice(2)})=...` +
  10869. `\nIf '${name}' is a directive input, make sure the directive is imported by the` +
  10870. ` current module.`;
  10871. throw new RuntimeError(306 /* RuntimeErrorCode.INVALID_EVENT_BINDING */, errorMessage);
  10872. }
  10873. }
  10874. function validateAgainstEventAttributes(name) {
  10875. if (name.toLowerCase().startsWith('on')) {
  10876. const errorMessage = `Binding to event attribute '${name}' is disallowed for security reasons, ` +
  10877. `please use (${name.slice(2)})=...`;
  10878. throw new RuntimeError(306 /* RuntimeErrorCode.INVALID_EVENT_BINDING */, errorMessage);
  10879. }
  10880. }
  10881. function getSanitizer() {
  10882. const lView = getLView();
  10883. return lView && lView[ENVIRONMENT].sanitizer;
  10884. }
  10885. /**
  10886. * Disallowed strings in the comment.
  10887. *
  10888. * see: https://html.spec.whatwg.org/multipage/syntax.html#comments
  10889. */
  10890. const COMMENT_DISALLOWED = /^>|^->|<!--|-->|--!>|<!-$/g;
  10891. /**
  10892. * Delimiter in the disallowed strings which needs to be wrapped with zero with character.
  10893. */
  10894. const COMMENT_DELIMITER = /(<|>)/g;
  10895. const COMMENT_DELIMITER_ESCAPED = '\u200B$1\u200B';
  10896. /**
  10897. * Escape the content of comment strings so that it can be safely inserted into a comment node.
  10898. *
  10899. * The issue is that HTML does not specify any way to escape comment end text inside the comment.
  10900. * Consider: `<!-- The way you close a comment is with ">", and "->" at the beginning or by "-->" or
  10901. * "--!>" at the end. -->`. Above the `"-->"` is meant to be text not an end to the comment. This
  10902. * can be created programmatically through DOM APIs. (`<!--` are also disallowed.)
  10903. *
  10904. * see: https://html.spec.whatwg.org/multipage/syntax.html#comments
  10905. *
  10906. * ```ts
  10907. * div.innerHTML = div.innerHTML
  10908. * ```
  10909. *
  10910. * One would expect that the above code would be safe to do, but it turns out that because comment
  10911. * text is not escaped, the comment may contain text which will prematurely close the comment
  10912. * opening up the application for XSS attack. (In SSR we programmatically create comment nodes which
  10913. * may contain such text and expect them to be safe.)
  10914. *
  10915. * This function escapes the comment text by looking for comment delimiters (`<` and `>`) and
  10916. * surrounding them with `_>_` where the `_` is a zero width space `\u200B`. The result is that if a
  10917. * comment contains any of the comment start/end delimiters (such as `<!--`, `-->` or `--!>`) the
  10918. * text it will render normally but it will not cause the HTML parser to close/open the comment.
  10919. *
  10920. * @param value text to make safe for comment node by escaping the comment open/close character
  10921. * sequence.
  10922. */
  10923. function escapeCommentText(value) {
  10924. return value.replace(COMMENT_DISALLOWED, (text) => text.replace(COMMENT_DELIMITER, COMMENT_DELIMITER_ESCAPED));
  10925. }
  10926. function normalizeDebugBindingName(name) {
  10927. // Attribute names with `$` (eg `x-y$`) are valid per spec, but unsupported by some browsers
  10928. name = camelCaseToDashCase(name.replace(/[$@]/g, '_'));
  10929. return `ng-reflect-${name}`;
  10930. }
  10931. const CAMEL_CASE_REGEXP = /([A-Z])/g;
  10932. function camelCaseToDashCase(input) {
  10933. return input.replace(CAMEL_CASE_REGEXP, (...m) => '-' + m[1].toLowerCase());
  10934. }
  10935. function normalizeDebugBindingValue(value) {
  10936. try {
  10937. // Limit the size of the value as otherwise the DOM just gets polluted.
  10938. return value != null ? value.toString().slice(0, 30) : value;
  10939. }
  10940. catch (e) {
  10941. return '[ERROR] Exception while trying to serialize the value';
  10942. }
  10943. }
  10944. /**
  10945. * Defines a schema that allows an NgModule to contain the following:
  10946. * - Non-Angular elements named with dash case (`-`).
  10947. * - Element properties named with dash case (`-`).
  10948. * Dash case is the naming convention for custom elements.
  10949. *
  10950. * @publicApi
  10951. */
  10952. const CUSTOM_ELEMENTS_SCHEMA = {
  10953. name: 'custom-elements',
  10954. };
  10955. /**
  10956. * Defines a schema that allows any property on any element.
  10957. *
  10958. * This schema allows you to ignore the errors related to any unknown elements or properties in a
  10959. * template. The usage of this schema is generally discouraged because it prevents useful validation
  10960. * and may hide real errors in your template. Consider using the `CUSTOM_ELEMENTS_SCHEMA` instead.
  10961. *
  10962. * @publicApi
  10963. */
  10964. const NO_ERRORS_SCHEMA = {
  10965. name: 'no-errors-schema',
  10966. };
  10967. let shouldThrowErrorOnUnknownElement = false;
  10968. /**
  10969. * Sets a strict mode for JIT-compiled components to throw an error on unknown elements,
  10970. * instead of just logging the error.
  10971. * (for AOT-compiled ones this check happens at build time).
  10972. */
  10973. function ɵsetUnknownElementStrictMode(shouldThrow) {
  10974. shouldThrowErrorOnUnknownElement = shouldThrow;
  10975. }
  10976. /**
  10977. * Gets the current value of the strict mode.
  10978. */
  10979. function ɵgetUnknownElementStrictMode() {
  10980. return shouldThrowErrorOnUnknownElement;
  10981. }
  10982. let shouldThrowErrorOnUnknownProperty = false;
  10983. /**
  10984. * Sets a strict mode for JIT-compiled components to throw an error on unknown properties,
  10985. * instead of just logging the error.
  10986. * (for AOT-compiled ones this check happens at build time).
  10987. */
  10988. function ɵsetUnknownPropertyStrictMode(shouldThrow) {
  10989. shouldThrowErrorOnUnknownProperty = shouldThrow;
  10990. }
  10991. /**
  10992. * Gets the current value of the strict mode.
  10993. */
  10994. function ɵgetUnknownPropertyStrictMode() {
  10995. return shouldThrowErrorOnUnknownProperty;
  10996. }
  10997. /**
  10998. * Validates that the element is known at runtime and produces
  10999. * an error if it's not the case.
  11000. * This check is relevant for JIT-compiled components (for AOT-compiled
  11001. * ones this check happens at build time).
  11002. *
  11003. * The element is considered known if either:
  11004. * - it's a known HTML element
  11005. * - it's a known custom element
  11006. * - the element matches any directive
  11007. * - the element is allowed by one of the schemas
  11008. *
  11009. * @param element Element to validate
  11010. * @param lView An `LView` that represents a current component that is being rendered
  11011. * @param tagName Name of the tag to check
  11012. * @param schemas Array of schemas
  11013. * @param hasDirectives Boolean indicating that the element matches any directive
  11014. */
  11015. function validateElementIsKnown(element, lView, tagName, schemas, hasDirectives) {
  11016. // If `schemas` is set to `null`, that's an indication that this Component was compiled in AOT
  11017. // mode where this check happens at compile time. In JIT mode, `schemas` is always present and
  11018. // defined as an array (as an empty array in case `schemas` field is not defined) and we should
  11019. // execute the check below.
  11020. if (schemas === null)
  11021. return;
  11022. // If the element matches any directive, it's considered as valid.
  11023. if (!hasDirectives && tagName !== null) {
  11024. // The element is unknown if it's an instance of HTMLUnknownElement, or it isn't registered
  11025. // as a custom element. Note that unknown elements with a dash in their name won't be instances
  11026. // of HTMLUnknownElement in browsers that support web components.
  11027. const isUnknown =
  11028. // Note that we can't check for `typeof HTMLUnknownElement === 'function'` because
  11029. // Domino doesn't expose HTMLUnknownElement globally.
  11030. (typeof HTMLUnknownElement !== 'undefined' &&
  11031. HTMLUnknownElement &&
  11032. element instanceof HTMLUnknownElement) ||
  11033. (typeof customElements !== 'undefined' &&
  11034. tagName.indexOf('-') > -1 &&
  11035. !customElements.get(tagName));
  11036. if (isUnknown && !matchingSchemas(schemas, tagName)) {
  11037. const isHostStandalone = isHostComponentStandalone(lView);
  11038. const templateLocation = getTemplateLocationDetails(lView);
  11039. const schemas = `'${isHostStandalone ? '@Component' : '@NgModule'}.schemas'`;
  11040. let message = `'${tagName}' is not a known element${templateLocation}:\n`;
  11041. message += `1. If '${tagName}' is an Angular component, then verify that it is ${isHostStandalone
  11042. ? "included in the '@Component.imports' of this component"
  11043. : 'a part of an @NgModule where this component is declared'}.\n`;
  11044. if (tagName && tagName.indexOf('-') > -1) {
  11045. message += `2. If '${tagName}' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the ${schemas} of this component to suppress this message.`;
  11046. }
  11047. else {
  11048. message += `2. To allow any element add 'NO_ERRORS_SCHEMA' to the ${schemas} of this component.`;
  11049. }
  11050. if (shouldThrowErrorOnUnknownElement) {
  11051. throw new RuntimeError(304 /* RuntimeErrorCode.UNKNOWN_ELEMENT */, message);
  11052. }
  11053. else {
  11054. console.error(formatRuntimeError(304 /* RuntimeErrorCode.UNKNOWN_ELEMENT */, message));
  11055. }
  11056. }
  11057. }
  11058. }
  11059. /**
  11060. * Validates that the property of the element is known at runtime and returns
  11061. * false if it's not the case.
  11062. * This check is relevant for JIT-compiled components (for AOT-compiled
  11063. * ones this check happens at build time).
  11064. *
  11065. * The property is considered known if either:
  11066. * - it's a known property of the element
  11067. * - the element is allowed by one of the schemas
  11068. * - the property is used for animations
  11069. *
  11070. * @param element Element to validate
  11071. * @param propName Name of the property to check
  11072. * @param tagName Name of the tag hosting the property
  11073. * @param schemas Array of schemas
  11074. */
  11075. function isPropertyValid(element, propName, tagName, schemas) {
  11076. // If `schemas` is set to `null`, that's an indication that this Component was compiled in AOT
  11077. // mode where this check happens at compile time. In JIT mode, `schemas` is always present and
  11078. // defined as an array (as an empty array in case `schemas` field is not defined) and we should
  11079. // execute the check below.
  11080. if (schemas === null)
  11081. return true;
  11082. // The property is considered valid if the element matches the schema, it exists on the element,
  11083. // or it is synthetic.
  11084. if (matchingSchemas(schemas, tagName) || propName in element || isAnimationProp(propName)) {
  11085. return true;
  11086. }
  11087. // Note: `typeof Node` returns 'function' in most browsers, but is undefined with domino.
  11088. return typeof Node === 'undefined' || Node === null || !(element instanceof Node);
  11089. }
  11090. /**
  11091. * Logs or throws an error that a property is not supported on an element.
  11092. *
  11093. * @param propName Name of the invalid property
  11094. * @param tagName Name of the tag hosting the property
  11095. * @param nodeType Type of the node hosting the property
  11096. * @param lView An `LView` that represents a current component
  11097. */
  11098. function handleUnknownPropertyError(propName, tagName, nodeType, lView) {
  11099. // Special-case a situation when a structural directive is applied to
  11100. // an `<ng-template>` element, for example: `<ng-template *ngIf="true">`.
  11101. // In this case the compiler generates the `ɵɵtemplate` instruction with
  11102. // the `null` as the tagName. The directive matching logic at runtime relies
  11103. // on this effect (see `isInlineTemplate`), thus using the 'ng-template' as
  11104. // a default value of the `tNode.value` is not feasible at this moment.
  11105. if (!tagName && nodeType === 4 /* TNodeType.Container */) {
  11106. tagName = 'ng-template';
  11107. }
  11108. const isHostStandalone = isHostComponentStandalone(lView);
  11109. const templateLocation = getTemplateLocationDetails(lView);
  11110. let message = `Can't bind to '${propName}' since it isn't a known property of '${tagName}'${templateLocation}.`;
  11111. const schemas = `'${isHostStandalone ? '@Component' : '@NgModule'}.schemas'`;
  11112. const importLocation = isHostStandalone
  11113. ? "included in the '@Component.imports' of this component"
  11114. : 'a part of an @NgModule where this component is declared';
  11115. if (KNOWN_CONTROL_FLOW_DIRECTIVES.has(propName)) {
  11116. // Most likely this is a control flow directive (such as `*ngIf`) used in
  11117. // a template, but the directive or the `CommonModule` is not imported.
  11118. const correspondingImport = KNOWN_CONTROL_FLOW_DIRECTIVES.get(propName);
  11119. message +=
  11120. `\nIf the '${propName}' is an Angular control flow directive, ` +
  11121. `please make sure that either the '${correspondingImport}' directive or the 'CommonModule' is ${importLocation}.`;
  11122. }
  11123. else {
  11124. // May be an Angular component, which is not imported/declared?
  11125. message +=
  11126. `\n1. If '${tagName}' is an Angular component and it has the ` +
  11127. `'${propName}' input, then verify that it is ${importLocation}.`;
  11128. // May be a Web Component?
  11129. if (tagName && tagName.indexOf('-') > -1) {
  11130. message +=
  11131. `\n2. If '${tagName}' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' ` +
  11132. `to the ${schemas} of this component to suppress this message.`;
  11133. message +=
  11134. `\n3. To allow any property add 'NO_ERRORS_SCHEMA' to ` +
  11135. `the ${schemas} of this component.`;
  11136. }
  11137. else {
  11138. // If it's expected, the error can be suppressed by the `NO_ERRORS_SCHEMA` schema.
  11139. message +=
  11140. `\n2. To allow any property add 'NO_ERRORS_SCHEMA' to ` +
  11141. `the ${schemas} of this component.`;
  11142. }
  11143. }
  11144. reportUnknownPropertyError(message);
  11145. }
  11146. function reportUnknownPropertyError(message) {
  11147. if (shouldThrowErrorOnUnknownProperty) {
  11148. throw new RuntimeError(303 /* RuntimeErrorCode.UNKNOWN_BINDING */, message);
  11149. }
  11150. else {
  11151. console.error(formatRuntimeError(303 /* RuntimeErrorCode.UNKNOWN_BINDING */, message));
  11152. }
  11153. }
  11154. /**
  11155. * WARNING: this is a **dev-mode only** function (thus should always be guarded by the `ngDevMode`)
  11156. * and must **not** be used in production bundles. The function makes megamorphic reads, which might
  11157. * be too slow for production mode and also it relies on the constructor function being available.
  11158. *
  11159. * Gets a reference to the host component def (where a current component is declared).
  11160. *
  11161. * @param lView An `LView` that represents a current component that is being rendered.
  11162. */
  11163. function getDeclarationComponentDef(lView) {
  11164. !ngDevMode && throwError('Must never be called in production mode');
  11165. const declarationLView = lView[DECLARATION_COMPONENT_VIEW];
  11166. const context = declarationLView[CONTEXT];
  11167. // Unable to obtain a context.
  11168. if (!context)
  11169. return null;
  11170. return context.constructor ? getComponentDef(context.constructor) : null;
  11171. }
  11172. /**
  11173. * WARNING: this is a **dev-mode only** function (thus should always be guarded by the `ngDevMode`)
  11174. * and must **not** be used in production bundles. The function makes megamorphic reads, which might
  11175. * be too slow for production mode.
  11176. *
  11177. * Checks if the current component is declared inside of a standalone component template.
  11178. *
  11179. * @param lView An `LView` that represents a current component that is being rendered.
  11180. */
  11181. function isHostComponentStandalone(lView) {
  11182. !ngDevMode && throwError('Must never be called in production mode');
  11183. const componentDef = getDeclarationComponentDef(lView);
  11184. // Treat host component as non-standalone if we can't obtain the def.
  11185. return !!componentDef?.standalone;
  11186. }
  11187. /**
  11188. * WARNING: this is a **dev-mode only** function (thus should always be guarded by the `ngDevMode`)
  11189. * and must **not** be used in production bundles. The function makes megamorphic reads, which might
  11190. * be too slow for production mode.
  11191. *
  11192. * Constructs a string describing the location of the host component template. The function is used
  11193. * in dev mode to produce error messages.
  11194. *
  11195. * @param lView An `LView` that represents a current component that is being rendered.
  11196. */
  11197. function getTemplateLocationDetails(lView) {
  11198. !ngDevMode && throwError('Must never be called in production mode');
  11199. const hostComponentDef = getDeclarationComponentDef(lView);
  11200. const componentClassName = hostComponentDef?.type?.name;
  11201. return componentClassName ? ` (used in the '${componentClassName}' component template)` : '';
  11202. }
  11203. /**
  11204. * The set of known control flow directives and their corresponding imports.
  11205. * We use this set to produce a more precises error message with a note
  11206. * that the `CommonModule` should also be included.
  11207. */
  11208. const KNOWN_CONTROL_FLOW_DIRECTIVES = new Map([
  11209. ['ngIf', 'NgIf'],
  11210. ['ngFor', 'NgFor'],
  11211. ['ngSwitchCase', 'NgSwitchCase'],
  11212. ['ngSwitchDefault', 'NgSwitchDefault'],
  11213. ]);
  11214. /**
  11215. * Returns true if the tag name is allowed by specified schemas.
  11216. * @param schemas Array of schemas
  11217. * @param tagName Name of the tag
  11218. */
  11219. function matchingSchemas(schemas, tagName) {
  11220. if (schemas !== null) {
  11221. for (let i = 0; i < schemas.length; i++) {
  11222. const schema = schemas[i];
  11223. if (schema === NO_ERRORS_SCHEMA ||
  11224. (schema === CUSTOM_ELEMENTS_SCHEMA && tagName && tagName.indexOf('-') > -1)) {
  11225. return true;
  11226. }
  11227. }
  11228. }
  11229. return false;
  11230. }
  11231. /**
  11232. *
  11233. * @codeGenApi
  11234. */
  11235. function ɵɵresolveWindow(element) {
  11236. return element.ownerDocument.defaultView;
  11237. }
  11238. /**
  11239. *
  11240. * @codeGenApi
  11241. */
  11242. function ɵɵresolveDocument(element) {
  11243. return element.ownerDocument;
  11244. }
  11245. /**
  11246. *
  11247. * @codeGenApi
  11248. */
  11249. function ɵɵresolveBody(element) {
  11250. return element.ownerDocument.body;
  11251. }
  11252. /**
  11253. * The special delimiter we use to separate property names, prefixes, and suffixes
  11254. * in property binding metadata. See storeBindingMetadata().
  11255. *
  11256. * We intentionally use the Unicode "REPLACEMENT CHARACTER" (U+FFFD) as a delimiter
  11257. * because it is a very uncommon character that is unlikely to be part of a user's
  11258. * property names or interpolation strings. If it is in fact used in a property
  11259. * binding, DebugElement.properties will not return the correct value for that
  11260. * binding. However, there should be no runtime effect for real applications.
  11261. *
  11262. * This character is typically rendered as a question mark inside of a diamond.
  11263. * See https://en.wikipedia.org/wiki/Specials_(Unicode_block)
  11264. *
  11265. */
  11266. const INTERPOLATION_DELIMITER = `�`;
  11267. /**
  11268. * Unwrap a value which might be behind a closure (for forward declaration reasons).
  11269. */
  11270. function maybeUnwrapFn(value) {
  11271. if (value instanceof Function) {
  11272. return value();
  11273. }
  11274. else {
  11275. return value;
  11276. }
  11277. }
  11278. /**
  11279. * The max length of the string representation of a value in an error message
  11280. */
  11281. const VALUE_STRING_LENGTH_LIMIT = 200;
  11282. /** Verifies that a given type is a Standalone Component. */
  11283. function assertStandaloneComponentType(type) {
  11284. assertComponentDef(type);
  11285. const componentDef = getComponentDef(type);
  11286. if (!componentDef.standalone) {
  11287. throw new RuntimeError(907 /* RuntimeErrorCode.TYPE_IS_NOT_STANDALONE */, `The ${stringifyForError(type)} component is not marked as standalone, ` +
  11288. `but Angular expects to have a standalone component here. ` +
  11289. `Please make sure the ${stringifyForError(type)} component has ` +
  11290. `the \`standalone: true\` flag in the decorator.`);
  11291. }
  11292. }
  11293. /** Verifies whether a given type is a component */
  11294. function assertComponentDef(type) {
  11295. if (!getComponentDef(type)) {
  11296. throw new RuntimeError(906 /* RuntimeErrorCode.MISSING_GENERATED_DEF */, `The ${stringifyForError(type)} is not an Angular component, ` +
  11297. `make sure it has the \`@Component\` decorator.`);
  11298. }
  11299. }
  11300. /** Called when there are multiple component selectors that match a given node */
  11301. function throwMultipleComponentError(tNode, first, second) {
  11302. throw new RuntimeError(-300 /* RuntimeErrorCode.MULTIPLE_COMPONENTS_MATCH */, `Multiple components match node with tagname ${tNode.value}: ` +
  11303. `${stringifyForError(first)} and ` +
  11304. `${stringifyForError(second)}`);
  11305. }
  11306. /** Throws an ExpressionChangedAfterChecked error if checkNoChanges mode is on. */
  11307. function throwErrorIfNoChangesMode(creationMode, oldValue, currValue, propName, lView) {
  11308. const hostComponentDef = getDeclarationComponentDef(lView);
  11309. const componentClassName = hostComponentDef?.type?.name;
  11310. const field = propName ? ` for '${propName}'` : '';
  11311. let msg = `ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value${field}: '${formatValue(oldValue)}'. Current value: '${formatValue(currValue)}'.${componentClassName ? ` Expression location: ${componentClassName} component` : ''}`;
  11312. if (creationMode) {
  11313. msg +=
  11314. ` It seems like the view has been created after its parent and its children have been dirty checked.` +
  11315. ` Has it been created in a change detection hook?`;
  11316. }
  11317. throw new RuntimeError(-100 /* RuntimeErrorCode.EXPRESSION_CHANGED_AFTER_CHECKED */, msg);
  11318. }
  11319. function formatValue(value) {
  11320. let strValue = String(value);
  11321. // JSON.stringify will throw on circular references
  11322. try {
  11323. if (Array.isArray(value) || strValue === '[object Object]') {
  11324. strValue = JSON.stringify(value);
  11325. }
  11326. }
  11327. catch (error) { }
  11328. return strValue.length > VALUE_STRING_LENGTH_LIMIT
  11329. ? strValue.substring(0, VALUE_STRING_LENGTH_LIMIT) + '…'
  11330. : strValue;
  11331. }
  11332. function constructDetailsForInterpolation(lView, rootIndex, expressionIndex, meta, changedValue) {
  11333. const [propName, prefix, ...chunks] = meta.split(INTERPOLATION_DELIMITER);
  11334. let oldValue = prefix, newValue = prefix;
  11335. for (let i = 0; i < chunks.length; i++) {
  11336. const slotIdx = rootIndex + i;
  11337. oldValue += `${lView[slotIdx]}${chunks[i]}`;
  11338. newValue += `${slotIdx === expressionIndex ? changedValue : lView[slotIdx]}${chunks[i]}`;
  11339. }
  11340. return { propName, oldValue, newValue };
  11341. }
  11342. /**
  11343. * Constructs an object that contains details for the ExpressionChangedAfterItHasBeenCheckedError:
  11344. * - property name (for property bindings or interpolations)
  11345. * - old and new values, enriched using information from metadata
  11346. *
  11347. * More information on the metadata storage format can be found in `storePropertyBindingMetadata`
  11348. * function description.
  11349. */
  11350. function getExpressionChangedErrorDetails(lView, bindingIndex, oldValue, newValue) {
  11351. const tData = lView[TVIEW].data;
  11352. const metadata = tData[bindingIndex];
  11353. if (typeof metadata === 'string') {
  11354. // metadata for property interpolation
  11355. if (metadata.indexOf(INTERPOLATION_DELIMITER) > -1) {
  11356. return constructDetailsForInterpolation(lView, bindingIndex, bindingIndex, metadata, newValue);
  11357. }
  11358. // metadata for property binding
  11359. return { propName: metadata, oldValue, newValue };
  11360. }
  11361. // metadata is not available for this expression, check if this expression is a part of the
  11362. // property interpolation by going from the current binding index left and look for a string that
  11363. // contains INTERPOLATION_DELIMITER, the layout in tView.data for this case will look like this:
  11364. // [..., 'id�Prefix � and � suffix', null, null, null, ...]
  11365. if (metadata === null) {
  11366. let idx = bindingIndex - 1;
  11367. while (typeof tData[idx] !== 'string' && tData[idx + 1] === null) {
  11368. idx--;
  11369. }
  11370. const meta = tData[idx];
  11371. if (typeof meta === 'string') {
  11372. const matches = meta.match(new RegExp(INTERPOLATION_DELIMITER, 'g'));
  11373. // first interpolation delimiter separates property name from interpolation parts (in case of
  11374. // property interpolations), so we subtract one from total number of found delimiters
  11375. if (matches && matches.length - 1 > bindingIndex - idx) {
  11376. return constructDetailsForInterpolation(lView, idx, bindingIndex, meta, newValue);
  11377. }
  11378. }
  11379. }
  11380. return { propName: undefined, oldValue, newValue };
  11381. }
  11382. /**
  11383. * Returns an index of `classToSearch` in `className` taking token boundaries into account.
  11384. *
  11385. * `classIndexOf('AB A', 'A', 0)` will be 3 (not 0 since `AB!==A`)
  11386. *
  11387. * @param className A string containing classes (whitespace separated)
  11388. * @param classToSearch A class name to locate
  11389. * @param startingIndex Starting location of search
  11390. * @returns an index of the located class (or -1 if not found)
  11391. */
  11392. function classIndexOf(className, classToSearch, startingIndex) {
  11393. ngDevMode && assertNotEqual(classToSearch, '', 'can not look for "" string.');
  11394. let end = className.length;
  11395. while (true) {
  11396. const foundIndex = className.indexOf(classToSearch, startingIndex);
  11397. if (foundIndex === -1)
  11398. return foundIndex;
  11399. if (foundIndex === 0 || className.charCodeAt(foundIndex - 1) <= 32 /* CharCode.SPACE */) {
  11400. // Ensure that it has leading whitespace
  11401. const length = classToSearch.length;
  11402. if (foundIndex + length === end ||
  11403. className.charCodeAt(foundIndex + length) <= 32 /* CharCode.SPACE */) {
  11404. // Ensure that it has trailing whitespace
  11405. return foundIndex;
  11406. }
  11407. }
  11408. // False positive, keep searching from where we left off.
  11409. startingIndex = foundIndex + 1;
  11410. }
  11411. }
  11412. const NG_TEMPLATE_SELECTOR = 'ng-template';
  11413. /**
  11414. * Search the `TAttributes` to see if it contains `cssClassToMatch` (case insensitive)
  11415. *
  11416. * @param tNode static data of the node to match
  11417. * @param attrs `TAttributes` to search through.
  11418. * @param cssClassToMatch class to match (lowercase)
  11419. * @param isProjectionMode Whether or not class matching should look into the attribute `class` in
  11420. * addition to the `AttributeMarker.Classes`.
  11421. */
  11422. function isCssClassMatching(tNode, attrs, cssClassToMatch, isProjectionMode) {
  11423. ngDevMode &&
  11424. assertEqual(cssClassToMatch, cssClassToMatch.toLowerCase(), 'Class name expected to be lowercase.');
  11425. let i = 0;
  11426. if (isProjectionMode) {
  11427. for (; i < attrs.length && typeof attrs[i] === 'string'; i += 2) {
  11428. // Search for an implicit `class` attribute and check if its value matches `cssClassToMatch`.
  11429. if (attrs[i] === 'class' &&
  11430. classIndexOf(attrs[i + 1].toLowerCase(), cssClassToMatch, 0) !== -1) {
  11431. return true;
  11432. }
  11433. }
  11434. }
  11435. else if (isInlineTemplate(tNode)) {
  11436. // Matching directives (i.e. when not matching for projection mode) should not consider the
  11437. // class bindings that are present on inline templates, as those class bindings only target
  11438. // the root node of the template, not the template itself.
  11439. return false;
  11440. }
  11441. // Resume the search for classes after the `Classes` marker.
  11442. i = attrs.indexOf(1 /* AttributeMarker.Classes */, i);
  11443. if (i > -1) {
  11444. // We found the classes section. Start searching for the class.
  11445. let item;
  11446. while (++i < attrs.length && typeof (item = attrs[i]) === 'string') {
  11447. if (item.toLowerCase() === cssClassToMatch) {
  11448. return true;
  11449. }
  11450. }
  11451. }
  11452. return false;
  11453. }
  11454. /**
  11455. * Checks whether the `tNode` represents an inline template (e.g. `*ngFor`).
  11456. *
  11457. * @param tNode current TNode
  11458. */
  11459. function isInlineTemplate(tNode) {
  11460. return tNode.type === 4 /* TNodeType.Container */ && tNode.value !== NG_TEMPLATE_SELECTOR;
  11461. }
  11462. /**
  11463. * Function that checks whether a given tNode matches tag-based selector and has a valid type.
  11464. *
  11465. * Matching can be performed in 2 modes: projection mode (when we project nodes) and regular
  11466. * directive matching mode:
  11467. * - in the "directive matching" mode we do _not_ take TContainer's tagName into account if it is
  11468. * different from NG_TEMPLATE_SELECTOR (value different from NG_TEMPLATE_SELECTOR indicates that a
  11469. * tag name was extracted from * syntax so we would match the same directive twice);
  11470. * - in the "projection" mode, we use a tag name potentially extracted from the * syntax processing
  11471. * (applicable to TNodeType.Container only).
  11472. */
  11473. function hasTagAndTypeMatch(tNode, currentSelector, isProjectionMode) {
  11474. const tagNameToCompare = tNode.type === 4 /* TNodeType.Container */ && !isProjectionMode ? NG_TEMPLATE_SELECTOR : tNode.value;
  11475. return currentSelector === tagNameToCompare;
  11476. }
  11477. /**
  11478. * A utility function to match an Ivy node static data against a simple CSS selector
  11479. *
  11480. * @param tNode static data of the node to match
  11481. * @param selector The selector to try matching against the node.
  11482. * @param isProjectionMode if `true` we are matching for content projection, otherwise we are doing
  11483. * directive matching.
  11484. * @returns true if node matches the selector.
  11485. */
  11486. function isNodeMatchingSelector(tNode, selector, isProjectionMode) {
  11487. ngDevMode && assertDefined(selector[0], 'Selector should have a tag name');
  11488. let mode = 4 /* SelectorFlags.ELEMENT */;
  11489. const nodeAttrs = tNode.attrs;
  11490. // Find the index of first attribute that has no value, only a name.
  11491. const nameOnlyMarkerIdx = nodeAttrs !== null ? getNameOnlyMarkerIndex(nodeAttrs) : 0;
  11492. // When processing ":not" selectors, we skip to the next ":not" if the
  11493. // current one doesn't match
  11494. let skipToNextSelector = false;
  11495. for (let i = 0; i < selector.length; i++) {
  11496. const current = selector[i];
  11497. if (typeof current === 'number') {
  11498. // If we finish processing a :not selector and it hasn't failed, return false
  11499. if (!skipToNextSelector && !isPositive(mode) && !isPositive(current)) {
  11500. return false;
  11501. }
  11502. // If we are skipping to the next :not() and this mode flag is positive,
  11503. // it's a part of the current :not() selector, and we should keep skipping
  11504. if (skipToNextSelector && isPositive(current))
  11505. continue;
  11506. skipToNextSelector = false;
  11507. mode = current | (mode & 1 /* SelectorFlags.NOT */);
  11508. continue;
  11509. }
  11510. if (skipToNextSelector)
  11511. continue;
  11512. if (mode & 4 /* SelectorFlags.ELEMENT */) {
  11513. mode = 2 /* SelectorFlags.ATTRIBUTE */ | (mode & 1 /* SelectorFlags.NOT */);
  11514. if ((current !== '' && !hasTagAndTypeMatch(tNode, current, isProjectionMode)) ||
  11515. (current === '' && selector.length === 1)) {
  11516. if (isPositive(mode))
  11517. return false;
  11518. skipToNextSelector = true;
  11519. }
  11520. }
  11521. else if (mode & 8 /* SelectorFlags.CLASS */) {
  11522. if (nodeAttrs === null || !isCssClassMatching(tNode, nodeAttrs, current, isProjectionMode)) {
  11523. if (isPositive(mode))
  11524. return false;
  11525. skipToNextSelector = true;
  11526. }
  11527. }
  11528. else {
  11529. const selectorAttrValue = selector[++i];
  11530. const attrIndexInNode = findAttrIndexInNode(current, nodeAttrs, isInlineTemplate(tNode), isProjectionMode);
  11531. if (attrIndexInNode === -1) {
  11532. if (isPositive(mode))
  11533. return false;
  11534. skipToNextSelector = true;
  11535. continue;
  11536. }
  11537. if (selectorAttrValue !== '') {
  11538. let nodeAttrValue;
  11539. if (attrIndexInNode > nameOnlyMarkerIdx) {
  11540. nodeAttrValue = '';
  11541. }
  11542. else {
  11543. ngDevMode &&
  11544. assertNotEqual(nodeAttrs[attrIndexInNode], 0 /* AttributeMarker.NamespaceURI */, 'We do not match directives on namespaced attributes');
  11545. // we lowercase the attribute value to be able to match
  11546. // selectors without case-sensitivity
  11547. // (selectors are already in lowercase when generated)
  11548. nodeAttrValue = nodeAttrs[attrIndexInNode + 1].toLowerCase();
  11549. }
  11550. if (mode & 2 /* SelectorFlags.ATTRIBUTE */ && selectorAttrValue !== nodeAttrValue) {
  11551. if (isPositive(mode))
  11552. return false;
  11553. skipToNextSelector = true;
  11554. }
  11555. }
  11556. }
  11557. }
  11558. return isPositive(mode) || skipToNextSelector;
  11559. }
  11560. function isPositive(mode) {
  11561. return (mode & 1 /* SelectorFlags.NOT */) === 0;
  11562. }
  11563. /**
  11564. * Examines the attribute's definition array for a node to find the index of the
  11565. * attribute that matches the given `name`.
  11566. *
  11567. * NOTE: This will not match namespaced attributes.
  11568. *
  11569. * Attribute matching depends upon `isInlineTemplate` and `isProjectionMode`.
  11570. * The following table summarizes which types of attributes we attempt to match:
  11571. *
  11572. * ===========================================================================================================
  11573. * Modes | Normal Attributes | Bindings Attributes | Template Attributes | I18n
  11574. * Attributes
  11575. * ===========================================================================================================
  11576. * Inline + Projection | YES | YES | NO | YES
  11577. * -----------------------------------------------------------------------------------------------------------
  11578. * Inline + Directive | NO | NO | YES | NO
  11579. * -----------------------------------------------------------------------------------------------------------
  11580. * Non-inline + Projection | YES | YES | NO | YES
  11581. * -----------------------------------------------------------------------------------------------------------
  11582. * Non-inline + Directive | YES | YES | NO | YES
  11583. * ===========================================================================================================
  11584. *
  11585. * @param name the name of the attribute to find
  11586. * @param attrs the attribute array to examine
  11587. * @param isInlineTemplate true if the node being matched is an inline template (e.g. `*ngFor`)
  11588. * rather than a manually expanded template node (e.g `<ng-template>`).
  11589. * @param isProjectionMode true if we are matching against content projection otherwise we are
  11590. * matching against directives.
  11591. */
  11592. function findAttrIndexInNode(name, attrs, isInlineTemplate, isProjectionMode) {
  11593. if (attrs === null)
  11594. return -1;
  11595. let i = 0;
  11596. if (isProjectionMode || !isInlineTemplate) {
  11597. let bindingsMode = false;
  11598. while (i < attrs.length) {
  11599. const maybeAttrName = attrs[i];
  11600. if (maybeAttrName === name) {
  11601. return i;
  11602. }
  11603. else if (maybeAttrName === 3 /* AttributeMarker.Bindings */ ||
  11604. maybeAttrName === 6 /* AttributeMarker.I18n */) {
  11605. bindingsMode = true;
  11606. }
  11607. else if (maybeAttrName === 1 /* AttributeMarker.Classes */ ||
  11608. maybeAttrName === 2 /* AttributeMarker.Styles */) {
  11609. let value = attrs[++i];
  11610. // We should skip classes here because we have a separate mechanism for
  11611. // matching classes in projection mode.
  11612. while (typeof value === 'string') {
  11613. value = attrs[++i];
  11614. }
  11615. continue;
  11616. }
  11617. else if (maybeAttrName === 4 /* AttributeMarker.Template */) {
  11618. // We do not care about Template attributes in this scenario.
  11619. break;
  11620. }
  11621. else if (maybeAttrName === 0 /* AttributeMarker.NamespaceURI */) {
  11622. // Skip the whole namespaced attribute and value. This is by design.
  11623. i += 4;
  11624. continue;
  11625. }
  11626. // In binding mode there are only names, rather than name-value pairs.
  11627. i += bindingsMode ? 1 : 2;
  11628. }
  11629. // We did not match the attribute
  11630. return -1;
  11631. }
  11632. else {
  11633. return matchTemplateAttribute(attrs, name);
  11634. }
  11635. }
  11636. function isNodeMatchingSelectorList(tNode, selector, isProjectionMode = false) {
  11637. for (let i = 0; i < selector.length; i++) {
  11638. if (isNodeMatchingSelector(tNode, selector[i], isProjectionMode)) {
  11639. return true;
  11640. }
  11641. }
  11642. return false;
  11643. }
  11644. function getProjectAsAttrValue(tNode) {
  11645. const nodeAttrs = tNode.attrs;
  11646. if (nodeAttrs != null) {
  11647. const ngProjectAsAttrIdx = nodeAttrs.indexOf(5 /* AttributeMarker.ProjectAs */);
  11648. // only check for ngProjectAs in attribute names, don't accidentally match attribute's value
  11649. // (attribute names are stored at even indexes)
  11650. if ((ngProjectAsAttrIdx & 1) === 0) {
  11651. return nodeAttrs[ngProjectAsAttrIdx + 1];
  11652. }
  11653. }
  11654. return null;
  11655. }
  11656. function getNameOnlyMarkerIndex(nodeAttrs) {
  11657. for (let i = 0; i < nodeAttrs.length; i++) {
  11658. const nodeAttr = nodeAttrs[i];
  11659. if (isNameOnlyAttributeMarker(nodeAttr)) {
  11660. return i;
  11661. }
  11662. }
  11663. return nodeAttrs.length;
  11664. }
  11665. function matchTemplateAttribute(attrs, name) {
  11666. let i = attrs.indexOf(4 /* AttributeMarker.Template */);
  11667. if (i > -1) {
  11668. i++;
  11669. while (i < attrs.length) {
  11670. const attr = attrs[i];
  11671. // Return in case we checked all template attrs and are switching to the next section in the
  11672. // attrs array (that starts with a number that represents an attribute marker).
  11673. if (typeof attr === 'number')
  11674. return -1;
  11675. if (attr === name)
  11676. return i;
  11677. i++;
  11678. }
  11679. }
  11680. return -1;
  11681. }
  11682. /**
  11683. * Checks whether a selector is inside a CssSelectorList
  11684. * @param selector Selector to be checked.
  11685. * @param list List in which to look for the selector.
  11686. */
  11687. function isSelectorInSelectorList(selector, list) {
  11688. selectorListLoop: for (let i = 0; i < list.length; i++) {
  11689. const currentSelectorInList = list[i];
  11690. if (selector.length !== currentSelectorInList.length) {
  11691. continue;
  11692. }
  11693. for (let j = 0; j < selector.length; j++) {
  11694. if (selector[j] !== currentSelectorInList[j]) {
  11695. continue selectorListLoop;
  11696. }
  11697. }
  11698. return true;
  11699. }
  11700. return false;
  11701. }
  11702. function maybeWrapInNotSelector(isNegativeMode, chunk) {
  11703. return isNegativeMode ? ':not(' + chunk.trim() + ')' : chunk;
  11704. }
  11705. function stringifyCSSSelector(selector) {
  11706. let result = selector[0];
  11707. let i = 1;
  11708. let mode = 2 /* SelectorFlags.ATTRIBUTE */;
  11709. let currentChunk = '';
  11710. let isNegativeMode = false;
  11711. while (i < selector.length) {
  11712. let valueOrMarker = selector[i];
  11713. if (typeof valueOrMarker === 'string') {
  11714. if (mode & 2 /* SelectorFlags.ATTRIBUTE */) {
  11715. const attrValue = selector[++i];
  11716. currentChunk +=
  11717. '[' + valueOrMarker + (attrValue.length > 0 ? '="' + attrValue + '"' : '') + ']';
  11718. }
  11719. else if (mode & 8 /* SelectorFlags.CLASS */) {
  11720. currentChunk += '.' + valueOrMarker;
  11721. }
  11722. else if (mode & 4 /* SelectorFlags.ELEMENT */) {
  11723. currentChunk += ' ' + valueOrMarker;
  11724. }
  11725. }
  11726. else {
  11727. //
  11728. // Append current chunk to the final result in case we come across SelectorFlag, which
  11729. // indicates that the previous section of a selector is over. We need to accumulate content
  11730. // between flags to make sure we wrap the chunk later in :not() selector if needed, e.g.
  11731. // ```
  11732. // ['', Flags.CLASS, '.classA', Flags.CLASS | Flags.NOT, '.classB', '.classC']
  11733. // ```
  11734. // should be transformed to `.classA :not(.classB .classC)`.
  11735. //
  11736. // Note: for negative selector part, we accumulate content between flags until we find the
  11737. // next negative flag. This is needed to support a case where `:not()` rule contains more than
  11738. // one chunk, e.g. the following selector:
  11739. // ```
  11740. // ['', Flags.ELEMENT | Flags.NOT, 'p', Flags.CLASS, 'foo', Flags.CLASS | Flags.NOT, 'bar']
  11741. // ```
  11742. // should be stringified to `:not(p.foo) :not(.bar)`
  11743. //
  11744. if (currentChunk !== '' && !isPositive(valueOrMarker)) {
  11745. result += maybeWrapInNotSelector(isNegativeMode, currentChunk);
  11746. currentChunk = '';
  11747. }
  11748. mode = valueOrMarker;
  11749. // According to CssSelector spec, once we come across `SelectorFlags.NOT` flag, the negative
  11750. // mode is maintained for remaining chunks of a selector.
  11751. isNegativeMode = isNegativeMode || !isPositive(mode);
  11752. }
  11753. i++;
  11754. }
  11755. if (currentChunk !== '') {
  11756. result += maybeWrapInNotSelector(isNegativeMode, currentChunk);
  11757. }
  11758. return result;
  11759. }
  11760. /**
  11761. * Generates string representation of CSS selector in parsed form.
  11762. *
  11763. * ComponentDef and DirectiveDef are generated with the selector in parsed form to avoid doing
  11764. * additional parsing at runtime (for example, for directive matching). However in some cases (for
  11765. * example, while bootstrapping a component), a string version of the selector is required to query
  11766. * for the host element on the page. This function takes the parsed form of a selector and returns
  11767. * its string representation.
  11768. *
  11769. * @param selectorList selector in parsed form
  11770. * @returns string representation of a given selector
  11771. */
  11772. function stringifyCSSSelectorList(selectorList) {
  11773. return selectorList.map(stringifyCSSSelector).join(',');
  11774. }
  11775. /**
  11776. * Extracts attributes and classes information from a given CSS selector.
  11777. *
  11778. * This function is used while creating a component dynamically. In this case, the host element
  11779. * (that is created dynamically) should contain attributes and classes specified in component's CSS
  11780. * selector.
  11781. *
  11782. * @param selector CSS selector in parsed form (in a form of array)
  11783. * @returns object with `attrs` and `classes` fields that contain extracted information
  11784. */
  11785. function extractAttrsAndClassesFromSelector(selector) {
  11786. const attrs = [];
  11787. const classes = [];
  11788. let i = 1;
  11789. let mode = 2 /* SelectorFlags.ATTRIBUTE */;
  11790. while (i < selector.length) {
  11791. let valueOrMarker = selector[i];
  11792. if (typeof valueOrMarker === 'string') {
  11793. if (mode === 2 /* SelectorFlags.ATTRIBUTE */) {
  11794. if (valueOrMarker !== '') {
  11795. attrs.push(valueOrMarker, selector[++i]);
  11796. }
  11797. }
  11798. else if (mode === 8 /* SelectorFlags.CLASS */) {
  11799. classes.push(valueOrMarker);
  11800. }
  11801. }
  11802. else {
  11803. // According to CssSelector spec, once we come across `SelectorFlags.NOT` flag, the negative
  11804. // mode is maintained for remaining chunks of a selector. Since attributes and classes are
  11805. // extracted only for "positive" part of the selector, we can stop here.
  11806. if (!isPositive(mode))
  11807. break;
  11808. mode = valueOrMarker;
  11809. }
  11810. i++;
  11811. }
  11812. if (classes.length) {
  11813. attrs.push(1 /* AttributeMarker.Classes */, ...classes);
  11814. }
  11815. return attrs;
  11816. }
  11817. /** A special value which designates that a value has not changed. */
  11818. const NO_CHANGE = typeof ngDevMode === 'undefined' || ngDevMode ? { __brand__: 'NO_CHANGE' } : {};
  11819. function createTextNode(renderer, value) {
  11820. ngDevMode && ngDevMode.rendererCreateTextNode++;
  11821. ngDevMode && ngDevMode.rendererSetText++;
  11822. return renderer.createText(value);
  11823. }
  11824. function updateTextNode(renderer, rNode, value) {
  11825. ngDevMode && ngDevMode.rendererSetText++;
  11826. renderer.setValue(rNode, value);
  11827. }
  11828. function createCommentNode(renderer, value) {
  11829. ngDevMode && ngDevMode.rendererCreateComment++;
  11830. return renderer.createComment(escapeCommentText(value));
  11831. }
  11832. /**
  11833. * Creates a native element from a tag name, using a renderer.
  11834. * @param renderer A renderer to use
  11835. * @param name the tag name
  11836. * @param namespace Optional namespace for element.
  11837. * @returns the element created
  11838. */
  11839. function createElementNode(renderer, name, namespace) {
  11840. ngDevMode && ngDevMode.rendererCreateElement++;
  11841. return renderer.createElement(name, namespace);
  11842. }
  11843. /**
  11844. * Inserts a native node before another native node for a given parent.
  11845. * This is a utility function that can be used when native nodes were determined.
  11846. */
  11847. function nativeInsertBefore(renderer, parent, child, beforeNode, isMove) {
  11848. ngDevMode && ngDevMode.rendererInsertBefore++;
  11849. renderer.insertBefore(parent, child, beforeNode, isMove);
  11850. }
  11851. function nativeAppendChild(renderer, parent, child) {
  11852. ngDevMode && ngDevMode.rendererAppendChild++;
  11853. ngDevMode && assertDefined(parent, 'parent node must be defined');
  11854. renderer.appendChild(parent, child);
  11855. }
  11856. function nativeAppendOrInsertBefore(renderer, parent, child, beforeNode, isMove) {
  11857. if (beforeNode !== null) {
  11858. nativeInsertBefore(renderer, parent, child, beforeNode, isMove);
  11859. }
  11860. else {
  11861. nativeAppendChild(renderer, parent, child);
  11862. }
  11863. }
  11864. /**
  11865. * Removes a native node itself using a given renderer. To remove the node we are looking up its
  11866. * parent from the native tree as not all platforms / browsers support the equivalent of
  11867. * node.remove().
  11868. *
  11869. * @param renderer A renderer to be used
  11870. * @param rNode The native node that should be removed
  11871. * @param isHostElement A flag indicating if a node to be removed is a host of a component.
  11872. */
  11873. function nativeRemoveNode(renderer, rNode, isHostElement) {
  11874. ngDevMode && ngDevMode.rendererRemoveNode++;
  11875. renderer.removeChild(null, rNode, isHostElement);
  11876. }
  11877. /**
  11878. * Clears the contents of a given RElement.
  11879. *
  11880. * @param rElement the native RElement to be cleared
  11881. */
  11882. function clearElementContents(rElement) {
  11883. rElement.textContent = '';
  11884. }
  11885. /**
  11886. * Write `cssText` to `RElement`.
  11887. *
  11888. * This function does direct write without any reconciliation. Used for writing initial values, so
  11889. * that static styling values do not pull in the style parser.
  11890. *
  11891. * @param renderer Renderer to use
  11892. * @param element The element which needs to be updated.
  11893. * @param newValue The new class list to write.
  11894. */
  11895. function writeDirectStyle(renderer, element, newValue) {
  11896. ngDevMode && assertString(newValue, "'newValue' should be a string");
  11897. renderer.setAttribute(element, 'style', newValue);
  11898. ngDevMode && ngDevMode.rendererSetStyle++;
  11899. }
  11900. /**
  11901. * Write `className` to `RElement`.
  11902. *
  11903. * This function does direct write without any reconciliation. Used for writing initial values, so
  11904. * that static styling values do not pull in the style parser.
  11905. *
  11906. * @param renderer Renderer to use
  11907. * @param element The element which needs to be updated.
  11908. * @param newValue The new class list to write.
  11909. */
  11910. function writeDirectClass(renderer, element, newValue) {
  11911. ngDevMode && assertString(newValue, "'newValue' should be a string");
  11912. if (newValue === '') {
  11913. // There are tests in `google3` which expect `element.getAttribute('class')` to be `null`.
  11914. renderer.removeAttribute(element, 'class');
  11915. }
  11916. else {
  11917. renderer.setAttribute(element, 'class', newValue);
  11918. }
  11919. ngDevMode && ngDevMode.rendererSetClassName++;
  11920. }
  11921. /** Sets up the static DOM attributes on an `RNode`. */
  11922. function setupStaticAttributes(renderer, element, tNode) {
  11923. const { mergedAttrs, classes, styles } = tNode;
  11924. if (mergedAttrs !== null) {
  11925. setUpAttributes(renderer, element, mergedAttrs);
  11926. }
  11927. if (classes !== null) {
  11928. writeDirectClass(renderer, element, classes);
  11929. }
  11930. if (styles !== null) {
  11931. writeDirectStyle(renderer, element, styles);
  11932. }
  11933. }
  11934. /**
  11935. * Creates a TView instance
  11936. *
  11937. * @param type Type of `TView`.
  11938. * @param declTNode Declaration location of this `TView`.
  11939. * @param templateFn Template function
  11940. * @param decls The number of nodes, local refs, and pipes in this template
  11941. * @param directives Registry of directives for this view
  11942. * @param pipes Registry of pipes for this view
  11943. * @param viewQuery View queries for this view
  11944. * @param schemas Schemas for this view
  11945. * @param consts Constants for this view
  11946. */
  11947. function createTView(type, declTNode, templateFn, decls, vars, directives, pipes, viewQuery, schemas, constsOrFactory, ssrId) {
  11948. ngDevMode && ngDevMode.tView++;
  11949. const bindingStartIndex = HEADER_OFFSET + decls;
  11950. // This length does not yet contain host bindings from child directives because at this point,
  11951. // we don't know which directives are active on this template. As soon as a directive is matched
  11952. // that has a host binding, we will update the blueprint with that def's hostVars count.
  11953. const initialViewLength = bindingStartIndex + vars;
  11954. const blueprint = createViewBlueprint(bindingStartIndex, initialViewLength);
  11955. const consts = typeof constsOrFactory === 'function' ? constsOrFactory() : constsOrFactory;
  11956. const tView = (blueprint[TVIEW] = {
  11957. type: type,
  11958. blueprint: blueprint,
  11959. template: templateFn,
  11960. queries: null,
  11961. viewQuery: viewQuery,
  11962. declTNode: declTNode,
  11963. data: blueprint.slice().fill(null, bindingStartIndex),
  11964. bindingStartIndex: bindingStartIndex,
  11965. expandoStartIndex: initialViewLength,
  11966. hostBindingOpCodes: null,
  11967. firstCreatePass: true,
  11968. firstUpdatePass: true,
  11969. staticViewQueries: false,
  11970. staticContentQueries: false,
  11971. preOrderHooks: null,
  11972. preOrderCheckHooks: null,
  11973. contentHooks: null,
  11974. contentCheckHooks: null,
  11975. viewHooks: null,
  11976. viewCheckHooks: null,
  11977. destroyHooks: null,
  11978. cleanup: null,
  11979. contentQueries: null,
  11980. components: null,
  11981. directiveRegistry: typeof directives === 'function' ? directives() : directives,
  11982. pipeRegistry: typeof pipes === 'function' ? pipes() : pipes,
  11983. firstChild: null,
  11984. schemas: schemas,
  11985. consts: consts,
  11986. incompleteFirstPass: false,
  11987. ssrId,
  11988. });
  11989. if (ngDevMode) {
  11990. // For performance reasons it is important that the tView retains the same shape during runtime.
  11991. // (To make sure that all of the code is monomorphic.) For this reason we seal the object to
  11992. // prevent class transitions.
  11993. Object.seal(tView);
  11994. }
  11995. return tView;
  11996. }
  11997. function createViewBlueprint(bindingStartIndex, initialViewLength) {
  11998. const blueprint = [];
  11999. for (let i = 0; i < initialViewLength; i++) {
  12000. blueprint.push(i < bindingStartIndex ? null : NO_CHANGE);
  12001. }
  12002. return blueprint;
  12003. }
  12004. /**
  12005. * Gets TView from a template function or creates a new TView
  12006. * if it doesn't already exist.
  12007. *
  12008. * @param def ComponentDef
  12009. * @returns TView
  12010. */
  12011. function getOrCreateComponentTView(def) {
  12012. const tView = def.tView;
  12013. // Create a TView if there isn't one, or recreate it if the first create pass didn't
  12014. // complete successfully since we can't know for sure whether it's in a usable shape.
  12015. if (tView === null || tView.incompleteFirstPass) {
  12016. // Declaration node here is null since this function is called when we dynamically create a
  12017. // component and hence there is no declaration.
  12018. const declTNode = null;
  12019. return (def.tView = createTView(1 /* TViewType.Component */, declTNode, def.template, def.decls, def.vars, def.directiveDefs, def.pipeDefs, def.viewQuery, def.schemas, def.consts, def.id));
  12020. }
  12021. return tView;
  12022. }
  12023. function createLView(parentLView, tView, context, flags, host, tHostNode, environment, renderer, injector, embeddedViewInjector, hydrationInfo) {
  12024. const lView = tView.blueprint.slice();
  12025. lView[HOST] = host;
  12026. lView[FLAGS] =
  12027. flags |
  12028. 4 /* LViewFlags.CreationMode */ |
  12029. 128 /* LViewFlags.Attached */ |
  12030. 8 /* LViewFlags.FirstLViewPass */ |
  12031. 64 /* LViewFlags.Dirty */ |
  12032. 1024 /* LViewFlags.RefreshView */;
  12033. if (embeddedViewInjector !== null ||
  12034. (parentLView && parentLView[FLAGS] & 2048 /* LViewFlags.HasEmbeddedViewInjector */)) {
  12035. lView[FLAGS] |= 2048 /* LViewFlags.HasEmbeddedViewInjector */;
  12036. }
  12037. resetPreOrderHookFlags(lView);
  12038. ngDevMode && tView.declTNode && parentLView && assertTNodeForLView(tView.declTNode, parentLView);
  12039. lView[PARENT] = lView[DECLARATION_VIEW] = parentLView;
  12040. lView[CONTEXT] = context;
  12041. lView[ENVIRONMENT] = (environment || (parentLView && parentLView[ENVIRONMENT]));
  12042. ngDevMode && assertDefined(lView[ENVIRONMENT], 'LViewEnvironment is required');
  12043. lView[RENDERER] = (renderer || (parentLView && parentLView[RENDERER]));
  12044. ngDevMode && assertDefined(lView[RENDERER], 'Renderer is required');
  12045. lView[INJECTOR] = injector || (parentLView && parentLView[INJECTOR]) || null;
  12046. lView[T_HOST] = tHostNode;
  12047. lView[ID] = getUniqueLViewId();
  12048. lView[HYDRATION] = hydrationInfo;
  12049. lView[EMBEDDED_VIEW_INJECTOR] = embeddedViewInjector;
  12050. ngDevMode &&
  12051. assertEqual(tView.type == 2 /* TViewType.Embedded */ ? parentLView !== null : true, true, 'Embedded views must have parentLView');
  12052. lView[DECLARATION_COMPONENT_VIEW] =
  12053. tView.type == 2 /* TViewType.Embedded */ ? parentLView[DECLARATION_COMPONENT_VIEW] : lView;
  12054. return lView;
  12055. }
  12056. function createComponentLView(lView, hostTNode, def) {
  12057. const native = getNativeByTNode(hostTNode, lView);
  12058. const tView = getOrCreateComponentTView(def);
  12059. // Only component views should be added to the view tree directly. Embedded views are
  12060. // accessed through their containers because they may be removed / re-added later.
  12061. const rendererFactory = lView[ENVIRONMENT].rendererFactory;
  12062. const componentView = addToEndOfViewTree(lView, createLView(lView, tView, null, getInitialLViewFlagsFromDef(def), native, hostTNode, null, rendererFactory.createRenderer(native, def), null, null, null));
  12063. // Component view will always be created before any injected LContainers,
  12064. // so this is a regular element, wrap it with the component view
  12065. return (lView[hostTNode.index] = componentView);
  12066. }
  12067. /**
  12068. * Gets the initial set of LView flags based on the component definition that the LView represents.
  12069. * @param def Component definition from which to determine the flags.
  12070. */
  12071. function getInitialLViewFlagsFromDef(def) {
  12072. let flags = 16 /* LViewFlags.CheckAlways */;
  12073. if (def.signals) {
  12074. flags = 4096 /* LViewFlags.SignalView */;
  12075. }
  12076. else if (def.onPush) {
  12077. flags = 64 /* LViewFlags.Dirty */;
  12078. }
  12079. return flags;
  12080. }
  12081. /**
  12082. * When elements are created dynamically after a view blueprint is created (e.g. through
  12083. * i18nApply()), we need to adjust the blueprint for future template passes.
  12084. *
  12085. * @param tView `TView` associated with `LView`
  12086. * @param lView The `LView` containing the blueprint to adjust
  12087. * @param numSlotsToAlloc The number of slots to alloc in the LView, should be >0
  12088. * @param initialValue Initial value to store in blueprint
  12089. */
  12090. function allocExpando(tView, lView, numSlotsToAlloc, initialValue) {
  12091. if (numSlotsToAlloc === 0)
  12092. return -1;
  12093. if (ngDevMode) {
  12094. assertFirstCreatePass(tView);
  12095. assertSame(tView, lView[TVIEW], '`LView` must be associated with `TView`!');
  12096. assertEqual(tView.data.length, lView.length, 'Expecting LView to be same size as TView');
  12097. assertEqual(tView.data.length, tView.blueprint.length, 'Expecting Blueprint to be same size as TView');
  12098. assertFirstUpdatePass(tView);
  12099. }
  12100. const allocIdx = lView.length;
  12101. for (let i = 0; i < numSlotsToAlloc; i++) {
  12102. lView.push(initialValue);
  12103. tView.blueprint.push(initialValue);
  12104. tView.data.push(null);
  12105. }
  12106. return allocIdx;
  12107. }
  12108. /**
  12109. * Adds LView or LContainer to the end of the current view tree.
  12110. *
  12111. * This structure will be used to traverse through nested views to remove listeners
  12112. * and call onDestroy callbacks.
  12113. *
  12114. * @param lView The view where LView or LContainer should be added
  12115. * @param adjustedHostIndex Index of the view's host node in LView[], adjusted for header
  12116. * @param lViewOrLContainer The LView or LContainer to add to the view tree
  12117. * @returns The state passed in
  12118. */
  12119. function addToEndOfViewTree(lView, lViewOrLContainer) {
  12120. // TODO(benlesh/misko): This implementation is incorrect, because it always adds the LContainer
  12121. // to the end of the queue, which means if the developer retrieves the LContainers from RNodes out
  12122. // of order, the change detection will run out of order, as the act of retrieving the the
  12123. // LContainer from the RNode is what adds it to the queue.
  12124. if (lView[CHILD_HEAD]) {
  12125. lView[CHILD_TAIL][NEXT] = lViewOrLContainer;
  12126. }
  12127. else {
  12128. lView[CHILD_HEAD] = lViewOrLContainer;
  12129. }
  12130. lView[CHILD_TAIL] = lViewOrLContainer;
  12131. return lViewOrLContainer;
  12132. }
  12133. /**
  12134. * Advances to an element for later binding instructions.
  12135. *
  12136. * Used in conjunction with instructions like {@link property} to act on elements with specified
  12137. * indices, for example those created with {@link element} or {@link elementStart}.
  12138. *
  12139. * ```ts
  12140. * (rf: RenderFlags, ctx: any) => {
  12141. * if (rf & 1) {
  12142. * text(0, 'Hello');
  12143. * text(1, 'Goodbye')
  12144. * element(2, 'div');
  12145. * }
  12146. * if (rf & 2) {
  12147. * advance(2); // Advance twice to the <div>.
  12148. * property('title', 'test');
  12149. * }
  12150. * }
  12151. * ```
  12152. * @param delta Number of elements to advance forwards by.
  12153. *
  12154. * @codeGenApi
  12155. */
  12156. function ɵɵadvance(delta = 1) {
  12157. ngDevMode && assertGreaterThan(delta, 0, 'Can only advance forward');
  12158. selectIndexInternal(getTView(), getLView(), getSelectedIndex() + delta, !!ngDevMode && isInCheckNoChangesMode());
  12159. }
  12160. function selectIndexInternal(tView, lView, index, checkNoChangesMode) {
  12161. ngDevMode && assertIndexInDeclRange(lView[TVIEW], index);
  12162. // Flush the initial hooks for elements in the view that have been added up to this point.
  12163. // PERF WARNING: do NOT extract this to a separate function without running benchmarks
  12164. if (!checkNoChangesMode) {
  12165. const hooksInitPhaseCompleted = (lView[FLAGS] & 3 /* LViewFlags.InitPhaseStateMask */) === 3 /* InitPhaseState.InitPhaseCompleted */;
  12166. if (hooksInitPhaseCompleted) {
  12167. const preOrderCheckHooks = tView.preOrderCheckHooks;
  12168. if (preOrderCheckHooks !== null) {
  12169. executeCheckHooks(lView, preOrderCheckHooks, index);
  12170. }
  12171. }
  12172. else {
  12173. const preOrderHooks = tView.preOrderHooks;
  12174. if (preOrderHooks !== null) {
  12175. executeInitAndCheckHooks(lView, preOrderHooks, 0 /* InitPhaseState.OnInitHooksToBeRun */, index);
  12176. }
  12177. }
  12178. }
  12179. // We must set the selected index *after* running the hooks, because hooks may have side-effects
  12180. // that cause other template functions to run, thus updating the selected index, which is global
  12181. // state. If we run `setSelectedIndex` *before* we run the hooks, in some cases the selected index
  12182. // will be altered by the time we leave the `ɵɵadvance` instruction.
  12183. setSelectedIndex(index);
  12184. }
  12185. /** Flags describing an input for a directive. */
  12186. var InputFlags;
  12187. (function (InputFlags) {
  12188. InputFlags[InputFlags["None"] = 0] = "None";
  12189. InputFlags[InputFlags["SignalBased"] = 1] = "SignalBased";
  12190. InputFlags[InputFlags["HasDecoratorInputTransform"] = 2] = "HasDecoratorInputTransform";
  12191. })(InputFlags || (InputFlags = {}));
  12192. function writeToDirectiveInput(def, instance, publicName, value) {
  12193. const prevConsumer = setActiveConsumer$1(null);
  12194. try {
  12195. if (ngDevMode) {
  12196. if (!def.inputs.hasOwnProperty(publicName)) {
  12197. throw new Error(`ASSERTION ERROR: Directive ${def.type.name} does not have an input with a public name of "${publicName}"`);
  12198. }
  12199. // Usually we resolve the directive instance using `LView[someIndex]` before writing to an
  12200. // input, however if the read happens to early, the `LView[someIndex]` might actually be a
  12201. // `NodeInjectorFactory`. Check for this specific case here since it can break in subtle ways.
  12202. if (instance instanceof NodeInjectorFactory) {
  12203. throw new Error(`ASSERTION ERROR: Cannot write input to factory for type ${def.type.name}. Directive has not been created yet.`);
  12204. }
  12205. }
  12206. const [privateName, flags, transform] = def.inputs[publicName];
  12207. // If we know we are dealing with a signal input, we cache its reference
  12208. // in a tree-shakable way. The input signal node can then be used for
  12209. // value transform execution or actual value updates without introducing
  12210. // additional megamorphic accesses for accessing the instance field.
  12211. let inputSignalNode = null;
  12212. if ((flags & InputFlags.SignalBased) !== 0) {
  12213. const field = instance[privateName];
  12214. inputSignalNode = field[SIGNAL];
  12215. }
  12216. // If there is a signal node and a transform, run it before potentially
  12217. // delegating to features like `NgOnChanges`.
  12218. if (inputSignalNode !== null && inputSignalNode.transformFn !== undefined) {
  12219. value = inputSignalNode.transformFn(value);
  12220. }
  12221. else if (transform !== null) {
  12222. // If there is a decorator input transform, run it.
  12223. value = transform.call(instance, value);
  12224. }
  12225. if (def.setInput !== null) {
  12226. def.setInput(instance, inputSignalNode, value, publicName, privateName);
  12227. }
  12228. else {
  12229. applyValueToInputField(instance, inputSignalNode, privateName, value);
  12230. }
  12231. }
  12232. finally {
  12233. setActiveConsumer$1(prevConsumer);
  12234. }
  12235. }
  12236. function executeTemplate(tView, lView, templateFn, rf, context) {
  12237. const prevSelectedIndex = getSelectedIndex();
  12238. const isUpdatePhase = rf & 2 /* RenderFlags.Update */;
  12239. try {
  12240. setSelectedIndex(-1);
  12241. if (isUpdatePhase && lView.length > HEADER_OFFSET) {
  12242. // When we're updating, inherently select 0 so we don't
  12243. // have to generate that instruction for most update blocks.
  12244. selectIndexInternal(tView, lView, HEADER_OFFSET, !!ngDevMode && isInCheckNoChangesMode());
  12245. }
  12246. const preHookType = isUpdatePhase
  12247. ? 2 /* ProfilerEvent.TemplateUpdateStart */
  12248. : 0 /* ProfilerEvent.TemplateCreateStart */;
  12249. profiler(preHookType, context);
  12250. templateFn(rf, context);
  12251. }
  12252. finally {
  12253. setSelectedIndex(prevSelectedIndex);
  12254. const postHookType = isUpdatePhase
  12255. ? 3 /* ProfilerEvent.TemplateUpdateEnd */
  12256. : 1 /* ProfilerEvent.TemplateCreateEnd */;
  12257. profiler(postHookType, context);
  12258. }
  12259. }
  12260. /**
  12261. * Creates directive instances.
  12262. */
  12263. function createDirectivesInstances(tView, lView, tNode) {
  12264. instantiateAllDirectives(tView, lView, tNode);
  12265. if ((tNode.flags & 64 /* TNodeFlags.hasHostBindings */) === 64 /* TNodeFlags.hasHostBindings */) {
  12266. invokeDirectivesHostBindings(tView, lView, tNode);
  12267. }
  12268. }
  12269. /**
  12270. * Takes a list of local names and indices and pushes the resolved local variable values
  12271. * to LView in the same order as they are loaded in the template with load().
  12272. */
  12273. function saveResolvedLocalsInData(viewData, tNode, localRefExtractor = getNativeByTNode) {
  12274. const localNames = tNode.localNames;
  12275. if (localNames !== null) {
  12276. let localIndex = tNode.index + 1;
  12277. for (let i = 0; i < localNames.length; i += 2) {
  12278. const index = localNames[i + 1];
  12279. const value = index === -1
  12280. ? localRefExtractor(tNode, viewData)
  12281. : viewData[index];
  12282. viewData[localIndex++] = value;
  12283. }
  12284. }
  12285. }
  12286. /**
  12287. * Locates the host native element, used for bootstrapping existing nodes into rendering pipeline.
  12288. *
  12289. * @param renderer the renderer used to locate the element.
  12290. * @param elementOrSelector Render element or CSS selector to locate the element.
  12291. * @param encapsulation View Encapsulation defined for component that requests host element.
  12292. * @param injector Root view injector instance.
  12293. */
  12294. function locateHostElement(renderer, elementOrSelector, encapsulation, injector) {
  12295. // Note: we use default value for the `PRESERVE_HOST_CONTENT` here even though it's a
  12296. // tree-shakable one (providedIn:'root'). This code path can be triggered during dynamic
  12297. // component creation (after calling ViewContainerRef.createComponent) when an injector
  12298. // instance can be provided. The injector instance might be disconnected from the main DI
  12299. // tree, thus the `PRESERVE_HOST_CONTENT` would not be able to instantiate. In this case, the
  12300. // default value will be used.
  12301. const preserveHostContent = injector.get(PRESERVE_HOST_CONTENT, PRESERVE_HOST_CONTENT_DEFAULT);
  12302. // When using native Shadow DOM, do not clear host element to allow native slot
  12303. // projection.
  12304. const preserveContent = preserveHostContent || encapsulation === ViewEncapsulation.ShadowDom;
  12305. const rootElement = renderer.selectRootElement(elementOrSelector, preserveContent);
  12306. applyRootElementTransform(rootElement);
  12307. return rootElement;
  12308. }
  12309. /**
  12310. * Applies any root element transformations that are needed. If hydration is enabled,
  12311. * this will process corrupted text nodes.
  12312. *
  12313. * @param rootElement the app root HTML Element
  12314. */
  12315. function applyRootElementTransform(rootElement) {
  12316. _applyRootElementTransformImpl(rootElement);
  12317. }
  12318. /**
  12319. * Reference to a function that applies transformations to the root HTML element
  12320. * of an app. When hydration is enabled, this processes any corrupt text nodes
  12321. * so they are properly hydratable on the client.
  12322. *
  12323. * @param rootElement the app root HTML Element
  12324. */
  12325. let _applyRootElementTransformImpl = () => null;
  12326. /**
  12327. * Processes text node markers before hydration begins. This replaces any special comment
  12328. * nodes that were added prior to serialization are swapped out to restore proper text
  12329. * nodes before hydration.
  12330. *
  12331. * @param rootElement the app root HTML Element
  12332. */
  12333. function applyRootElementTransformImpl(rootElement) {
  12334. if (hasSkipHydrationAttrOnRElement(rootElement)) {
  12335. // Handle a situation when the `ngSkipHydration` attribute is applied
  12336. // to the root node of an application. In this case, we should clear
  12337. // the contents and render everything from scratch.
  12338. clearElementContents(rootElement);
  12339. }
  12340. else {
  12341. processTextNodeMarkersBeforeHydration(rootElement);
  12342. }
  12343. }
  12344. /**
  12345. * Sets the implementation for the `applyRootElementTransform` function.
  12346. */
  12347. function enableApplyRootElementTransformImpl() {
  12348. _applyRootElementTransformImpl = applyRootElementTransformImpl;
  12349. }
  12350. /**
  12351. * Mapping between attributes names that don't correspond to their element property names.
  12352. *
  12353. * Performance note: this function is written as a series of if checks (instead of, say, a property
  12354. * object lookup) for performance reasons - the series of `if` checks seems to be the fastest way of
  12355. * mapping property names. Do NOT change without benchmarking.
  12356. *
  12357. * Note: this mapping has to be kept in sync with the equally named mapping in the template
  12358. * type-checking machinery of ngtsc.
  12359. */
  12360. function mapPropName(name) {
  12361. if (name === 'class')
  12362. return 'className';
  12363. if (name === 'for')
  12364. return 'htmlFor';
  12365. if (name === 'formaction')
  12366. return 'formAction';
  12367. if (name === 'innerHtml')
  12368. return 'innerHTML';
  12369. if (name === 'readonly')
  12370. return 'readOnly';
  12371. if (name === 'tabindex')
  12372. return 'tabIndex';
  12373. return name;
  12374. }
  12375. function elementPropertyInternal(tView, tNode, lView, propName, value, renderer, sanitizer, nativeOnly) {
  12376. ngDevMode && assertNotSame(value, NO_CHANGE, 'Incoming value should never be NO_CHANGE.');
  12377. if (!nativeOnly) {
  12378. const hasSetInput = setAllInputsForProperty(tNode, tView, lView, propName, value);
  12379. if (hasSetInput) {
  12380. isComponentHost(tNode) && markDirtyIfOnPush(lView, tNode.index);
  12381. ngDevMode && setNgReflectProperties(lView, tView, tNode, propName, value);
  12382. return; // Stop propcessing if we've matched at least one input.
  12383. }
  12384. }
  12385. if (tNode.type & 3 /* TNodeType.AnyRNode */) {
  12386. const element = getNativeByTNode(tNode, lView);
  12387. propName = mapPropName(propName);
  12388. if (ngDevMode) {
  12389. validateAgainstEventProperties(propName);
  12390. if (!isPropertyValid(element, propName, tNode.value, tView.schemas)) {
  12391. handleUnknownPropertyError(propName, tNode.value, tNode.type, lView);
  12392. }
  12393. ngDevMode.rendererSetProperty++;
  12394. }
  12395. // It is assumed that the sanitizer is only added when the compiler determines that the
  12396. // property is risky, so sanitization can be done without further checks.
  12397. value = sanitizer != null ? sanitizer(value, tNode.value || '', propName) : value;
  12398. renderer.setProperty(element, propName, value);
  12399. }
  12400. else if (tNode.type & 12 /* TNodeType.AnyContainer */) {
  12401. // If the node is a container and the property didn't
  12402. // match any of the inputs or schemas we should throw.
  12403. if (ngDevMode && !matchingSchemas(tView.schemas, tNode.value)) {
  12404. handleUnknownPropertyError(propName, tNode.value, tNode.type, lView);
  12405. }
  12406. }
  12407. }
  12408. /** If node is an OnPush component, marks its LView dirty. */
  12409. function markDirtyIfOnPush(lView, viewIndex) {
  12410. ngDevMode && assertLView(lView);
  12411. const childComponentLView = getComponentLViewByIndex(viewIndex, lView);
  12412. if (!(childComponentLView[FLAGS] & 16 /* LViewFlags.CheckAlways */)) {
  12413. childComponentLView[FLAGS] |= 64 /* LViewFlags.Dirty */;
  12414. }
  12415. }
  12416. function setNgReflectProperty(lView, tNode, attrName, value) {
  12417. const element = getNativeByTNode(tNode, lView);
  12418. const renderer = lView[RENDERER];
  12419. attrName = normalizeDebugBindingName(attrName);
  12420. const debugValue = normalizeDebugBindingValue(value);
  12421. if (tNode.type & 3 /* TNodeType.AnyRNode */) {
  12422. if (value == null) {
  12423. renderer.removeAttribute(element, attrName);
  12424. }
  12425. else {
  12426. renderer.setAttribute(element, attrName, debugValue);
  12427. }
  12428. }
  12429. else {
  12430. const textContent = escapeCommentText(`bindings=${JSON.stringify({ [attrName]: debugValue }, null, 2)}`);
  12431. renderer.setValue(element, textContent);
  12432. }
  12433. }
  12434. function setNgReflectProperties(lView, tView, tNode, publicName, value) {
  12435. if (!(tNode.type & (3 /* TNodeType.AnyRNode */ | 4 /* TNodeType.Container */))) {
  12436. return;
  12437. }
  12438. const inputConfig = tNode.inputs?.[publicName];
  12439. const hostInputConfig = tNode.hostDirectiveInputs?.[publicName];
  12440. if (hostInputConfig) {
  12441. for (let i = 0; i < hostInputConfig.length; i += 2) {
  12442. const index = hostInputConfig[i];
  12443. const publicName = hostInputConfig[i + 1];
  12444. const def = tView.data[index];
  12445. setNgReflectProperty(lView, tNode, def.inputs[publicName][0], value);
  12446. }
  12447. }
  12448. // Note: we set the private name of the input as the reflected property, not the public one.
  12449. if (inputConfig) {
  12450. for (const index of inputConfig) {
  12451. const def = tView.data[index];
  12452. setNgReflectProperty(lView, tNode, def.inputs[publicName][0], value);
  12453. }
  12454. }
  12455. }
  12456. /**
  12457. * Instantiate all the directives that were previously resolved on the current node.
  12458. */
  12459. function instantiateAllDirectives(tView, lView, tNode) {
  12460. const start = tNode.directiveStart;
  12461. const end = tNode.directiveEnd;
  12462. // The component view needs to be created before creating the node injector
  12463. // since it is used to inject some special symbols like `ChangeDetectorRef`.
  12464. if (isComponentHost(tNode)) {
  12465. ngDevMode && assertTNodeType(tNode, 3 /* TNodeType.AnyRNode */);
  12466. createComponentLView(lView, tNode, tView.data[start + tNode.componentOffset]);
  12467. }
  12468. if (!tView.firstCreatePass) {
  12469. getOrCreateNodeInjectorForNode(tNode, lView);
  12470. }
  12471. const initialInputs = tNode.initialInputs;
  12472. for (let i = start; i < end; i++) {
  12473. const def = tView.data[i];
  12474. const directive = getNodeInjectable(lView, tView, i, tNode);
  12475. attachPatchData(directive, lView);
  12476. if (initialInputs !== null) {
  12477. setInputsFromAttrs(lView, i - start, directive, def, tNode, initialInputs);
  12478. }
  12479. if (isComponentDef(def)) {
  12480. const componentView = getComponentLViewByIndex(tNode.index, lView);
  12481. componentView[CONTEXT] = getNodeInjectable(lView, tView, i, tNode);
  12482. }
  12483. }
  12484. }
  12485. function invokeDirectivesHostBindings(tView, lView, tNode) {
  12486. const start = tNode.directiveStart;
  12487. const end = tNode.directiveEnd;
  12488. const elementIndex = tNode.index;
  12489. const currentDirectiveIndex = getCurrentDirectiveIndex();
  12490. try {
  12491. setSelectedIndex(elementIndex);
  12492. for (let dirIndex = start; dirIndex < end; dirIndex++) {
  12493. const def = tView.data[dirIndex];
  12494. const directive = lView[dirIndex];
  12495. setCurrentDirectiveIndex(dirIndex);
  12496. if (def.hostBindings !== null || def.hostVars !== 0 || def.hostAttrs !== null) {
  12497. invokeHostBindingsInCreationMode(def, directive);
  12498. }
  12499. }
  12500. }
  12501. finally {
  12502. setSelectedIndex(-1);
  12503. setCurrentDirectiveIndex(currentDirectiveIndex);
  12504. }
  12505. }
  12506. /**
  12507. * Invoke the host bindings in creation mode.
  12508. *
  12509. * @param def `DirectiveDef` which may contain the `hostBindings` function.
  12510. * @param directive Instance of directive.
  12511. */
  12512. function invokeHostBindingsInCreationMode(def, directive) {
  12513. if (def.hostBindings !== null) {
  12514. def.hostBindings(1 /* RenderFlags.Create */, directive);
  12515. }
  12516. }
  12517. /**
  12518. * Matches the current node against all available selectors.
  12519. * If a component is matched (at most one), it is returned in first position in the array.
  12520. */
  12521. function findDirectiveDefMatches(tView, tNode) {
  12522. ngDevMode && assertFirstCreatePass(tView);
  12523. ngDevMode && assertTNodeType(tNode, 3 /* TNodeType.AnyRNode */ | 12 /* TNodeType.AnyContainer */);
  12524. const registry = tView.directiveRegistry;
  12525. let matches = null;
  12526. if (registry) {
  12527. for (let i = 0; i < registry.length; i++) {
  12528. const def = registry[i];
  12529. if (isNodeMatchingSelectorList(tNode, def.selectors, /* isProjectionMode */ false)) {
  12530. matches ??= [];
  12531. if (isComponentDef(def)) {
  12532. if (ngDevMode) {
  12533. assertTNodeType(tNode, 2 /* TNodeType.Element */, `"${tNode.value}" tags cannot be used as component hosts. ` +
  12534. `Please use a different tag to activate the ${stringify(def.type)} component.`);
  12535. if (matches.length && isComponentDef(matches[0])) {
  12536. throwMultipleComponentError(tNode, matches.find(isComponentDef).type, def.type);
  12537. }
  12538. }
  12539. matches.unshift(def);
  12540. }
  12541. else {
  12542. matches.push(def);
  12543. }
  12544. }
  12545. }
  12546. }
  12547. return matches;
  12548. }
  12549. function elementAttributeInternal(tNode, lView, name, value, sanitizer, namespace) {
  12550. if (ngDevMode) {
  12551. assertNotSame(value, NO_CHANGE, 'Incoming value should never be NO_CHANGE.');
  12552. validateAgainstEventAttributes(name);
  12553. assertTNodeType(tNode, 2 /* TNodeType.Element */, `Attempted to set attribute \`${name}\` on a container node. ` +
  12554. `Host bindings are not valid on ng-container or ng-template.`);
  12555. }
  12556. const element = getNativeByTNode(tNode, lView);
  12557. setElementAttribute(lView[RENDERER], element, namespace, tNode.value, name, value, sanitizer);
  12558. }
  12559. function setElementAttribute(renderer, element, namespace, tagName, name, value, sanitizer) {
  12560. if (value == null) {
  12561. ngDevMode && ngDevMode.rendererRemoveAttribute++;
  12562. renderer.removeAttribute(element, name, namespace);
  12563. }
  12564. else {
  12565. ngDevMode && ngDevMode.rendererSetAttribute++;
  12566. const strValue = sanitizer == null ? renderStringify(value) : sanitizer(value, tagName || '', name);
  12567. renderer.setAttribute(element, name, strValue, namespace);
  12568. }
  12569. }
  12570. /**
  12571. * Sets initial input properties on directive instances from attribute data
  12572. *
  12573. * @param lView Current LView that is being processed.
  12574. * @param directiveIndex Index of the directive in directives array
  12575. * @param instance Instance of the directive on which to set the initial inputs
  12576. * @param def The directive def that contains the list of inputs
  12577. * @param tNode The static data for this node
  12578. */
  12579. function setInputsFromAttrs(lView, directiveIndex, instance, def, tNode, initialInputData) {
  12580. const initialInputs = initialInputData[directiveIndex];
  12581. if (initialInputs !== null) {
  12582. for (let i = 0; i < initialInputs.length; i += 2) {
  12583. const lookupName = initialInputs[i];
  12584. const value = initialInputs[i + 1];
  12585. writeToDirectiveInput(def, instance, lookupName, value);
  12586. if (ngDevMode) {
  12587. setNgReflectProperty(lView, tNode, def.inputs[lookupName][0], value);
  12588. }
  12589. }
  12590. }
  12591. }
  12592. ///////////////////////////////
  12593. //// Bindings & interpolations
  12594. ///////////////////////////////
  12595. /**
  12596. * Stores meta-data for a property binding to be used by TestBed's `DebugElement.properties`.
  12597. *
  12598. * In order to support TestBed's `DebugElement.properties` we need to save, for each binding:
  12599. * - a bound property name;
  12600. * - a static parts of interpolated strings;
  12601. *
  12602. * A given property metadata is saved at the binding's index in the `TView.data` (in other words, a
  12603. * property binding metadata will be stored in `TView.data` at the same index as a bound value in
  12604. * `LView`). Metadata are represented as `INTERPOLATION_DELIMITER`-delimited string with the
  12605. * following format:
  12606. * - `propertyName` for bound properties;
  12607. * - `propertyName�prefix�interpolation_static_part1�..interpolation_static_partN�suffix` for
  12608. * interpolated properties.
  12609. *
  12610. * @param tData `TData` where meta-data will be saved;
  12611. * @param tNode `TNode` that is a target of the binding;
  12612. * @param propertyName bound property name;
  12613. * @param bindingIndex binding index in `LView`
  12614. * @param interpolationParts static interpolation parts (for property interpolations)
  12615. */
  12616. function storePropertyBindingMetadata(tData, tNode, propertyName, bindingIndex, ...interpolationParts) {
  12617. // Binding meta-data are stored only the first time a given property instruction is processed.
  12618. // Since we don't have a concept of the "first update pass" we need to check for presence of the
  12619. // binding meta-data to decide if one should be stored (or if was stored already).
  12620. if (tData[bindingIndex] === null) {
  12621. if (!tNode.inputs?.[propertyName] && !tNode.hostDirectiveInputs?.[propertyName]) {
  12622. const propBindingIdxs = tNode.propertyBindings || (tNode.propertyBindings = []);
  12623. propBindingIdxs.push(bindingIndex);
  12624. let bindingMetadata = propertyName;
  12625. if (interpolationParts.length > 0) {
  12626. bindingMetadata +=
  12627. INTERPOLATION_DELIMITER + interpolationParts.join(INTERPOLATION_DELIMITER);
  12628. }
  12629. tData[bindingIndex] = bindingMetadata;
  12630. }
  12631. }
  12632. }
  12633. /**
  12634. * There are cases where the sub component's renderer needs to be included
  12635. * instead of the current renderer (see the componentSyntheticHost* instructions).
  12636. */
  12637. function loadComponentRenderer(currentDef, tNode, lView) {
  12638. // TODO(FW-2043): the `currentDef` is null when host bindings are invoked while creating root
  12639. // component (see packages/core/src/render3/component.ts). This is not consistent with the process
  12640. // of creating inner components, when current directive index is available in the state. In order
  12641. // to avoid relying on current def being `null` (thus special-casing root component creation), the
  12642. // process of creating root component should be unified with the process of creating inner
  12643. // components.
  12644. if (currentDef === null || isComponentDef(currentDef)) {
  12645. lView = unwrapLView(lView[tNode.index]);
  12646. }
  12647. return lView[RENDERER];
  12648. }
  12649. /** Handles an error thrown in an LView. */
  12650. function handleError$1(lView, error) {
  12651. const injector = lView[INJECTOR];
  12652. const errorHandler = injector ? injector.get(ErrorHandler, null) : null;
  12653. errorHandler && errorHandler.handleError(error);
  12654. }
  12655. /**
  12656. * Set all directive inputs with the specific public name on the node.
  12657. *
  12658. * @param tNode TNode on which the input is being set.
  12659. * @param tView Current TView
  12660. * @param lView `LView` which contains the directives.
  12661. * @param publicName Public name of the input being set.
  12662. * @param value Value to set.
  12663. */
  12664. function setAllInputsForProperty(tNode, tView, lView, publicName, value) {
  12665. const inputs = tNode.inputs?.[publicName];
  12666. const hostDirectiveInputs = tNode.hostDirectiveInputs?.[publicName];
  12667. let hasMatch = false;
  12668. if (hostDirectiveInputs) {
  12669. for (let i = 0; i < hostDirectiveInputs.length; i += 2) {
  12670. const index = hostDirectiveInputs[i];
  12671. ngDevMode && assertIndexInRange(lView, index);
  12672. const publicName = hostDirectiveInputs[i + 1];
  12673. const def = tView.data[index];
  12674. writeToDirectiveInput(def, lView[index], publicName, value);
  12675. hasMatch = true;
  12676. }
  12677. }
  12678. if (inputs) {
  12679. for (const index of inputs) {
  12680. ngDevMode && assertIndexInRange(lView, index);
  12681. const instance = lView[index];
  12682. const def = tView.data[index];
  12683. writeToDirectiveInput(def, instance, publicName, value);
  12684. hasMatch = true;
  12685. }
  12686. }
  12687. return hasMatch;
  12688. }
  12689. function renderComponent(hostLView, componentHostIdx) {
  12690. ngDevMode && assertEqual(isCreationMode(hostLView), true, 'Should be run in creation mode');
  12691. const componentView = getComponentLViewByIndex(componentHostIdx, hostLView);
  12692. const componentTView = componentView[TVIEW];
  12693. syncViewWithBlueprint(componentTView, componentView);
  12694. const hostRNode = componentView[HOST];
  12695. // Populate an LView with hydration info retrieved from the DOM via TransferState.
  12696. if (hostRNode !== null && componentView[HYDRATION] === null) {
  12697. componentView[HYDRATION] = retrieveHydrationInfo(hostRNode, componentView[INJECTOR]);
  12698. }
  12699. profiler(18 /* ProfilerEvent.ComponentStart */);
  12700. renderView(componentTView, componentView, componentView[CONTEXT]);
  12701. profiler(19 /* ProfilerEvent.ComponentEnd */, componentView[CONTEXT]);
  12702. }
  12703. /**
  12704. * Syncs an LView instance with its blueprint if they have gotten out of sync.
  12705. *
  12706. * Typically, blueprints and their view instances should always be in sync, so the loop here
  12707. * will be skipped. However, consider this case of two components side-by-side:
  12708. *
  12709. * App template:
  12710. * ```html
  12711. * <comp></comp>
  12712. * <comp></comp>
  12713. * ```
  12714. *
  12715. * The following will happen:
  12716. * 1. App template begins processing.
  12717. * 2. First <comp> is matched as a component and its LView is created.
  12718. * 3. Second <comp> is matched as a component and its LView is created.
  12719. * 4. App template completes processing, so it's time to check child templates.
  12720. * 5. First <comp> template is checked. It has a directive, so its def is pushed to blueprint.
  12721. * 6. Second <comp> template is checked. Its blueprint has been updated by the first
  12722. * <comp> template, but its LView was created before this update, so it is out of sync.
  12723. *
  12724. * Note that embedded views inside ngFor loops will never be out of sync because these views
  12725. * are processed as soon as they are created.
  12726. *
  12727. * @param tView The `TView` that contains the blueprint for syncing
  12728. * @param lView The view to sync
  12729. */
  12730. function syncViewWithBlueprint(tView, lView) {
  12731. for (let i = lView.length; i < tView.blueprint.length; i++) {
  12732. lView.push(tView.blueprint[i]);
  12733. }
  12734. }
  12735. /**
  12736. * Processes a view in the creation mode. This includes a number of steps in a specific order:
  12737. * - creating view query functions (if any);
  12738. * - executing a template function in the creation mode;
  12739. * - updating static queries (if any);
  12740. * - creating child components defined in a given view.
  12741. */
  12742. function renderView(tView, lView, context) {
  12743. ngDevMode && assertEqual(isCreationMode(lView), true, 'Should be run in creation mode');
  12744. ngDevMode && assertNotReactive(renderView.name);
  12745. enterView(lView);
  12746. try {
  12747. const viewQuery = tView.viewQuery;
  12748. if (viewQuery !== null) {
  12749. executeViewQueryFn(1 /* RenderFlags.Create */, viewQuery, context);
  12750. }
  12751. // Execute a template associated with this view, if it exists. A template function might not be
  12752. // defined for the root component views.
  12753. const templateFn = tView.template;
  12754. if (templateFn !== null) {
  12755. executeTemplate(tView, lView, templateFn, 1 /* RenderFlags.Create */, context);
  12756. }
  12757. // This needs to be set before children are processed to support recursive components.
  12758. // This must be set to false immediately after the first creation run because in an
  12759. // ngFor loop, all the views will be created together before update mode runs and turns
  12760. // off firstCreatePass. If we don't set it here, instances will perform directive
  12761. // matching, etc again and again.
  12762. if (tView.firstCreatePass) {
  12763. tView.firstCreatePass = false;
  12764. }
  12765. // Mark all queries active in this view as dirty. This is necessary for signal-based queries to
  12766. // have a clear marking point where we can read query results atomically (for a given view).
  12767. lView[QUERIES]?.finishViewCreation(tView);
  12768. // We resolve content queries specifically marked as `static` in creation mode. Dynamic
  12769. // content queries are resolved during change detection (i.e. update mode), after embedded
  12770. // views are refreshed (see block above).
  12771. if (tView.staticContentQueries) {
  12772. refreshContentQueries(tView, lView);
  12773. }
  12774. // We must materialize query results before child components are processed
  12775. // in case a child component has projected a container. The LContainer needs
  12776. // to exist so the embedded views are properly attached by the container.
  12777. if (tView.staticViewQueries) {
  12778. executeViewQueryFn(2 /* RenderFlags.Update */, tView.viewQuery, context);
  12779. }
  12780. // Render child component views.
  12781. const components = tView.components;
  12782. if (components !== null) {
  12783. renderChildComponents(lView, components);
  12784. }
  12785. }
  12786. catch (error) {
  12787. // If we didn't manage to get past the first template pass due to
  12788. // an error, mark the view as corrupted so we can try to recover.
  12789. if (tView.firstCreatePass) {
  12790. tView.incompleteFirstPass = true;
  12791. tView.firstCreatePass = false;
  12792. }
  12793. throw error;
  12794. }
  12795. finally {
  12796. lView[FLAGS] &= -5 /* LViewFlags.CreationMode */;
  12797. leaveView();
  12798. }
  12799. }
  12800. /** Renders child components in the current view (creation mode). */
  12801. function renderChildComponents(hostLView, components) {
  12802. for (let i = 0; i < components.length; i++) {
  12803. renderComponent(hostLView, components[i]);
  12804. }
  12805. }
  12806. function createAndRenderEmbeddedLView(declarationLView, templateTNode, context, options) {
  12807. const prevConsumer = setActiveConsumer$1(null);
  12808. try {
  12809. const embeddedTView = templateTNode.tView;
  12810. ngDevMode && assertDefined(embeddedTView, 'TView must be defined for a template node.');
  12811. ngDevMode && assertTNodeForLView(templateTNode, declarationLView);
  12812. // Embedded views follow the change detection strategy of the view they're declared in.
  12813. const isSignalView = declarationLView[FLAGS] & 4096 /* LViewFlags.SignalView */;
  12814. const viewFlags = isSignalView ? 4096 /* LViewFlags.SignalView */ : 16 /* LViewFlags.CheckAlways */;
  12815. const embeddedLView = createLView(declarationLView, embeddedTView, context, viewFlags, null, templateTNode, null, null, options?.injector ?? null, options?.embeddedViewInjector ?? null, options?.dehydratedView ?? null);
  12816. const declarationLContainer = declarationLView[templateTNode.index];
  12817. ngDevMode && assertLContainer(declarationLContainer);
  12818. embeddedLView[DECLARATION_LCONTAINER] = declarationLContainer;
  12819. const declarationViewLQueries = declarationLView[QUERIES];
  12820. if (declarationViewLQueries !== null) {
  12821. embeddedLView[QUERIES] = declarationViewLQueries.createEmbeddedView(embeddedTView);
  12822. }
  12823. // execute creation mode of a view
  12824. renderView(embeddedTView, embeddedLView, context);
  12825. return embeddedLView;
  12826. }
  12827. finally {
  12828. setActiveConsumer$1(prevConsumer);
  12829. }
  12830. }
  12831. /**
  12832. * Returns whether an elements that belong to a view should be
  12833. * inserted into the DOM. For client-only cases, DOM elements are
  12834. * always inserted. For hydration cases, we check whether serialized
  12835. * info is available for a view and the view is not in a "skip hydration"
  12836. * block (in which case view contents was re-created, thus needing insertion).
  12837. */
  12838. function shouldAddViewToDom(tNode, dehydratedView) {
  12839. return (!dehydratedView || dehydratedView.firstChild === null || hasInSkipHydrationBlockFlag(tNode));
  12840. }
  12841. let _icuContainerIterate;
  12842. /**
  12843. * Iterator which provides ability to visit all of the `TIcuContainerNode` root `RNode`s.
  12844. */
  12845. function icuContainerIterate(tIcuContainerNode, lView) {
  12846. return _icuContainerIterate(tIcuContainerNode, lView);
  12847. }
  12848. /**
  12849. * Ensures that `IcuContainerVisitor`'s implementation is present.
  12850. *
  12851. * This function is invoked when i18n instruction comes across an ICU. The purpose is to allow the
  12852. * bundler to tree shake ICU logic and only load it if ICU instruction is executed.
  12853. */
  12854. function ensureIcuContainerVisitorLoaded(loader) {
  12855. if (_icuContainerIterate === undefined) {
  12856. // Do not inline this function. We want to keep `ensureIcuContainerVisitorLoaded` light, so it
  12857. // can be inlined into call-site.
  12858. _icuContainerIterate = loader();
  12859. }
  12860. }
  12861. /**
  12862. * Flags for renderer-specific style modifiers.
  12863. * @publicApi
  12864. */
  12865. var RendererStyleFlags2;
  12866. (function (RendererStyleFlags2) {
  12867. // TODO(misko): This needs to be refactored into a separate file so that it can be imported from
  12868. // `node_manipulation.ts` Currently doing the import cause resolution order to change and fails
  12869. // the tests. The work around is to have hard coded value in `node_manipulation.ts` for now.
  12870. /**
  12871. * Marks a style as important.
  12872. */
  12873. RendererStyleFlags2[RendererStyleFlags2["Important"] = 1] = "Important";
  12874. /**
  12875. * Marks a style as using dash case naming (this-is-dash-case).
  12876. */
  12877. RendererStyleFlags2[RendererStyleFlags2["DashCase"] = 2] = "DashCase";
  12878. })(RendererStyleFlags2 || (RendererStyleFlags2 = {}));
  12879. /**
  12880. * Checks whether a TNode is considered detached, i.e. not present in the
  12881. * translated i18n template. We should not attempt hydration for such nodes
  12882. * and instead, use a regular "creation mode".
  12883. */
  12884. function isDetachedByI18n(tNode) {
  12885. return (tNode.flags & 32 /* TNodeFlags.isDetached */) === 32 /* TNodeFlags.isDetached */;
  12886. }
  12887. /**
  12888. * NOTE: for performance reasons, the possible actions are inlined within the function instead of
  12889. * being passed as an argument.
  12890. */
  12891. function applyToElementOrContainer(action, renderer, parent, lNodeToHandle, beforeNode) {
  12892. // If this slot was allocated for a text node dynamically created by i18n, the text node itself
  12893. // won't be created until i18nApply() in the update block, so this node should be skipped.
  12894. // For more info, see "ICU expressions should work inside an ngTemplateOutlet inside an ngFor"
  12895. // in `i18n_spec.ts`.
  12896. if (lNodeToHandle != null) {
  12897. let lContainer;
  12898. let isComponent = false;
  12899. // We are expecting an RNode, but in the case of a component or LContainer the `RNode` is
  12900. // wrapped in an array which needs to be unwrapped. We need to know if it is a component and if
  12901. // it has LContainer so that we can process all of those cases appropriately.
  12902. if (isLContainer(lNodeToHandle)) {
  12903. lContainer = lNodeToHandle;
  12904. }
  12905. else if (isLView(lNodeToHandle)) {
  12906. isComponent = true;
  12907. ngDevMode && assertDefined(lNodeToHandle[HOST], 'HOST must be defined for a component LView');
  12908. lNodeToHandle = lNodeToHandle[HOST];
  12909. }
  12910. const rNode = unwrapRNode(lNodeToHandle);
  12911. if (action === 0 /* WalkTNodeTreeAction.Create */ && parent !== null) {
  12912. if (beforeNode == null) {
  12913. nativeAppendChild(renderer, parent, rNode);
  12914. }
  12915. else {
  12916. nativeInsertBefore(renderer, parent, rNode, beforeNode || null, true);
  12917. }
  12918. }
  12919. else if (action === 1 /* WalkTNodeTreeAction.Insert */ && parent !== null) {
  12920. nativeInsertBefore(renderer, parent, rNode, beforeNode || null, true);
  12921. }
  12922. else if (action === 2 /* WalkTNodeTreeAction.Detach */) {
  12923. nativeRemoveNode(renderer, rNode, isComponent);
  12924. }
  12925. else if (action === 3 /* WalkTNodeTreeAction.Destroy */) {
  12926. ngDevMode && ngDevMode.rendererDestroyNode++;
  12927. renderer.destroyNode(rNode);
  12928. }
  12929. if (lContainer != null) {
  12930. applyContainer(renderer, action, lContainer, parent, beforeNode);
  12931. }
  12932. }
  12933. }
  12934. /**
  12935. * Removes all DOM elements associated with a view.
  12936. *
  12937. * Because some root nodes of the view may be containers, we sometimes need
  12938. * to propagate deeply into the nested containers to remove all elements in the
  12939. * views beneath it.
  12940. *
  12941. * @param tView The `TView' of the `LView` from which elements should be added or removed
  12942. * @param lView The view from which elements should be added or removed
  12943. */
  12944. function removeViewFromDOM(tView, lView) {
  12945. detachViewFromDOM(tView, lView);
  12946. lView[HOST] = null;
  12947. lView[T_HOST] = null;
  12948. }
  12949. /**
  12950. * Adds all DOM elements associated with a view.
  12951. *
  12952. * Because some root nodes of the view may be containers, we sometimes need
  12953. * to propagate deeply into the nested containers to add all elements in the
  12954. * views beneath it.
  12955. *
  12956. * @param tView The `TView' of the `LView` from which elements should be added or removed
  12957. * @param parentTNode The `TNode` where the `LView` should be attached to.
  12958. * @param renderer Current renderer to use for DOM manipulations.
  12959. * @param lView The view from which elements should be added or removed
  12960. * @param parentNativeNode The parent `RElement` where it should be inserted into.
  12961. * @param beforeNode The node before which elements should be added, if insert mode
  12962. */
  12963. function addViewToDOM(tView, parentTNode, renderer, lView, parentNativeNode, beforeNode) {
  12964. lView[HOST] = parentNativeNode;
  12965. lView[T_HOST] = parentTNode;
  12966. applyView(tView, lView, renderer, 1 /* WalkTNodeTreeAction.Insert */, parentNativeNode, beforeNode);
  12967. }
  12968. /**
  12969. * Detach a `LView` from the DOM by detaching its nodes.
  12970. *
  12971. * @param tView The `TView' of the `LView` to be detached
  12972. * @param lView the `LView` to be detached.
  12973. */
  12974. function detachViewFromDOM(tView, lView) {
  12975. // When we remove a view from the DOM, we need to rerun afterRender hooks
  12976. // We don't necessarily needs to run change detection. DOM removal only requires
  12977. // change detection if animations are enabled (this notification is handled by animations).
  12978. lView[ENVIRONMENT].changeDetectionScheduler?.notify(9 /* NotificationSource.ViewDetachedFromDOM */);
  12979. applyView(tView, lView, lView[RENDERER], 2 /* WalkTNodeTreeAction.Detach */, null, null);
  12980. }
  12981. /**
  12982. * Traverses down and up the tree of views and containers to remove listeners and
  12983. * call onDestroy callbacks.
  12984. *
  12985. * Notes:
  12986. * - Because it's used for onDestroy calls, it needs to be bottom-up.
  12987. * - Must process containers instead of their views to avoid splicing
  12988. * when views are destroyed and re-added.
  12989. * - Using a while loop because it's faster than recursion
  12990. * - Destroy only called on movement to sibling or movement to parent (laterally or up)
  12991. *
  12992. * @param rootView The view to destroy
  12993. */
  12994. function destroyViewTree(rootView) {
  12995. // If the view has no children, we can clean it up and return early.
  12996. let lViewOrLContainer = rootView[CHILD_HEAD];
  12997. if (!lViewOrLContainer) {
  12998. return cleanUpView(rootView[TVIEW], rootView);
  12999. }
  13000. while (lViewOrLContainer) {
  13001. let next = null;
  13002. if (isLView(lViewOrLContainer)) {
  13003. // If LView, traverse down to child.
  13004. next = lViewOrLContainer[CHILD_HEAD];
  13005. }
  13006. else {
  13007. ngDevMode && assertLContainer(lViewOrLContainer);
  13008. // If container, traverse down to its first LView.
  13009. const firstView = lViewOrLContainer[CONTAINER_HEADER_OFFSET];
  13010. if (firstView)
  13011. next = firstView;
  13012. }
  13013. if (!next) {
  13014. // Only clean up view when moving to the side or up, as destroy hooks
  13015. // should be called in order from the bottom up.
  13016. while (lViewOrLContainer && !lViewOrLContainer[NEXT] && lViewOrLContainer !== rootView) {
  13017. if (isLView(lViewOrLContainer)) {
  13018. cleanUpView(lViewOrLContainer[TVIEW], lViewOrLContainer);
  13019. }
  13020. lViewOrLContainer = lViewOrLContainer[PARENT];
  13021. }
  13022. if (lViewOrLContainer === null)
  13023. lViewOrLContainer = rootView;
  13024. if (isLView(lViewOrLContainer)) {
  13025. cleanUpView(lViewOrLContainer[TVIEW], lViewOrLContainer);
  13026. }
  13027. next = lViewOrLContainer && lViewOrLContainer[NEXT];
  13028. }
  13029. lViewOrLContainer = next;
  13030. }
  13031. }
  13032. function detachMovedView(declarationContainer, lView) {
  13033. ngDevMode && assertLContainer(declarationContainer);
  13034. ngDevMode &&
  13035. assertDefined(declarationContainer[MOVED_VIEWS], 'A projected view should belong to a non-empty projected views collection');
  13036. const movedViews = declarationContainer[MOVED_VIEWS];
  13037. const declarationViewIndex = movedViews.indexOf(lView);
  13038. movedViews.splice(declarationViewIndex, 1);
  13039. }
  13040. /**
  13041. * A standalone function which destroys an LView,
  13042. * conducting clean up (e.g. removing listeners, calling onDestroys).
  13043. *
  13044. * @param tView The `TView' of the `LView` to be destroyed
  13045. * @param lView The view to be destroyed.
  13046. */
  13047. function destroyLView(tView, lView) {
  13048. if (isDestroyed(lView)) {
  13049. return;
  13050. }
  13051. const renderer = lView[RENDERER];
  13052. if (renderer.destroyNode) {
  13053. applyView(tView, lView, renderer, 3 /* WalkTNodeTreeAction.Destroy */, null, null);
  13054. }
  13055. destroyViewTree(lView);
  13056. }
  13057. /**
  13058. * Calls onDestroys hooks for all directives and pipes in a given view and then removes all
  13059. * listeners. Listeners are removed as the last step so events delivered in the onDestroys hooks
  13060. * can be propagated to @Output listeners.
  13061. *
  13062. * @param tView `TView` for the `LView` to clean up.
  13063. * @param lView The LView to clean up
  13064. */
  13065. function cleanUpView(tView, lView) {
  13066. if (isDestroyed(lView)) {
  13067. return;
  13068. }
  13069. const prevConsumer = setActiveConsumer$1(null);
  13070. try {
  13071. // Usually the Attached flag is removed when the view is detached from its parent, however
  13072. // if it's a root view, the flag won't be unset hence why we're also removing on destroy.
  13073. lView[FLAGS] &= ~128 /* LViewFlags.Attached */;
  13074. // Mark the LView as destroyed *before* executing the onDestroy hooks. An onDestroy hook
  13075. // runs arbitrary user code, which could include its own `viewRef.destroy()` (or similar). If
  13076. // We don't flag the view as destroyed before the hooks, this could lead to an infinite loop.
  13077. // This also aligns with the ViewEngine behavior. It also means that the onDestroy hook is
  13078. // really more of an "afterDestroy" hook if you think about it.
  13079. lView[FLAGS] |= 256 /* LViewFlags.Destroyed */;
  13080. lView[REACTIVE_TEMPLATE_CONSUMER] && consumerDestroy(lView[REACTIVE_TEMPLATE_CONSUMER]);
  13081. executeOnDestroys(tView, lView);
  13082. processCleanups(tView, lView);
  13083. // For component views only, the local renderer is destroyed at clean up time.
  13084. if (lView[TVIEW].type === 1 /* TViewType.Component */) {
  13085. ngDevMode && ngDevMode.rendererDestroy++;
  13086. lView[RENDERER].destroy();
  13087. }
  13088. const declarationContainer = lView[DECLARATION_LCONTAINER];
  13089. // we are dealing with an embedded view that is still inserted into a container
  13090. if (declarationContainer !== null && isLContainer(lView[PARENT])) {
  13091. // and this is a projected view
  13092. if (declarationContainer !== lView[PARENT]) {
  13093. detachMovedView(declarationContainer, lView);
  13094. }
  13095. // For embedded views still attached to a container: remove query result from this view.
  13096. const lQueries = lView[QUERIES];
  13097. if (lQueries !== null) {
  13098. lQueries.detachView(tView);
  13099. }
  13100. }
  13101. // Unregister the view once everything else has been cleaned up.
  13102. unregisterLView(lView);
  13103. }
  13104. finally {
  13105. setActiveConsumer$1(prevConsumer);
  13106. }
  13107. }
  13108. /** Removes listeners and unsubscribes from output subscriptions */
  13109. function processCleanups(tView, lView) {
  13110. ngDevMode && assertNotReactive(processCleanups.name);
  13111. const tCleanup = tView.cleanup;
  13112. const lCleanup = lView[CLEANUP];
  13113. if (tCleanup !== null) {
  13114. for (let i = 0; i < tCleanup.length - 1; i += 2) {
  13115. if (typeof tCleanup[i] === 'string') {
  13116. // This is a native DOM listener. It will occupy 4 entries in the TCleanup array (hence i +=
  13117. // 2 at the end of this block).
  13118. const targetIdx = tCleanup[i + 3];
  13119. ngDevMode && assertNumber(targetIdx, 'cleanup target must be a number');
  13120. if (targetIdx >= 0) {
  13121. // Destroy anything whose teardown is a function call (e.g. QueryList, ModelSignal).
  13122. lCleanup[targetIdx]();
  13123. }
  13124. else {
  13125. // Subscription
  13126. lCleanup[-targetIdx].unsubscribe();
  13127. }
  13128. i += 2;
  13129. }
  13130. else {
  13131. // This is a cleanup function that is grouped with the index of its context
  13132. const context = lCleanup[tCleanup[i + 1]];
  13133. tCleanup[i].call(context);
  13134. }
  13135. }
  13136. }
  13137. if (lCleanup !== null) {
  13138. lView[CLEANUP] = null;
  13139. }
  13140. const destroyHooks = lView[ON_DESTROY_HOOKS];
  13141. if (destroyHooks !== null) {
  13142. // Reset the ON_DESTROY_HOOKS array before iterating over it to prevent hooks that unregister
  13143. // themselves from mutating the array during iteration.
  13144. lView[ON_DESTROY_HOOKS] = null;
  13145. for (let i = 0; i < destroyHooks.length; i++) {
  13146. const destroyHooksFn = destroyHooks[i];
  13147. ngDevMode && assertFunction(destroyHooksFn, 'Expecting destroy hook to be a function.');
  13148. destroyHooksFn();
  13149. }
  13150. }
  13151. // Destroy effects registered to the view. Many of these will have been processed above.
  13152. const effects = lView[EFFECTS];
  13153. if (effects !== null) {
  13154. lView[EFFECTS] = null;
  13155. for (const effect of effects) {
  13156. effect.destroy();
  13157. }
  13158. }
  13159. }
  13160. /** Calls onDestroy hooks for this view */
  13161. function executeOnDestroys(tView, lView) {
  13162. ngDevMode && assertNotReactive(executeOnDestroys.name);
  13163. let destroyHooks;
  13164. if (tView != null && (destroyHooks = tView.destroyHooks) != null) {
  13165. for (let i = 0; i < destroyHooks.length; i += 2) {
  13166. const context = lView[destroyHooks[i]];
  13167. // Only call the destroy hook if the context has been requested.
  13168. if (!(context instanceof NodeInjectorFactory)) {
  13169. const toCall = destroyHooks[i + 1];
  13170. if (Array.isArray(toCall)) {
  13171. for (let j = 0; j < toCall.length; j += 2) {
  13172. const callContext = context[toCall[j]];
  13173. const hook = toCall[j + 1];
  13174. profiler(4 /* ProfilerEvent.LifecycleHookStart */, callContext, hook);
  13175. try {
  13176. hook.call(callContext);
  13177. }
  13178. finally {
  13179. profiler(5 /* ProfilerEvent.LifecycleHookEnd */, callContext, hook);
  13180. }
  13181. }
  13182. }
  13183. else {
  13184. profiler(4 /* ProfilerEvent.LifecycleHookStart */, context, toCall);
  13185. try {
  13186. toCall.call(context);
  13187. }
  13188. finally {
  13189. profiler(5 /* ProfilerEvent.LifecycleHookEnd */, context, toCall);
  13190. }
  13191. }
  13192. }
  13193. }
  13194. }
  13195. }
  13196. /**
  13197. * Returns a native element if a node can be inserted into the given parent.
  13198. *
  13199. * There are two reasons why we may not be able to insert a element immediately.
  13200. * - Projection: When creating a child content element of a component, we have to skip the
  13201. * insertion because the content of a component will be projected.
  13202. * `<component><content>delayed due to projection</content></component>`
  13203. * - Parent container is disconnected: This can happen when we are inserting a view into
  13204. * parent container, which itself is disconnected. For example the parent container is part
  13205. * of a View which has not be inserted or is made for projection but has not been inserted
  13206. * into destination.
  13207. *
  13208. * @param tView: Current `TView`.
  13209. * @param tNode: `TNode` for which we wish to retrieve render parent.
  13210. * @param lView: Current `LView`.
  13211. */
  13212. function getParentRElement(tView, tNode, lView) {
  13213. return getClosestRElement(tView, tNode.parent, lView);
  13214. }
  13215. /**
  13216. * Get closest `RElement` or `null` if it can't be found.
  13217. *
  13218. * If `TNode` is `TNodeType.Element` => return `RElement` at `LView[tNode.index]` location.
  13219. * If `TNode` is `TNodeType.ElementContainer|IcuContain` => return the parent (recursively).
  13220. * If `TNode` is `null` then return host `RElement`:
  13221. * - return `null` if projection
  13222. * - return `null` if parent container is disconnected (we have no parent.)
  13223. *
  13224. * @param tView: Current `TView`.
  13225. * @param tNode: `TNode` for which we wish to retrieve `RElement` (or `null` if host element is
  13226. * needed).
  13227. * @param lView: Current `LView`.
  13228. * @returns `null` if the `RElement` can't be determined at this time (no parent / projection)
  13229. */
  13230. function getClosestRElement(tView, tNode, lView) {
  13231. let parentTNode = tNode;
  13232. // Skip over element and ICU containers as those are represented by a comment node and
  13233. // can't be used as a render parent. Also skip let declarations since they don't have a
  13234. // corresponding DOM node at all.
  13235. while (parentTNode !== null &&
  13236. parentTNode.type & (8 /* TNodeType.ElementContainer */ | 32 /* TNodeType.Icu */ | 128 /* TNodeType.LetDeclaration */)) {
  13237. tNode = parentTNode;
  13238. parentTNode = tNode.parent;
  13239. }
  13240. // If the parent tNode is null, then we are inserting across views: either into an embedded view
  13241. // or a component view.
  13242. if (parentTNode === null) {
  13243. // We are inserting a root element of the component view into the component host element and
  13244. // it should always be eager.
  13245. return lView[HOST];
  13246. }
  13247. else {
  13248. ngDevMode && assertTNodeType(parentTNode, 3 /* TNodeType.AnyRNode */ | 4 /* TNodeType.Container */);
  13249. if (isComponentHost(parentTNode)) {
  13250. ngDevMode && assertTNodeForLView(parentTNode, lView);
  13251. const { encapsulation } = tView.data[parentTNode.directiveStart + parentTNode.componentOffset];
  13252. // We've got a parent which is an element in the current view. We just need to verify if the
  13253. // parent element is not a component. Component's content nodes are not inserted immediately
  13254. // because they will be projected, and so doing insert at this point would be wasteful.
  13255. // Since the projection would then move it to its final destination. Note that we can't
  13256. // make this assumption when using the Shadow DOM, because the native projection placeholders
  13257. // (<content> or <slot>) have to be in place as elements are being inserted.
  13258. if (encapsulation === ViewEncapsulation.None ||
  13259. encapsulation === ViewEncapsulation.Emulated) {
  13260. return null;
  13261. }
  13262. }
  13263. return getNativeByTNode(parentTNode, lView);
  13264. }
  13265. }
  13266. /**
  13267. * Find a node in front of which `currentTNode` should be inserted.
  13268. *
  13269. * This method determines the `RNode` in front of which we should insert the `currentRNode`. This
  13270. * takes `TNode.insertBeforeIndex` into account if i18n code has been invoked.
  13271. *
  13272. * @param parentTNode parent `TNode`
  13273. * @param currentTNode current `TNode` (The node which we would like to insert into the DOM)
  13274. * @param lView current `LView`
  13275. */
  13276. function getInsertInFrontOfRNode(parentTNode, currentTNode, lView) {
  13277. return _getInsertInFrontOfRNodeWithI18n(parentTNode, currentTNode, lView);
  13278. }
  13279. /**
  13280. * Find a node in front of which `currentTNode` should be inserted. (Does not take i18n into
  13281. * account)
  13282. *
  13283. * This method determines the `RNode` in front of which we should insert the `currentRNode`. This
  13284. * does not take `TNode.insertBeforeIndex` into account.
  13285. *
  13286. * @param parentTNode parent `TNode`
  13287. * @param currentTNode current `TNode` (The node which we would like to insert into the DOM)
  13288. * @param lView current `LView`
  13289. */
  13290. function getInsertInFrontOfRNodeWithNoI18n(parentTNode, currentTNode, lView) {
  13291. if (parentTNode.type & (8 /* TNodeType.ElementContainer */ | 32 /* TNodeType.Icu */)) {
  13292. return getNativeByTNode(parentTNode, lView);
  13293. }
  13294. return null;
  13295. }
  13296. /**
  13297. * Tree shakable boundary for `getInsertInFrontOfRNodeWithI18n` function.
  13298. *
  13299. * This function will only be set if i18n code runs.
  13300. */
  13301. let _getInsertInFrontOfRNodeWithI18n = getInsertInFrontOfRNodeWithNoI18n;
  13302. /**
  13303. * Tree shakable boundary for `processI18nInsertBefore` function.
  13304. *
  13305. * This function will only be set if i18n code runs.
  13306. */
  13307. let _processI18nInsertBefore;
  13308. function setI18nHandling(getInsertInFrontOfRNodeWithI18n, processI18nInsertBefore) {
  13309. _getInsertInFrontOfRNodeWithI18n = getInsertInFrontOfRNodeWithI18n;
  13310. _processI18nInsertBefore = processI18nInsertBefore;
  13311. }
  13312. /**
  13313. * Appends the `child` native node (or a collection of nodes) to the `parent`.
  13314. *
  13315. * @param tView The `TView' to be appended
  13316. * @param lView The current LView
  13317. * @param childRNode The native child (or children) that should be appended
  13318. * @param childTNode The TNode of the child element
  13319. */
  13320. function appendChild(tView, lView, childRNode, childTNode) {
  13321. const parentRNode = getParentRElement(tView, childTNode, lView);
  13322. const renderer = lView[RENDERER];
  13323. const parentTNode = childTNode.parent || lView[T_HOST];
  13324. const anchorNode = getInsertInFrontOfRNode(parentTNode, childTNode, lView);
  13325. if (parentRNode != null) {
  13326. if (Array.isArray(childRNode)) {
  13327. for (let i = 0; i < childRNode.length; i++) {
  13328. nativeAppendOrInsertBefore(renderer, parentRNode, childRNode[i], anchorNode, false);
  13329. }
  13330. }
  13331. else {
  13332. nativeAppendOrInsertBefore(renderer, parentRNode, childRNode, anchorNode, false);
  13333. }
  13334. }
  13335. _processI18nInsertBefore !== undefined &&
  13336. _processI18nInsertBefore(renderer, childTNode, lView, childRNode, parentRNode);
  13337. }
  13338. /**
  13339. * Returns the first native node for a given LView, starting from the provided TNode.
  13340. *
  13341. * Native nodes are returned in the order in which those appear in the native tree (DOM).
  13342. */
  13343. function getFirstNativeNode(lView, tNode) {
  13344. if (tNode !== null) {
  13345. ngDevMode &&
  13346. assertTNodeType(tNode, 3 /* TNodeType.AnyRNode */ |
  13347. 12 /* TNodeType.AnyContainer */ |
  13348. 32 /* TNodeType.Icu */ |
  13349. 16 /* TNodeType.Projection */ |
  13350. 128 /* TNodeType.LetDeclaration */);
  13351. const tNodeType = tNode.type;
  13352. if (tNodeType & 3 /* TNodeType.AnyRNode */) {
  13353. return getNativeByTNode(tNode, lView);
  13354. }
  13355. else if (tNodeType & 4 /* TNodeType.Container */) {
  13356. return getBeforeNodeForView(-1, lView[tNode.index]);
  13357. }
  13358. else if (tNodeType & 8 /* TNodeType.ElementContainer */) {
  13359. const elIcuContainerChild = tNode.child;
  13360. if (elIcuContainerChild !== null) {
  13361. return getFirstNativeNode(lView, elIcuContainerChild);
  13362. }
  13363. else {
  13364. const rNodeOrLContainer = lView[tNode.index];
  13365. if (isLContainer(rNodeOrLContainer)) {
  13366. return getBeforeNodeForView(-1, rNodeOrLContainer);
  13367. }
  13368. else {
  13369. return unwrapRNode(rNodeOrLContainer);
  13370. }
  13371. }
  13372. }
  13373. else if (tNodeType & 128 /* TNodeType.LetDeclaration */) {
  13374. return getFirstNativeNode(lView, tNode.next);
  13375. }
  13376. else if (tNodeType & 32 /* TNodeType.Icu */) {
  13377. let nextRNode = icuContainerIterate(tNode, lView);
  13378. let rNode = nextRNode();
  13379. // If the ICU container has no nodes, than we use the ICU anchor as the node.
  13380. return rNode || unwrapRNode(lView[tNode.index]);
  13381. }
  13382. else {
  13383. const projectionNodes = getProjectionNodes(lView, tNode);
  13384. if (projectionNodes !== null) {
  13385. if (Array.isArray(projectionNodes)) {
  13386. return projectionNodes[0];
  13387. }
  13388. const parentView = getLViewParent(lView[DECLARATION_COMPONENT_VIEW]);
  13389. ngDevMode && assertParentView(parentView);
  13390. return getFirstNativeNode(parentView, projectionNodes);
  13391. }
  13392. else {
  13393. return getFirstNativeNode(lView, tNode.next);
  13394. }
  13395. }
  13396. }
  13397. return null;
  13398. }
  13399. function getProjectionNodes(lView, tNode) {
  13400. if (tNode !== null) {
  13401. const componentView = lView[DECLARATION_COMPONENT_VIEW];
  13402. const componentHost = componentView[T_HOST];
  13403. const slotIdx = tNode.projection;
  13404. ngDevMode && assertProjectionSlots(lView);
  13405. return componentHost.projection[slotIdx];
  13406. }
  13407. return null;
  13408. }
  13409. function getBeforeNodeForView(viewIndexInContainer, lContainer) {
  13410. const nextViewIndex = CONTAINER_HEADER_OFFSET + viewIndexInContainer + 1;
  13411. if (nextViewIndex < lContainer.length) {
  13412. const lView = lContainer[nextViewIndex];
  13413. const firstTNodeOfView = lView[TVIEW].firstChild;
  13414. if (firstTNodeOfView !== null) {
  13415. return getFirstNativeNode(lView, firstTNodeOfView);
  13416. }
  13417. }
  13418. return lContainer[NATIVE];
  13419. }
  13420. /**
  13421. * Performs the operation of `action` on the node. Typically this involves inserting or removing
  13422. * nodes on the LView or projection boundary.
  13423. */
  13424. function applyNodes(renderer, action, tNode, lView, parentRElement, beforeNode, isProjection) {
  13425. while (tNode != null) {
  13426. ngDevMode && assertTNodeForLView(tNode, lView);
  13427. // Let declarations don't have corresponding DOM nodes so we skip over them.
  13428. if (tNode.type === 128 /* TNodeType.LetDeclaration */) {
  13429. tNode = tNode.next;
  13430. continue;
  13431. }
  13432. ngDevMode &&
  13433. assertTNodeType(tNode, 3 /* TNodeType.AnyRNode */ | 12 /* TNodeType.AnyContainer */ | 16 /* TNodeType.Projection */ | 32 /* TNodeType.Icu */);
  13434. const rawSlotValue = lView[tNode.index];
  13435. const tNodeType = tNode.type;
  13436. if (isProjection) {
  13437. if (action === 0 /* WalkTNodeTreeAction.Create */) {
  13438. rawSlotValue && attachPatchData(unwrapRNode(rawSlotValue), lView);
  13439. tNode.flags |= 2 /* TNodeFlags.isProjected */;
  13440. }
  13441. }
  13442. if (!isDetachedByI18n(tNode)) {
  13443. if (tNodeType & 8 /* TNodeType.ElementContainer */) {
  13444. applyNodes(renderer, action, tNode.child, lView, parentRElement, beforeNode, false);
  13445. applyToElementOrContainer(action, renderer, parentRElement, rawSlotValue, beforeNode);
  13446. }
  13447. else if (tNodeType & 32 /* TNodeType.Icu */) {
  13448. const nextRNode = icuContainerIterate(tNode, lView);
  13449. let rNode;
  13450. while ((rNode = nextRNode())) {
  13451. applyToElementOrContainer(action, renderer, parentRElement, rNode, beforeNode);
  13452. }
  13453. applyToElementOrContainer(action, renderer, parentRElement, rawSlotValue, beforeNode);
  13454. }
  13455. else if (tNodeType & 16 /* TNodeType.Projection */) {
  13456. applyProjectionRecursive(renderer, action, lView, tNode, parentRElement, beforeNode);
  13457. }
  13458. else {
  13459. ngDevMode && assertTNodeType(tNode, 3 /* TNodeType.AnyRNode */ | 4 /* TNodeType.Container */);
  13460. applyToElementOrContainer(action, renderer, parentRElement, rawSlotValue, beforeNode);
  13461. }
  13462. }
  13463. tNode = isProjection ? tNode.projectionNext : tNode.next;
  13464. }
  13465. }
  13466. function applyView(tView, lView, renderer, action, parentRElement, beforeNode) {
  13467. applyNodes(renderer, action, tView.firstChild, lView, parentRElement, beforeNode, false);
  13468. }
  13469. /**
  13470. * `applyProjection` performs operation on the projection.
  13471. *
  13472. * Inserting a projection requires us to locate the projected nodes from the parent component. The
  13473. * complication is that those nodes themselves could be re-projected from their parent component.
  13474. *
  13475. * @param tView The `TView` of `LView` which needs to be inserted, detached, destroyed
  13476. * @param lView The `LView` which needs to be inserted, detached, destroyed.
  13477. * @param tProjectionNode node to project
  13478. */
  13479. function applyProjection(tView, lView, tProjectionNode) {
  13480. const renderer = lView[RENDERER];
  13481. const parentRNode = getParentRElement(tView, tProjectionNode, lView);
  13482. const parentTNode = tProjectionNode.parent || lView[T_HOST];
  13483. let beforeNode = getInsertInFrontOfRNode(parentTNode, tProjectionNode, lView);
  13484. applyProjectionRecursive(renderer, 0 /* WalkTNodeTreeAction.Create */, lView, tProjectionNode, parentRNode, beforeNode);
  13485. }
  13486. /**
  13487. * `applyProjectionRecursive` performs operation on the projection specified by `action` (insert,
  13488. * detach, destroy)
  13489. *
  13490. * Inserting a projection requires us to locate the projected nodes from the parent component. The
  13491. * complication is that those nodes themselves could be re-projected from their parent component.
  13492. *
  13493. * @param renderer Render to use
  13494. * @param action action to perform (insert, detach, destroy)
  13495. * @param lView The LView which needs to be inserted, detached, destroyed.
  13496. * @param tProjectionNode node to project
  13497. * @param parentRElement parent DOM element for insertion/removal.
  13498. * @param beforeNode Before which node the insertions should happen.
  13499. */
  13500. function applyProjectionRecursive(renderer, action, lView, tProjectionNode, parentRElement, beforeNode) {
  13501. const componentLView = lView[DECLARATION_COMPONENT_VIEW];
  13502. const componentNode = componentLView[T_HOST];
  13503. ngDevMode &&
  13504. assertEqual(typeof tProjectionNode.projection, 'number', 'expecting projection index');
  13505. const nodeToProjectOrRNodes = componentNode.projection[tProjectionNode.projection];
  13506. if (Array.isArray(nodeToProjectOrRNodes)) {
  13507. // This should not exist, it is a bit of a hack. When we bootstrap a top level node and we
  13508. // need to support passing projectable nodes, so we cheat and put them in the TNode
  13509. // of the Host TView. (Yes we put instance info at the T Level). We can get away with it
  13510. // because we know that TView is not shared and therefore it will not be a problem.
  13511. // This should be refactored and cleaned up.
  13512. for (let i = 0; i < nodeToProjectOrRNodes.length; i++) {
  13513. const rNode = nodeToProjectOrRNodes[i];
  13514. applyToElementOrContainer(action, renderer, parentRElement, rNode, beforeNode);
  13515. }
  13516. }
  13517. else {
  13518. let nodeToProject = nodeToProjectOrRNodes;
  13519. const projectedComponentLView = componentLView[PARENT];
  13520. // If a parent <ng-content> is located within a skip hydration block,
  13521. // annotate an actual node that is being projected with the same flag too.
  13522. if (hasInSkipHydrationBlockFlag(tProjectionNode)) {
  13523. nodeToProject.flags |= 128 /* TNodeFlags.inSkipHydrationBlock */;
  13524. }
  13525. applyNodes(renderer, action, nodeToProject, projectedComponentLView, parentRElement, beforeNode, true);
  13526. }
  13527. }
  13528. /**
  13529. * `applyContainer` performs an operation on the container and its views as specified by
  13530. * `action` (insert, detach, destroy)
  13531. *
  13532. * Inserting a Container is complicated by the fact that the container may have Views which
  13533. * themselves have containers or projections.
  13534. *
  13535. * @param renderer Renderer to use
  13536. * @param action action to perform (insert, detach, destroy)
  13537. * @param lContainer The LContainer which needs to be inserted, detached, destroyed.
  13538. * @param parentRElement parent DOM element for insertion/removal.
  13539. * @param beforeNode Before which node the insertions should happen.
  13540. */
  13541. function applyContainer(renderer, action, lContainer, parentRElement, beforeNode) {
  13542. ngDevMode && assertLContainer(lContainer);
  13543. const anchor = lContainer[NATIVE]; // LContainer has its own before node.
  13544. const native = unwrapRNode(lContainer);
  13545. // An LContainer can be created dynamically on any node by injecting ViewContainerRef.
  13546. // Asking for a ViewContainerRef on an element will result in a creation of a separate anchor
  13547. // node (comment in the DOM) that will be different from the LContainer's host node. In this
  13548. // particular case we need to execute action on 2 nodes:
  13549. // - container's host node (this is done in the executeActionOnElementOrContainer)
  13550. // - container's host node (this is done here)
  13551. if (anchor !== native) {
  13552. // This is very strange to me (Misko). I would expect that the native is same as anchor. I
  13553. // don't see a reason why they should be different, but they are.
  13554. //
  13555. // If they are we need to process the second anchor as well.
  13556. applyToElementOrContainer(action, renderer, parentRElement, anchor, beforeNode);
  13557. }
  13558. for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
  13559. const lView = lContainer[i];
  13560. applyView(lView[TVIEW], lView, renderer, action, parentRElement, anchor);
  13561. }
  13562. }
  13563. /**
  13564. * Writes class/style to element.
  13565. *
  13566. * @param renderer Renderer to use.
  13567. * @param isClassBased `true` if it should be written to `class` (`false` to write to `style`)
  13568. * @param rNode The Node to write to.
  13569. * @param prop Property to write to. This would be the class/style name.
  13570. * @param value Value to write. If `null`/`undefined`/`false` this is considered a remove (set/add
  13571. * otherwise).
  13572. */
  13573. function applyStyling(renderer, isClassBased, rNode, prop, value) {
  13574. if (isClassBased) {
  13575. // We actually want JS true/false here because any truthy value should add the class
  13576. if (!value) {
  13577. ngDevMode && ngDevMode.rendererRemoveClass++;
  13578. renderer.removeClass(rNode, prop);
  13579. }
  13580. else {
  13581. ngDevMode && ngDevMode.rendererAddClass++;
  13582. renderer.addClass(rNode, prop);
  13583. }
  13584. }
  13585. else {
  13586. let flags = prop.indexOf('-') === -1 ? undefined : RendererStyleFlags2.DashCase;
  13587. if (value == null /** || value === undefined */) {
  13588. ngDevMode && ngDevMode.rendererRemoveStyle++;
  13589. renderer.removeStyle(rNode, prop, flags);
  13590. }
  13591. else {
  13592. // A value is important if it ends with `!important`. The style
  13593. // parser strips any semicolons at the end of the value.
  13594. const isImportant = typeof value === 'string' ? value.endsWith('!important') : false;
  13595. if (isImportant) {
  13596. // !important has to be stripped from the value for it to be valid.
  13597. value = value.slice(0, -10);
  13598. flags |= RendererStyleFlags2.Important;
  13599. }
  13600. ngDevMode && ngDevMode.rendererSetStyle++;
  13601. renderer.setStyle(rNode, prop, value, flags);
  13602. }
  13603. }
  13604. }
  13605. function collectNativeNodes(tView, lView, tNode, result, isProjection = false) {
  13606. while (tNode !== null) {
  13607. // Let declarations don't have corresponding DOM nodes so we skip over them.
  13608. if (tNode.type === 128 /* TNodeType.LetDeclaration */) {
  13609. tNode = isProjection ? tNode.projectionNext : tNode.next;
  13610. continue;
  13611. }
  13612. ngDevMode &&
  13613. assertTNodeType(tNode, 3 /* TNodeType.AnyRNode */ | 12 /* TNodeType.AnyContainer */ | 16 /* TNodeType.Projection */ | 32 /* TNodeType.Icu */);
  13614. const lNode = lView[tNode.index];
  13615. if (lNode !== null) {
  13616. result.push(unwrapRNode(lNode));
  13617. }
  13618. // A given lNode can represent either a native node or a LContainer (when it is a host of a
  13619. // ViewContainerRef). When we find a LContainer we need to descend into it to collect root nodes
  13620. // from the views in this container.
  13621. if (isLContainer(lNode)) {
  13622. collectNativeNodesInLContainer(lNode, result);
  13623. }
  13624. const tNodeType = tNode.type;
  13625. if (tNodeType & 8 /* TNodeType.ElementContainer */) {
  13626. collectNativeNodes(tView, lView, tNode.child, result);
  13627. }
  13628. else if (tNodeType & 32 /* TNodeType.Icu */) {
  13629. const nextRNode = icuContainerIterate(tNode, lView);
  13630. let rNode;
  13631. while ((rNode = nextRNode())) {
  13632. result.push(rNode);
  13633. }
  13634. }
  13635. else if (tNodeType & 16 /* TNodeType.Projection */) {
  13636. const nodesInSlot = getProjectionNodes(lView, tNode);
  13637. if (Array.isArray(nodesInSlot)) {
  13638. result.push(...nodesInSlot);
  13639. }
  13640. else {
  13641. const parentView = getLViewParent(lView[DECLARATION_COMPONENT_VIEW]);
  13642. ngDevMode && assertParentView(parentView);
  13643. collectNativeNodes(parentView[TVIEW], parentView, nodesInSlot, result, true);
  13644. }
  13645. }
  13646. tNode = isProjection ? tNode.projectionNext : tNode.next;
  13647. }
  13648. return result;
  13649. }
  13650. /**
  13651. * Collects all root nodes in all views in a given LContainer.
  13652. */
  13653. function collectNativeNodesInLContainer(lContainer, result) {
  13654. for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
  13655. const lViewInAContainer = lContainer[i];
  13656. const lViewFirstChildTNode = lViewInAContainer[TVIEW].firstChild;
  13657. if (lViewFirstChildTNode !== null) {
  13658. collectNativeNodes(lViewInAContainer[TVIEW], lViewInAContainer, lViewFirstChildTNode, result);
  13659. }
  13660. }
  13661. // When an LContainer is created, the anchor (comment) node is:
  13662. // - (1) either reused in case of an ElementContainer (<ng-container>)
  13663. // - (2) or a new comment node is created
  13664. // In the first case, the anchor comment node would be added to the final
  13665. // list by the code in the `collectNativeNodes` function
  13666. // (see the `result.push(unwrapRNode(lNode))` line), but the second
  13667. // case requires extra handling: the anchor node needs to be added to the
  13668. // final list manually. See additional information in the `createAnchorNode`
  13669. // function in the `view_container_ref.ts`.
  13670. //
  13671. // In the first case, the same reference would be stored in the `NATIVE`
  13672. // and `HOST` slots in an LContainer. Otherwise, this is the second case and
  13673. // we should add an element to the final list.
  13674. if (lContainer[NATIVE] !== lContainer[HOST]) {
  13675. result.push(lContainer[NATIVE]);
  13676. }
  13677. }
  13678. function addAfterRenderSequencesForView(lView) {
  13679. if (lView[AFTER_RENDER_SEQUENCES_TO_ADD] !== null) {
  13680. for (const sequence of lView[AFTER_RENDER_SEQUENCES_TO_ADD]) {
  13681. sequence.impl.addSequence(sequence);
  13682. }
  13683. lView[AFTER_RENDER_SEQUENCES_TO_ADD].length = 0;
  13684. }
  13685. }
  13686. let freeConsumers = [];
  13687. /**
  13688. * Create a new template consumer pointing at the specified LView.
  13689. * Sometimes, a previously created consumer may be reused, in order to save on allocations. In that
  13690. * case, the LView will be updated.
  13691. */
  13692. function getOrBorrowReactiveLViewConsumer(lView) {
  13693. return lView[REACTIVE_TEMPLATE_CONSUMER] ?? borrowReactiveLViewConsumer(lView);
  13694. }
  13695. function borrowReactiveLViewConsumer(lView) {
  13696. const consumer = freeConsumers.pop() ?? Object.create(REACTIVE_LVIEW_CONSUMER_NODE);
  13697. consumer.lView = lView;
  13698. return consumer;
  13699. }
  13700. function maybeReturnReactiveLViewConsumer(consumer) {
  13701. if (consumer.lView[REACTIVE_TEMPLATE_CONSUMER] === consumer) {
  13702. // The consumer got committed.
  13703. return;
  13704. }
  13705. consumer.lView = null;
  13706. freeConsumers.push(consumer);
  13707. }
  13708. const REACTIVE_LVIEW_CONSUMER_NODE = {
  13709. ...REACTIVE_NODE,
  13710. consumerIsAlwaysLive: true,
  13711. kind: 'template',
  13712. consumerMarkedDirty: (node) => {
  13713. markAncestorsForTraversal(node.lView);
  13714. },
  13715. consumerOnSignalRead() {
  13716. this.lView[REACTIVE_TEMPLATE_CONSUMER] = this;
  13717. },
  13718. };
  13719. /**
  13720. * Creates a temporary consumer for use with `LView`s that should not have consumers.
  13721. * If the LView already has a consumer, returns the existing one instead.
  13722. *
  13723. * This is necessary because some APIs may cause change detection directly on an LView
  13724. * that we do not want to have a consumer (Embedded views today). As a result, there
  13725. * would be no active consumer from running change detection on its host component
  13726. * and any signals in the LView template would be untracked. Instead, we create
  13727. * this temporary consumer that marks the first parent that _should_ have a consumer
  13728. * for refresh. Once change detection runs as part of that refresh, we throw away
  13729. * this consumer because its signals will then be tracked by the parent's consumer.
  13730. */
  13731. function getOrCreateTemporaryConsumer(lView) {
  13732. const consumer = lView[REACTIVE_TEMPLATE_CONSUMER] ?? Object.create(TEMPORARY_CONSUMER_NODE);
  13733. consumer.lView = lView;
  13734. return consumer;
  13735. }
  13736. const TEMPORARY_CONSUMER_NODE = {
  13737. ...REACTIVE_NODE,
  13738. consumerIsAlwaysLive: true,
  13739. kind: 'template',
  13740. consumerMarkedDirty: (node) => {
  13741. let parent = getLViewParent(node.lView);
  13742. while (parent && !viewShouldHaveReactiveConsumer(parent[TVIEW])) {
  13743. parent = getLViewParent(parent);
  13744. }
  13745. if (!parent) {
  13746. // If we can't find an appropriate parent that should have a consumer, we
  13747. // don't have a way of appropriately refreshing this LView as part of application synchronization.
  13748. return;
  13749. }
  13750. markViewForRefresh(parent);
  13751. },
  13752. consumerOnSignalRead() {
  13753. this.lView[REACTIVE_TEMPLATE_CONSUMER] = this;
  13754. },
  13755. };
  13756. /**
  13757. * Indicates if the view should get its own reactive consumer node.
  13758. *
  13759. * In the current design, all embedded views share a consumer with the component view. This allows
  13760. * us to refresh at the component level rather than at a per-view level. In addition, root views get
  13761. * their own reactive node because root component will have a host view that executes the
  13762. * component's host bindings. This needs to be tracked in a consumer as well.
  13763. *
  13764. * To get a more granular change detection than per-component, all we would just need to update the
  13765. * condition here so that a given view gets a reactive consumer which can become dirty independently
  13766. * from its parent component. For example embedded views for signal components could be created with
  13767. * a new type "SignalEmbeddedView" and the condition here wouldn't even need updating in order to
  13768. * get granular per-view change detection for signal components.
  13769. */
  13770. function viewShouldHaveReactiveConsumer(tView) {
  13771. return tView.type !== 2 /* TViewType.Embedded */;
  13772. }
  13773. function runEffectsInView(view) {
  13774. if (view[EFFECTS] === null) {
  13775. return;
  13776. }
  13777. // Since effects can make other effects dirty, we flush them in a loop until there are no more to
  13778. // flush.
  13779. let tryFlushEffects = true;
  13780. while (tryFlushEffects) {
  13781. let foundDirtyEffect = false;
  13782. for (const effect of view[EFFECTS]) {
  13783. if (!effect.dirty) {
  13784. continue;
  13785. }
  13786. foundDirtyEffect = true;
  13787. // `runEffectsInView` is called during change detection, and therefore runs
  13788. // in the Angular zone if it's available.
  13789. if (effect.zone === null || Zone.current === effect.zone) {
  13790. effect.run();
  13791. }
  13792. else {
  13793. effect.zone.run(() => effect.run());
  13794. }
  13795. }
  13796. // Check if we need to continue flushing. If we didn't find any dirty effects, then there's
  13797. // no need to loop back. Otherwise, check the view to see if it was marked for traversal
  13798. // again. If so, there's a chance that one of the effects we ran caused another effect to
  13799. // become dirty.
  13800. tryFlushEffects = foundDirtyEffect && !!(view[FLAGS] & 8192 /* LViewFlags.HasChildViewsToRefresh */);
  13801. }
  13802. }
  13803. /**
  13804. * The maximum number of times the change detection traversal will rerun before throwing an error.
  13805. */
  13806. const MAXIMUM_REFRESH_RERUNS$1 = 100;
  13807. function detectChangesInternal(lView, notifyErrorHandler = true, mode = 0 /* ChangeDetectionMode.Global */) {
  13808. const environment = lView[ENVIRONMENT];
  13809. const rendererFactory = environment.rendererFactory;
  13810. // Check no changes mode is a dev only mode used to verify that bindings have not changed
  13811. // since they were assigned. We do not want to invoke renderer factory functions in that mode
  13812. // to avoid any possible side-effects.
  13813. const checkNoChangesMode = !!ngDevMode && isInCheckNoChangesMode();
  13814. if (!checkNoChangesMode) {
  13815. rendererFactory.begin?.();
  13816. }
  13817. try {
  13818. detectChangesInViewWhileDirty(lView, mode);
  13819. }
  13820. catch (error) {
  13821. if (notifyErrorHandler) {
  13822. handleError$1(lView, error);
  13823. }
  13824. throw error;
  13825. }
  13826. finally {
  13827. if (!checkNoChangesMode) {
  13828. rendererFactory.end?.();
  13829. }
  13830. }
  13831. }
  13832. function detectChangesInViewWhileDirty(lView, mode) {
  13833. const lastIsRefreshingViewsValue = isRefreshingViews();
  13834. try {
  13835. setIsRefreshingViews(true);
  13836. detectChangesInView(lView, mode);
  13837. // We don't need or want to do any looping when in exhaustive checkNoChanges because we
  13838. // already traverse all the views and nothing should change so we shouldn't have to do
  13839. // another pass to pick up new changes.
  13840. if (ngDevMode && isExhaustiveCheckNoChanges()) {
  13841. return;
  13842. }
  13843. let retries = 0;
  13844. // If after running change detection, this view still needs to be refreshed or there are
  13845. // descendants views that need to be refreshed due to re-dirtying during the change detection
  13846. // run, detect changes on the view again. We run change detection in `Targeted` mode to only
  13847. // refresh views with the `RefreshView` flag.
  13848. while (requiresRefreshOrTraversal(lView)) {
  13849. if (retries === MAXIMUM_REFRESH_RERUNS$1) {
  13850. throw new RuntimeError(103 /* RuntimeErrorCode.INFINITE_CHANGE_DETECTION */, ngDevMode &&
  13851. 'Infinite change detection while trying to refresh views. ' +
  13852. 'There may be components which each cause the other to require a refresh, ' +
  13853. 'causing an infinite loop.');
  13854. }
  13855. retries++;
  13856. // Even if this view is detached, we still detect changes in targeted mode because this was
  13857. // the root of the change detection run.
  13858. detectChangesInView(lView, 1 /* ChangeDetectionMode.Targeted */);
  13859. }
  13860. }
  13861. finally {
  13862. // restore state to what it was before entering this change detection loop
  13863. setIsRefreshingViews(lastIsRefreshingViewsValue);
  13864. }
  13865. }
  13866. function checkNoChangesInternal(lView, mode, notifyErrorHandler = true) {
  13867. setIsInCheckNoChangesMode(mode);
  13868. try {
  13869. detectChangesInternal(lView, notifyErrorHandler);
  13870. }
  13871. finally {
  13872. setIsInCheckNoChangesMode(CheckNoChangesMode.Off);
  13873. }
  13874. }
  13875. /**
  13876. * Processes a view in update mode. This includes a number of steps in a specific order:
  13877. * - executing a template function in update mode;
  13878. * - executing hooks;
  13879. * - refreshing queries;
  13880. * - setting host bindings;
  13881. * - refreshing child (embedded and component) views.
  13882. */
  13883. function refreshView(tView, lView, templateFn, context) {
  13884. ngDevMode && assertEqual(isCreationMode(lView), false, 'Should be run in update mode');
  13885. if (isDestroyed(lView))
  13886. return;
  13887. const flags = lView[FLAGS];
  13888. // Check no changes mode is a dev only mode used to verify that bindings have not changed
  13889. // since they were assigned. We do not want to execute lifecycle hooks in that mode.
  13890. const isInCheckNoChangesPass = ngDevMode && isInCheckNoChangesMode();
  13891. const isInExhaustiveCheckNoChangesPass = ngDevMode && isExhaustiveCheckNoChanges();
  13892. // Start component reactive context
  13893. // - We might already be in a reactive context if this is an embedded view of the host.
  13894. // - We might be descending into a view that needs a consumer.
  13895. enterView(lView);
  13896. let returnConsumerToPool = true;
  13897. let prevConsumer = null;
  13898. let currentConsumer = null;
  13899. if (!isInCheckNoChangesPass) {
  13900. if (viewShouldHaveReactiveConsumer(tView)) {
  13901. currentConsumer = getOrBorrowReactiveLViewConsumer(lView);
  13902. prevConsumer = consumerBeforeComputation(currentConsumer);
  13903. }
  13904. else if (getActiveConsumer() === null) {
  13905. // If the current view should not have a reactive consumer but we don't have an active consumer,
  13906. // we still need to create a temporary consumer to track any signal reads in this template.
  13907. // This is a rare case that can happen with `viewContainerRef.createEmbeddedView(...).detectChanges()`.
  13908. // This temporary consumer marks the first parent that _should_ have a consumer for refresh.
  13909. // Once that refresh happens, the signals will be tracked in the parent consumer and we can destroy
  13910. // the temporary one.
  13911. returnConsumerToPool = false;
  13912. currentConsumer = getOrCreateTemporaryConsumer(lView);
  13913. prevConsumer = consumerBeforeComputation(currentConsumer);
  13914. }
  13915. else if (lView[REACTIVE_TEMPLATE_CONSUMER]) {
  13916. consumerDestroy(lView[REACTIVE_TEMPLATE_CONSUMER]);
  13917. lView[REACTIVE_TEMPLATE_CONSUMER] = null;
  13918. }
  13919. }
  13920. try {
  13921. resetPreOrderHookFlags(lView);
  13922. setBindingIndex(tView.bindingStartIndex);
  13923. if (templateFn !== null) {
  13924. executeTemplate(tView, lView, templateFn, 2 /* RenderFlags.Update */, context);
  13925. }
  13926. const hooksInitPhaseCompleted = (flags & 3 /* LViewFlags.InitPhaseStateMask */) === 3 /* InitPhaseState.InitPhaseCompleted */;
  13927. // execute pre-order hooks (OnInit, OnChanges, DoCheck)
  13928. // PERF WARNING: do NOT extract this to a separate function without running benchmarks
  13929. if (!isInCheckNoChangesPass) {
  13930. if (hooksInitPhaseCompleted) {
  13931. const preOrderCheckHooks = tView.preOrderCheckHooks;
  13932. if (preOrderCheckHooks !== null) {
  13933. executeCheckHooks(lView, preOrderCheckHooks, null);
  13934. }
  13935. }
  13936. else {
  13937. const preOrderHooks = tView.preOrderHooks;
  13938. if (preOrderHooks !== null) {
  13939. executeInitAndCheckHooks(lView, preOrderHooks, 0 /* InitPhaseState.OnInitHooksToBeRun */, null);
  13940. }
  13941. incrementInitPhaseFlags(lView, 0 /* InitPhaseState.OnInitHooksToBeRun */);
  13942. }
  13943. }
  13944. // We do not need to mark transplanted views for refresh when doing exhaustive checks
  13945. // because all views will be reached anyways during the traversal.
  13946. if (!isInExhaustiveCheckNoChangesPass) {
  13947. // First mark transplanted views that are declared in this lView as needing a refresh at their
  13948. // insertion points. This is needed to avoid the situation where the template is defined in this
  13949. // `LView` but its declaration appears after the insertion component.
  13950. markTransplantedViewsForRefresh(lView);
  13951. }
  13952. runEffectsInView(lView);
  13953. detectChangesInEmbeddedViews(lView, 0 /* ChangeDetectionMode.Global */);
  13954. // Content query results must be refreshed before content hooks are called.
  13955. if (tView.contentQueries !== null) {
  13956. refreshContentQueries(tView, lView);
  13957. }
  13958. // execute content hooks (AfterContentInit, AfterContentChecked)
  13959. // PERF WARNING: do NOT extract this to a separate function without running benchmarks
  13960. if (!isInCheckNoChangesPass) {
  13961. if (hooksInitPhaseCompleted) {
  13962. const contentCheckHooks = tView.contentCheckHooks;
  13963. if (contentCheckHooks !== null) {
  13964. executeCheckHooks(lView, contentCheckHooks);
  13965. }
  13966. }
  13967. else {
  13968. const contentHooks = tView.contentHooks;
  13969. if (contentHooks !== null) {
  13970. executeInitAndCheckHooks(lView, contentHooks, 1 /* InitPhaseState.AfterContentInitHooksToBeRun */);
  13971. }
  13972. incrementInitPhaseFlags(lView, 1 /* InitPhaseState.AfterContentInitHooksToBeRun */);
  13973. }
  13974. }
  13975. processHostBindingOpCodes(tView, lView);
  13976. // Refresh child component views.
  13977. const components = tView.components;
  13978. if (components !== null) {
  13979. detectChangesInChildComponents(lView, components, 0 /* ChangeDetectionMode.Global */);
  13980. }
  13981. // View queries must execute after refreshing child components because a template in this view
  13982. // could be inserted in a child component. If the view query executes before child component
  13983. // refresh, the template might not yet be inserted.
  13984. const viewQuery = tView.viewQuery;
  13985. if (viewQuery !== null) {
  13986. executeViewQueryFn(2 /* RenderFlags.Update */, viewQuery, context);
  13987. }
  13988. // execute view hooks (AfterViewInit, AfterViewChecked)
  13989. // PERF WARNING: do NOT extract this to a separate function without running benchmarks
  13990. if (!isInCheckNoChangesPass) {
  13991. if (hooksInitPhaseCompleted) {
  13992. const viewCheckHooks = tView.viewCheckHooks;
  13993. if (viewCheckHooks !== null) {
  13994. executeCheckHooks(lView, viewCheckHooks);
  13995. }
  13996. }
  13997. else {
  13998. const viewHooks = tView.viewHooks;
  13999. if (viewHooks !== null) {
  14000. executeInitAndCheckHooks(lView, viewHooks, 2 /* InitPhaseState.AfterViewInitHooksToBeRun */);
  14001. }
  14002. incrementInitPhaseFlags(lView, 2 /* InitPhaseState.AfterViewInitHooksToBeRun */);
  14003. }
  14004. }
  14005. if (tView.firstUpdatePass === true) {
  14006. // We need to make sure that we only flip the flag on successful `refreshView` only
  14007. // Don't do this in `finally` block.
  14008. // If we did this in `finally` block then an exception could block the execution of styling
  14009. // instructions which in turn would be unable to insert themselves into the styling linked
  14010. // list. The result of this would be that if the exception would not be throw on subsequent CD
  14011. // the styling would be unable to process it data and reflect to the DOM.
  14012. tView.firstUpdatePass = false;
  14013. }
  14014. // Schedule any effects that are waiting on the update pass of this view.
  14015. if (lView[EFFECTS_TO_SCHEDULE]) {
  14016. for (const notifyEffect of lView[EFFECTS_TO_SCHEDULE]) {
  14017. notifyEffect();
  14018. }
  14019. // Once they've been run, we can drop the array.
  14020. lView[EFFECTS_TO_SCHEDULE] = null;
  14021. }
  14022. // Do not reset the dirty state when running in check no changes mode. We don't want components
  14023. // to behave differently depending on whether check no changes is enabled or not. For example:
  14024. // Marking an OnPush component as dirty from within the `ngAfterViewInit` hook in order to
  14025. // refresh a `NgClass` binding should work. If we would reset the dirty state in the check
  14026. // no changes cycle, the component would be not be dirty for the next update pass. This would
  14027. // be different in production mode where the component dirty state is not reset.
  14028. if (!isInCheckNoChangesPass) {
  14029. addAfterRenderSequencesForView(lView);
  14030. lView[FLAGS] &= ~(64 /* LViewFlags.Dirty */ | 8 /* LViewFlags.FirstLViewPass */);
  14031. }
  14032. }
  14033. catch (e) {
  14034. if (!isInCheckNoChangesPass) {
  14035. // If refreshing a view causes an error, we need to remark the ancestors as needing traversal
  14036. // because the error might have caused a situation where views below the current location are
  14037. // dirty but will be unreachable because the "has dirty children" flag in the ancestors has been
  14038. // cleared during change detection and we failed to run to completion.
  14039. markAncestorsForTraversal(lView);
  14040. }
  14041. throw e;
  14042. }
  14043. finally {
  14044. if (currentConsumer !== null) {
  14045. consumerAfterComputation(currentConsumer, prevConsumer);
  14046. if (returnConsumerToPool) {
  14047. maybeReturnReactiveLViewConsumer(currentConsumer);
  14048. }
  14049. }
  14050. leaveView();
  14051. }
  14052. }
  14053. /**
  14054. * Goes over embedded views (ones created through ViewContainerRef APIs) and refreshes
  14055. * them by executing an associated template function.
  14056. */
  14057. function detectChangesInEmbeddedViews(lView, mode) {
  14058. for (let lContainer = getFirstLContainer(lView); lContainer !== null; lContainer = getNextLContainer(lContainer)) {
  14059. for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
  14060. const embeddedLView = lContainer[i];
  14061. detectChangesInViewIfAttached(embeddedLView, mode);
  14062. }
  14063. }
  14064. }
  14065. /**
  14066. * Mark transplanted views as needing to be refreshed at their attachment points.
  14067. *
  14068. * @param lView The `LView` that may have transplanted views.
  14069. */
  14070. function markTransplantedViewsForRefresh(lView) {
  14071. for (let lContainer = getFirstLContainer(lView); lContainer !== null; lContainer = getNextLContainer(lContainer)) {
  14072. if (!(lContainer[FLAGS] & 2 /* LContainerFlags.HasTransplantedViews */))
  14073. continue;
  14074. const movedViews = lContainer[MOVED_VIEWS];
  14075. ngDevMode && assertDefined(movedViews, 'Transplanted View flags set but missing MOVED_VIEWS');
  14076. for (let i = 0; i < movedViews.length; i++) {
  14077. const movedLView = movedViews[i];
  14078. markViewForRefresh(movedLView);
  14079. }
  14080. }
  14081. }
  14082. /**
  14083. * Detects changes in a component by entering the component view and processing its bindings,
  14084. * queries, etc. if it is CheckAlways, OnPush and Dirty, etc.
  14085. *
  14086. * @param componentHostIdx Element index in LView[] (adjusted for HEADER_OFFSET)
  14087. */
  14088. function detectChangesInComponent(hostLView, componentHostIdx, mode) {
  14089. ngDevMode && assertEqual(isCreationMode(hostLView), false, 'Should be run in update mode');
  14090. profiler(18 /* ProfilerEvent.ComponentStart */);
  14091. const componentView = getComponentLViewByIndex(componentHostIdx, hostLView);
  14092. detectChangesInViewIfAttached(componentView, mode);
  14093. profiler(19 /* ProfilerEvent.ComponentEnd */, componentView[CONTEXT]);
  14094. }
  14095. /**
  14096. * Visits a view as part of change detection traversal.
  14097. *
  14098. * If the view is detached, no additional traversal happens.
  14099. */
  14100. function detectChangesInViewIfAttached(lView, mode) {
  14101. if (!viewAttachedToChangeDetector(lView)) {
  14102. return;
  14103. }
  14104. detectChangesInView(lView, mode);
  14105. }
  14106. /**
  14107. * Visits a view as part of change detection traversal.
  14108. *
  14109. * The view is refreshed if:
  14110. * - If the view is CheckAlways or Dirty and ChangeDetectionMode is `Global`
  14111. * - If the view has the `RefreshView` flag
  14112. *
  14113. * The view is not refreshed, but descendants are traversed in `ChangeDetectionMode.Targeted` if the
  14114. * view HasChildViewsToRefresh flag is set.
  14115. */
  14116. function detectChangesInView(lView, mode) {
  14117. const isInCheckNoChangesPass = ngDevMode && isInCheckNoChangesMode();
  14118. const tView = lView[TVIEW];
  14119. const flags = lView[FLAGS];
  14120. const consumer = lView[REACTIVE_TEMPLATE_CONSUMER];
  14121. // Refresh CheckAlways views in Global mode.
  14122. let shouldRefreshView = !!(mode === 0 /* ChangeDetectionMode.Global */ && flags & 16 /* LViewFlags.CheckAlways */);
  14123. // Refresh Dirty views in Global mode, as long as we're not in checkNoChanges.
  14124. // CheckNoChanges never worked with `OnPush` components because the `Dirty` flag was
  14125. // cleared before checkNoChanges ran. Because there is now a loop for to check for
  14126. // backwards views, it gives an opportunity for `OnPush` components to be marked `Dirty`
  14127. // before the CheckNoChanges pass. We don't want existing errors that are hidden by the
  14128. // current CheckNoChanges bug to surface when making unrelated changes.
  14129. shouldRefreshView ||= !!(flags & 64 /* LViewFlags.Dirty */ &&
  14130. mode === 0 /* ChangeDetectionMode.Global */ &&
  14131. !isInCheckNoChangesPass);
  14132. // Always refresh views marked for refresh, regardless of mode.
  14133. shouldRefreshView ||= !!(flags & 1024 /* LViewFlags.RefreshView */);
  14134. // Refresh views when they have a dirty reactive consumer, regardless of mode.
  14135. shouldRefreshView ||= !!(consumer?.dirty && consumerPollProducersForChange(consumer));
  14136. shouldRefreshView ||= !!(ngDevMode && isExhaustiveCheckNoChanges());
  14137. // Mark the Flags and `ReactiveNode` as not dirty before refreshing the component, so that they
  14138. // can be re-dirtied during the refresh process.
  14139. if (consumer) {
  14140. consumer.dirty = false;
  14141. }
  14142. lView[FLAGS] &= -9217;
  14143. if (shouldRefreshView) {
  14144. refreshView(tView, lView, tView.template, lView[CONTEXT]);
  14145. }
  14146. else if (flags & 8192 /* LViewFlags.HasChildViewsToRefresh */) {
  14147. if (!isInCheckNoChangesPass) {
  14148. runEffectsInView(lView);
  14149. }
  14150. detectChangesInEmbeddedViews(lView, 1 /* ChangeDetectionMode.Targeted */);
  14151. const components = tView.components;
  14152. if (components !== null) {
  14153. detectChangesInChildComponents(lView, components, 1 /* ChangeDetectionMode.Targeted */);
  14154. }
  14155. if (!isInCheckNoChangesPass) {
  14156. addAfterRenderSequencesForView(lView);
  14157. }
  14158. }
  14159. }
  14160. /** Refreshes child components in the current view (update mode). */
  14161. function detectChangesInChildComponents(hostLView, components, mode) {
  14162. for (let i = 0; i < components.length; i++) {
  14163. detectChangesInComponent(hostLView, components[i], mode);
  14164. }
  14165. }
  14166. /**
  14167. * Invoke `HostBindingsFunction`s for view.
  14168. *
  14169. * This methods executes `TView.hostBindingOpCodes`. It is used to execute the
  14170. * `HostBindingsFunction`s associated with the current `LView`.
  14171. *
  14172. * @param tView Current `TView`.
  14173. * @param lView Current `LView`.
  14174. */
  14175. function processHostBindingOpCodes(tView, lView) {
  14176. const hostBindingOpCodes = tView.hostBindingOpCodes;
  14177. if (hostBindingOpCodes === null)
  14178. return;
  14179. try {
  14180. for (let i = 0; i < hostBindingOpCodes.length; i++) {
  14181. const opCode = hostBindingOpCodes[i];
  14182. if (opCode < 0) {
  14183. // Negative numbers are element indexes.
  14184. setSelectedIndex(~opCode);
  14185. }
  14186. else {
  14187. // Positive numbers are NumberTuple which store bindingRootIndex and directiveIndex.
  14188. const directiveIdx = opCode;
  14189. const bindingRootIndx = hostBindingOpCodes[++i];
  14190. const hostBindingFn = hostBindingOpCodes[++i];
  14191. setBindingRootForHostBindings(bindingRootIndx, directiveIdx);
  14192. const context = lView[directiveIdx];
  14193. profiler(24 /* ProfilerEvent.HostBindingsUpdateStart */, context);
  14194. hostBindingFn(2 /* RenderFlags.Update */, context);
  14195. profiler(25 /* ProfilerEvent.HostBindingsUpdateEnd */, context);
  14196. }
  14197. }
  14198. }
  14199. finally {
  14200. setSelectedIndex(-1);
  14201. }
  14202. }
  14203. /**
  14204. * Marks current view and all ancestors dirty.
  14205. *
  14206. * Returns the root view because it is found as a byproduct of marking the view tree
  14207. * dirty, and can be used by methods that consume markViewDirty() to easily schedule
  14208. * change detection. Otherwise, such methods would need to traverse up the view tree
  14209. * an additional time to get the root view and schedule a tick on it.
  14210. *
  14211. * @param lView The starting LView to mark dirty
  14212. * @returns the root LView
  14213. */
  14214. function markViewDirty(lView, source) {
  14215. const dirtyBitsToUse = isRefreshingViews()
  14216. ? // When we are actively refreshing views, we only use the `Dirty` bit to mark a view
  14217. 64 /* LViewFlags.Dirty */
  14218. : // When we are not actively refreshing a view tree, it is absolutely
  14219. // valid to update state and mark views dirty. We use the `RefreshView` flag in this
  14220. // case to allow synchronously rerunning change detection. This applies today to
  14221. // afterRender hooks as well as animation listeners which execute after detecting
  14222. // changes in a view when the render factory flushes.
  14223. 1024 /* LViewFlags.RefreshView */ | 64 /* LViewFlags.Dirty */;
  14224. lView[ENVIRONMENT].changeDetectionScheduler?.notify(source);
  14225. while (lView) {
  14226. lView[FLAGS] |= dirtyBitsToUse;
  14227. const parent = getLViewParent(lView);
  14228. // Stop traversing up as soon as you find a root view that wasn't attached to any container
  14229. if (isRootView(lView) && !parent) {
  14230. return lView;
  14231. }
  14232. // continue otherwise
  14233. lView = parent;
  14234. }
  14235. return null;
  14236. }
  14237. /**
  14238. * Creates a LContainer, either from a container instruction, or for a ViewContainerRef.
  14239. *
  14240. * @param hostNative The host element for the LContainer
  14241. * @param hostTNode The host TNode for the LContainer
  14242. * @param currentView The parent view of the LContainer
  14243. * @param native The native comment element
  14244. * @param isForViewContainerRef Optional a flag indicating the ViewContainerRef case
  14245. * @returns LContainer
  14246. */
  14247. function createLContainer(hostNative, currentView, native, tNode) {
  14248. ngDevMode && assertLView(currentView);
  14249. const lContainer = [
  14250. hostNative, // host native
  14251. true, // Boolean `true` in this position signifies that this is an `LContainer`
  14252. 0, // flags
  14253. currentView, // parent
  14254. null, // next
  14255. tNode, // t_host
  14256. null, // dehydrated views
  14257. native, // native,
  14258. null, // view refs
  14259. null, // moved views
  14260. ];
  14261. ngDevMode &&
  14262. assertEqual(lContainer.length, CONTAINER_HEADER_OFFSET, 'Should allocate correct number of slots for LContainer header.');
  14263. return lContainer;
  14264. }
  14265. function getLViewFromLContainer(lContainer, index) {
  14266. const adjustedIndex = CONTAINER_HEADER_OFFSET + index;
  14267. // avoid reading past the array boundaries
  14268. if (adjustedIndex < lContainer.length) {
  14269. const lView = lContainer[adjustedIndex];
  14270. ngDevMode && assertLView(lView);
  14271. return lView;
  14272. }
  14273. return undefined;
  14274. }
  14275. function addLViewToLContainer(lContainer, lView, index, addToDOM = true) {
  14276. const tView = lView[TVIEW];
  14277. // Insert into the view tree so the new view can be change-detected
  14278. insertView(tView, lView, lContainer, index);
  14279. // Insert elements that belong to this view into the DOM tree
  14280. if (addToDOM) {
  14281. const beforeNode = getBeforeNodeForView(index, lContainer);
  14282. const renderer = lView[RENDERER];
  14283. const parentRNode = renderer.parentNode(lContainer[NATIVE]);
  14284. if (parentRNode !== null) {
  14285. addViewToDOM(tView, lContainer[T_HOST], renderer, lView, parentRNode, beforeNode);
  14286. }
  14287. }
  14288. // When in hydration mode, reset the pointer to the first child in
  14289. // the dehydrated view. This indicates that the view was hydrated and
  14290. // further attaching/detaching should work with this view as normal.
  14291. const hydrationInfo = lView[HYDRATION];
  14292. if (hydrationInfo !== null && hydrationInfo.firstChild !== null) {
  14293. hydrationInfo.firstChild = null;
  14294. }
  14295. }
  14296. function removeLViewFromLContainer(lContainer, index) {
  14297. const lView = detachView(lContainer, index);
  14298. if (lView !== undefined) {
  14299. destroyLView(lView[TVIEW], lView);
  14300. }
  14301. return lView;
  14302. }
  14303. /**
  14304. * Detaches a view from a container.
  14305. *
  14306. * This method removes the view from the container's array of active views. It also
  14307. * removes the view's elements from the DOM.
  14308. *
  14309. * @param lContainer The container from which to detach a view
  14310. * @param removeIndex The index of the view to detach
  14311. * @returns Detached LView instance.
  14312. */
  14313. function detachView(lContainer, removeIndex) {
  14314. if (lContainer.length <= CONTAINER_HEADER_OFFSET)
  14315. return;
  14316. const indexInContainer = CONTAINER_HEADER_OFFSET + removeIndex;
  14317. const viewToDetach = lContainer[indexInContainer];
  14318. if (viewToDetach) {
  14319. const declarationLContainer = viewToDetach[DECLARATION_LCONTAINER];
  14320. if (declarationLContainer !== null && declarationLContainer !== lContainer) {
  14321. detachMovedView(declarationLContainer, viewToDetach);
  14322. }
  14323. if (removeIndex > 0) {
  14324. lContainer[indexInContainer - 1][NEXT] = viewToDetach[NEXT];
  14325. }
  14326. const removedLView = removeFromArray(lContainer, CONTAINER_HEADER_OFFSET + removeIndex);
  14327. removeViewFromDOM(viewToDetach[TVIEW], viewToDetach);
  14328. // notify query that a view has been removed
  14329. const lQueries = removedLView[QUERIES];
  14330. if (lQueries !== null) {
  14331. lQueries.detachView(removedLView[TVIEW]);
  14332. }
  14333. viewToDetach[PARENT] = null;
  14334. viewToDetach[NEXT] = null;
  14335. // Unsets the attached flag
  14336. viewToDetach[FLAGS] &= -129 /* LViewFlags.Attached */;
  14337. }
  14338. return viewToDetach;
  14339. }
  14340. /**
  14341. * Inserts a view into a container.
  14342. *
  14343. * This adds the view to the container's array of active views in the correct
  14344. * position. It also adds the view's elements to the DOM if the container isn't a
  14345. * root node of another view (in that case, the view's elements will be added when
  14346. * the container's parent view is added later).
  14347. *
  14348. * @param tView The `TView' of the `LView` to insert
  14349. * @param lView The view to insert
  14350. * @param lContainer The container into which the view should be inserted
  14351. * @param index Which index in the container to insert the child view into
  14352. */
  14353. function insertView(tView, lView, lContainer, index) {
  14354. ngDevMode && assertLView(lView);
  14355. ngDevMode && assertLContainer(lContainer);
  14356. const indexInContainer = CONTAINER_HEADER_OFFSET + index;
  14357. const containerLength = lContainer.length;
  14358. if (index > 0) {
  14359. // This is a new view, we need to add it to the children.
  14360. lContainer[indexInContainer - 1][NEXT] = lView;
  14361. }
  14362. if (index < containerLength - CONTAINER_HEADER_OFFSET) {
  14363. lView[NEXT] = lContainer[indexInContainer];
  14364. addToArray(lContainer, CONTAINER_HEADER_OFFSET + index, lView);
  14365. }
  14366. else {
  14367. lContainer.push(lView);
  14368. lView[NEXT] = null;
  14369. }
  14370. lView[PARENT] = lContainer;
  14371. // track views where declaration and insertion points are different
  14372. const declarationLContainer = lView[DECLARATION_LCONTAINER];
  14373. if (declarationLContainer !== null && lContainer !== declarationLContainer) {
  14374. trackMovedView(declarationLContainer, lView);
  14375. }
  14376. // notify query that a new view has been added
  14377. const lQueries = lView[QUERIES];
  14378. if (lQueries !== null) {
  14379. lQueries.insertView(tView);
  14380. }
  14381. updateAncestorTraversalFlagsOnAttach(lView);
  14382. // Sets the attached flag
  14383. lView[FLAGS] |= 128 /* LViewFlags.Attached */;
  14384. }
  14385. /**
  14386. * Track views created from the declaration container (TemplateRef) and inserted into a
  14387. * different LContainer or attached directly to ApplicationRef.
  14388. */
  14389. function trackMovedView(declarationContainer, lView) {
  14390. ngDevMode && assertDefined(lView, 'LView required');
  14391. ngDevMode && assertLContainer(declarationContainer);
  14392. const movedViews = declarationContainer[MOVED_VIEWS];
  14393. const parent = lView[PARENT];
  14394. ngDevMode && assertDefined(parent, 'missing parent');
  14395. if (isLView(parent)) {
  14396. declarationContainer[FLAGS] |= 2 /* LContainerFlags.HasTransplantedViews */;
  14397. }
  14398. else {
  14399. const insertedComponentLView = parent[PARENT][DECLARATION_COMPONENT_VIEW];
  14400. ngDevMode && assertDefined(insertedComponentLView, 'Missing insertedComponentLView');
  14401. const declaredComponentLView = lView[DECLARATION_COMPONENT_VIEW];
  14402. ngDevMode && assertDefined(declaredComponentLView, 'Missing declaredComponentLView');
  14403. if (declaredComponentLView !== insertedComponentLView) {
  14404. // At this point the declaration-component is not same as insertion-component; this means that
  14405. // this is a transplanted view. Mark the declared lView as having transplanted views so that
  14406. // those views can participate in CD.
  14407. declarationContainer[FLAGS] |= 2 /* LContainerFlags.HasTransplantedViews */;
  14408. }
  14409. }
  14410. if (movedViews === null) {
  14411. declarationContainer[MOVED_VIEWS] = [lView];
  14412. }
  14413. else {
  14414. movedViews.push(lView);
  14415. }
  14416. }
  14417. let ViewRef$1 = class ViewRef {
  14418. _lView;
  14419. _cdRefInjectingView;
  14420. notifyErrorHandler;
  14421. _appRef = null;
  14422. _attachedToViewContainer = false;
  14423. get rootNodes() {
  14424. const lView = this._lView;
  14425. const tView = lView[TVIEW];
  14426. return collectNativeNodes(tView, lView, tView.firstChild, []);
  14427. }
  14428. constructor(
  14429. /**
  14430. * This represents `LView` associated with the component when ViewRef is a ChangeDetectorRef.
  14431. *
  14432. * When ViewRef is created for a dynamic component, this also represents the `LView` for the
  14433. * component.
  14434. *
  14435. * For a "regular" ViewRef created for an embedded view, this is the `LView` for the embedded
  14436. * view.
  14437. *
  14438. * @internal
  14439. */
  14440. _lView,
  14441. /**
  14442. * This represents the `LView` associated with the point where `ChangeDetectorRef` was
  14443. * requested.
  14444. *
  14445. * This may be different from `_lView` if the `_cdRefInjectingView` is an embedded view.
  14446. */
  14447. _cdRefInjectingView, notifyErrorHandler = true) {
  14448. this._lView = _lView;
  14449. this._cdRefInjectingView = _cdRefInjectingView;
  14450. this.notifyErrorHandler = notifyErrorHandler;
  14451. }
  14452. get context() {
  14453. return this._lView[CONTEXT];
  14454. }
  14455. /**
  14456. * @deprecated Replacing the full context object is not supported. Modify the context
  14457. * directly, or consider using a `Proxy` if you need to replace the full object.
  14458. * // TODO(devversion): Remove this.
  14459. */
  14460. set context(value) {
  14461. if (ngDevMode) {
  14462. // Note: We have a warning message here because the `@deprecated` JSDoc will not be picked
  14463. // up for assignments on the setter. We want to let users know about the deprecated usage.
  14464. console.warn('Angular: Replacing the `context` object of an `EmbeddedViewRef` is deprecated.');
  14465. }
  14466. this._lView[CONTEXT] = value;
  14467. }
  14468. get destroyed() {
  14469. return isDestroyed(this._lView);
  14470. }
  14471. destroy() {
  14472. if (this._appRef) {
  14473. this._appRef.detachView(this);
  14474. }
  14475. else if (this._attachedToViewContainer) {
  14476. const parent = this._lView[PARENT];
  14477. if (isLContainer(parent)) {
  14478. const viewRefs = parent[VIEW_REFS];
  14479. const index = viewRefs ? viewRefs.indexOf(this) : -1;
  14480. if (index > -1) {
  14481. ngDevMode &&
  14482. assertEqual(index, parent.indexOf(this._lView) - CONTAINER_HEADER_OFFSET, 'An attached view should be in the same position within its container as its ViewRef in the VIEW_REFS array.');
  14483. detachView(parent, index);
  14484. removeFromArray(viewRefs, index);
  14485. }
  14486. }
  14487. this._attachedToViewContainer = false;
  14488. }
  14489. destroyLView(this._lView[TVIEW], this._lView);
  14490. }
  14491. onDestroy(callback) {
  14492. storeLViewOnDestroy(this._lView, callback);
  14493. }
  14494. /**
  14495. * Marks a view and all of its ancestors dirty.
  14496. *
  14497. * This can be used to ensure an {@link ChangeDetectionStrategy#OnPush} component is
  14498. * checked when it needs to be re-rendered but the two normal triggers haven't marked it
  14499. * dirty (i.e. inputs haven't changed and events haven't fired in the view).
  14500. *
  14501. * <!-- TODO: Add a link to a chapter on OnPush components -->
  14502. *
  14503. * @usageNotes
  14504. * ### Example
  14505. *
  14506. * ```ts
  14507. * @Component({
  14508. * selector: 'app-root',
  14509. * template: `Number of ticks: {{numberOfTicks}}`
  14510. * changeDetection: ChangeDetectionStrategy.OnPush,
  14511. * })
  14512. * class AppComponent {
  14513. * numberOfTicks = 0;
  14514. *
  14515. * constructor(private ref: ChangeDetectorRef) {
  14516. * setInterval(() => {
  14517. * this.numberOfTicks++;
  14518. * // the following is required, otherwise the view will not be updated
  14519. * this.ref.markForCheck();
  14520. * }, 1000);
  14521. * }
  14522. * }
  14523. * ```
  14524. */
  14525. markForCheck() {
  14526. markViewDirty(this._cdRefInjectingView || this._lView, 4 /* NotificationSource.MarkForCheck */);
  14527. }
  14528. /**
  14529. * Detaches the view from the change detection tree.
  14530. *
  14531. * Detached views will not be checked during change detection runs until they are
  14532. * re-attached, even if they are dirty. `detach` can be used in combination with
  14533. * {@link ChangeDetectorRef#detectChanges} to implement local change
  14534. * detection checks.
  14535. *
  14536. * <!-- TODO: Add a link to a chapter on detach/reattach/local digest -->
  14537. * <!-- TODO: Add a live demo once ref.detectChanges is merged into master -->
  14538. *
  14539. * @usageNotes
  14540. * ### Example
  14541. *
  14542. * The following example defines a component with a large list of readonly data.
  14543. * Imagine the data changes constantly, many times per second. For performance reasons,
  14544. * we want to check and update the list every five seconds. We can do that by detaching
  14545. * the component's change detector and doing a local check every five seconds.
  14546. *
  14547. * ```ts
  14548. * class DataProvider {
  14549. * // in a real application the returned data will be different every time
  14550. * get data() {
  14551. * return [1,2,3,4,5];
  14552. * }
  14553. * }
  14554. *
  14555. * @Component({
  14556. * selector: 'giant-list',
  14557. * template: `
  14558. * <li *ngFor="let d of dataProvider.data">Data {{d}}</li>
  14559. * `,
  14560. * })
  14561. * class GiantList {
  14562. * constructor(private ref: ChangeDetectorRef, private dataProvider: DataProvider) {
  14563. * ref.detach();
  14564. * setInterval(() => {
  14565. * this.ref.detectChanges();
  14566. * }, 5000);
  14567. * }
  14568. * }
  14569. *
  14570. * @Component({
  14571. * selector: 'app',
  14572. * providers: [DataProvider],
  14573. * template: `
  14574. * <giant-list><giant-list>
  14575. * `,
  14576. * })
  14577. * class App {
  14578. * }
  14579. * ```
  14580. */
  14581. detach() {
  14582. this._lView[FLAGS] &= -129 /* LViewFlags.Attached */;
  14583. }
  14584. /**
  14585. * Re-attaches a view to the change detection tree.
  14586. *
  14587. * This can be used to re-attach views that were previously detached from the tree
  14588. * using {@link ChangeDetectorRef#detach}. Views are attached to the tree by default.
  14589. *
  14590. * <!-- TODO: Add a link to a chapter on detach/reattach/local digest -->
  14591. *
  14592. * @usageNotes
  14593. * ### Example
  14594. *
  14595. * The following example creates a component displaying `live` data. The component will detach
  14596. * its change detector from the main change detector tree when the component's live property
  14597. * is set to false.
  14598. *
  14599. * ```ts
  14600. * class DataProvider {
  14601. * data = 1;
  14602. *
  14603. * constructor() {
  14604. * setInterval(() => {
  14605. * this.data = this.data * 2;
  14606. * }, 500);
  14607. * }
  14608. * }
  14609. *
  14610. * @Component({
  14611. * selector: 'live-data',
  14612. * inputs: ['live'],
  14613. * template: 'Data: {{dataProvider.data}}'
  14614. * })
  14615. * class LiveData {
  14616. * constructor(private ref: ChangeDetectorRef, private dataProvider: DataProvider) {}
  14617. *
  14618. * set live(value) {
  14619. * if (value) {
  14620. * this.ref.reattach();
  14621. * } else {
  14622. * this.ref.detach();
  14623. * }
  14624. * }
  14625. * }
  14626. *
  14627. * @Component({
  14628. * selector: 'app-root',
  14629. * providers: [DataProvider],
  14630. * template: `
  14631. * Live Update: <input type="checkbox" [(ngModel)]="live">
  14632. * <live-data [live]="live"><live-data>
  14633. * `,
  14634. * })
  14635. * class AppComponent {
  14636. * live = true;
  14637. * }
  14638. * ```
  14639. */
  14640. reattach() {
  14641. updateAncestorTraversalFlagsOnAttach(this._lView);
  14642. this._lView[FLAGS] |= 128 /* LViewFlags.Attached */;
  14643. }
  14644. /**
  14645. * Checks the view and its children.
  14646. *
  14647. * This can also be used in combination with {@link ChangeDetectorRef#detach} to implement
  14648. * local change detection checks.
  14649. *
  14650. * <!-- TODO: Add a link to a chapter on detach/reattach/local digest -->
  14651. * <!-- TODO: Add a live demo once ref.detectChanges is merged into master -->
  14652. *
  14653. * @usageNotes
  14654. * ### Example
  14655. *
  14656. * The following example defines a component with a large list of readonly data.
  14657. * Imagine, the data changes constantly, many times per second. For performance reasons,
  14658. * we want to check and update the list every five seconds.
  14659. *
  14660. * We can do that by detaching the component's change detector and doing a local change detection
  14661. * check every five seconds.
  14662. *
  14663. * See {@link ChangeDetectorRef#detach} for more information.
  14664. */
  14665. detectChanges() {
  14666. // Add `RefreshView` flag to ensure this view is refreshed if not already dirty.
  14667. // `RefreshView` flag is used intentionally over `Dirty` because it gets cleared before
  14668. // executing any of the actual refresh code while the `Dirty` flag doesn't get cleared
  14669. // until the end of the refresh. Using `RefreshView` prevents creating a potential difference
  14670. // in the state of the LViewFlags during template execution.
  14671. this._lView[FLAGS] |= 1024 /* LViewFlags.RefreshView */;
  14672. detectChangesInternal(this._lView, this.notifyErrorHandler);
  14673. }
  14674. /**
  14675. * Checks the change detector and its children, and throws if any changes are detected.
  14676. *
  14677. * This is used in development mode to verify that running change detection doesn't
  14678. * introduce other changes.
  14679. */
  14680. checkNoChanges() {
  14681. if (ngDevMode) {
  14682. checkNoChangesInternal(this._lView, CheckNoChangesMode.OnlyDirtyViews, this.notifyErrorHandler);
  14683. }
  14684. }
  14685. attachToViewContainerRef() {
  14686. if (this._appRef) {
  14687. throw new RuntimeError(902 /* RuntimeErrorCode.VIEW_ALREADY_ATTACHED */, ngDevMode && 'This view is already attached directly to the ApplicationRef!');
  14688. }
  14689. this._attachedToViewContainer = true;
  14690. }
  14691. detachFromAppRef() {
  14692. this._appRef = null;
  14693. const isRoot = isRootView(this._lView);
  14694. const declarationContainer = this._lView[DECLARATION_LCONTAINER];
  14695. if (declarationContainer !== null && !isRoot) {
  14696. detachMovedView(declarationContainer, this._lView);
  14697. }
  14698. detachViewFromDOM(this._lView[TVIEW], this._lView);
  14699. }
  14700. attachToAppRef(appRef) {
  14701. if (this._attachedToViewContainer) {
  14702. throw new RuntimeError(902 /* RuntimeErrorCode.VIEW_ALREADY_ATTACHED */, ngDevMode && 'This view is already attached to a ViewContainer!');
  14703. }
  14704. this._appRef = appRef;
  14705. const isRoot = isRootView(this._lView);
  14706. const declarationContainer = this._lView[DECLARATION_LCONTAINER];
  14707. if (declarationContainer !== null && !isRoot) {
  14708. trackMovedView(declarationContainer, this._lView);
  14709. }
  14710. updateAncestorTraversalFlagsOnAttach(this._lView);
  14711. }
  14712. };
  14713. /**
  14714. * Reports whether the given view is considered dirty according to the different marking mechanisms.
  14715. */
  14716. function isViewDirty(view) {
  14717. return requiresRefreshOrTraversal(view._lView) || !!(view._lView[FLAGS] & 64 /* LViewFlags.Dirty */);
  14718. }
  14719. function markForRefresh(view) {
  14720. markViewForRefresh(view['_cdRefInjectingView'] || view._lView);
  14721. }
  14722. /**
  14723. * Represents an embedded template that can be used to instantiate embedded views.
  14724. * To instantiate embedded views based on a template, use the `ViewContainerRef`
  14725. * method `createEmbeddedView()`.
  14726. *
  14727. * Access a `TemplateRef` instance by placing a directive on an `<ng-template>`
  14728. * element (or directive prefixed with `*`). The `TemplateRef` for the embedded view
  14729. * is injected into the constructor of the directive,
  14730. * using the `TemplateRef` token.
  14731. *
  14732. * You can also use a `Query` to find a `TemplateRef` associated with
  14733. * a component or a directive.
  14734. *
  14735. * @see {@link ViewContainerRef}
  14736. *
  14737. * @publicApi
  14738. */
  14739. class TemplateRef {
  14740. /**
  14741. * @internal
  14742. * @nocollapse
  14743. */
  14744. static __NG_ELEMENT_ID__ = injectTemplateRef;
  14745. }
  14746. const ViewEngineTemplateRef = TemplateRef;
  14747. // TODO(alxhub): combine interface and implementation. Currently this is challenging since something
  14748. // in g3 depends on them being separate.
  14749. const R3TemplateRef = class TemplateRef extends ViewEngineTemplateRef {
  14750. _declarationLView;
  14751. _declarationTContainer;
  14752. elementRef;
  14753. constructor(_declarationLView, _declarationTContainer, elementRef) {
  14754. super();
  14755. this._declarationLView = _declarationLView;
  14756. this._declarationTContainer = _declarationTContainer;
  14757. this.elementRef = elementRef;
  14758. }
  14759. /**
  14760. * Returns an `ssrId` associated with a TView, which was used to
  14761. * create this instance of the `TemplateRef`.
  14762. *
  14763. * @internal
  14764. */
  14765. get ssrId() {
  14766. return this._declarationTContainer.tView?.ssrId || null;
  14767. }
  14768. createEmbeddedView(context, injector) {
  14769. return this.createEmbeddedViewImpl(context, injector);
  14770. }
  14771. /**
  14772. * @internal
  14773. */
  14774. createEmbeddedViewImpl(context, injector, dehydratedView) {
  14775. const embeddedLView = createAndRenderEmbeddedLView(this._declarationLView, this._declarationTContainer, context, { embeddedViewInjector: injector, dehydratedView });
  14776. return new ViewRef$1(embeddedLView);
  14777. }
  14778. };
  14779. /**
  14780. * Creates a TemplateRef given a node.
  14781. *
  14782. * @returns The TemplateRef instance to use
  14783. */
  14784. function injectTemplateRef() {
  14785. return createTemplateRef(getCurrentTNode(), getLView());
  14786. }
  14787. /**
  14788. * Creates a TemplateRef and stores it on the injector.
  14789. *
  14790. * @param hostTNode The node on which a TemplateRef is requested
  14791. * @param hostLView The `LView` to which the node belongs
  14792. * @returns The TemplateRef instance or null if we can't create a TemplateRef on a given node type
  14793. */
  14794. function createTemplateRef(hostTNode, hostLView) {
  14795. if (hostTNode.type & 4 /* TNodeType.Container */) {
  14796. ngDevMode && assertDefined(hostTNode.tView, 'TView must be allocated');
  14797. return new R3TemplateRef(hostLView, hostTNode, createElementRef(hostTNode, hostLView));
  14798. }
  14799. return null;
  14800. }
  14801. const AT_THIS_LOCATION = '<-- AT THIS LOCATION';
  14802. /**
  14803. * Retrieves a user friendly string for a given TNodeType for use in
  14804. * friendly error messages
  14805. *
  14806. * @param tNodeType
  14807. * @returns
  14808. */
  14809. function getFriendlyStringFromTNodeType(tNodeType) {
  14810. switch (tNodeType) {
  14811. case 4 /* TNodeType.Container */:
  14812. return 'view container';
  14813. case 2 /* TNodeType.Element */:
  14814. return 'element';
  14815. case 8 /* TNodeType.ElementContainer */:
  14816. return 'ng-container';
  14817. case 32 /* TNodeType.Icu */:
  14818. return 'icu';
  14819. case 64 /* TNodeType.Placeholder */:
  14820. return 'i18n';
  14821. case 16 /* TNodeType.Projection */:
  14822. return 'projection';
  14823. case 1 /* TNodeType.Text */:
  14824. return 'text';
  14825. case 128 /* TNodeType.LetDeclaration */:
  14826. return '@let';
  14827. default:
  14828. // This should not happen as we cover all possible TNode types above.
  14829. return '<unknown>';
  14830. }
  14831. }
  14832. /**
  14833. * Validates that provided nodes match during the hydration process.
  14834. */
  14835. function validateMatchingNode(node, nodeType, tagName, lView, tNode, isViewContainerAnchor = false) {
  14836. if (!node ||
  14837. node.nodeType !== nodeType ||
  14838. (node.nodeType === Node.ELEMENT_NODE &&
  14839. node.tagName.toLowerCase() !== tagName?.toLowerCase())) {
  14840. const expectedNode = shortRNodeDescription(nodeType, tagName, null);
  14841. let header = `During hydration Angular expected ${expectedNode} but `;
  14842. const hostComponentDef = getDeclarationComponentDef(lView);
  14843. const componentClassName = hostComponentDef?.type?.name;
  14844. const expectedDom = describeExpectedDom(lView, tNode, isViewContainerAnchor);
  14845. const expected = `Angular expected this DOM:\n\n${expectedDom}\n\n`;
  14846. let actual = '';
  14847. const componentHostElement = unwrapRNode(lView[HOST]);
  14848. if (!node) {
  14849. // No node found during hydration.
  14850. header += `the node was not found.\n\n`;
  14851. // Since the node is missing, we use the closest node to attach the error to
  14852. markRNodeAsHavingHydrationMismatch(componentHostElement, expectedDom);
  14853. }
  14854. else {
  14855. const actualNode = shortRNodeDescription(node.nodeType, node.tagName ?? null, node.textContent ?? null);
  14856. header += `found ${actualNode}.\n\n`;
  14857. const actualDom = describeDomFromNode(node);
  14858. actual = `Actual DOM is:\n\n${actualDom}\n\n`;
  14859. // DevTools only report hydration issues on the component level, so we attach extra debug
  14860. // info to a component host element to make it available to DevTools.
  14861. markRNodeAsHavingHydrationMismatch(componentHostElement, expectedDom, actualDom);
  14862. }
  14863. const footer = getHydrationErrorFooter(componentClassName);
  14864. const message = header + expected + actual + getHydrationAttributeNote() + footer;
  14865. throw new RuntimeError(-500 /* RuntimeErrorCode.HYDRATION_NODE_MISMATCH */, message);
  14866. }
  14867. }
  14868. /**
  14869. * Validates that a given node has sibling nodes
  14870. */
  14871. function validateSiblingNodeExists(node) {
  14872. validateNodeExists(node);
  14873. if (!node.nextSibling) {
  14874. const header = 'During hydration Angular expected more sibling nodes to be present.\n\n';
  14875. const actual = `Actual DOM is:\n\n${describeDomFromNode(node)}\n\n`;
  14876. const footer = getHydrationErrorFooter();
  14877. const message = header + actual + footer;
  14878. markRNodeAsHavingHydrationMismatch(node, '', actual);
  14879. throw new RuntimeError(-501 /* RuntimeErrorCode.HYDRATION_MISSING_SIBLINGS */, message);
  14880. }
  14881. }
  14882. /**
  14883. * Validates that a node exists or throws
  14884. */
  14885. function validateNodeExists(node, lView = null, tNode = null) {
  14886. if (!node) {
  14887. const header = 'During hydration, Angular expected an element to be present at this location.\n\n';
  14888. let expected = '';
  14889. let footer = '';
  14890. if (lView !== null && tNode !== null) {
  14891. expected = describeExpectedDom(lView, tNode, false);
  14892. footer = getHydrationErrorFooter();
  14893. // Since the node is missing, we use the closest node to attach the error to
  14894. markRNodeAsHavingHydrationMismatch(unwrapRNode(lView[HOST]), expected, '');
  14895. }
  14896. throw new RuntimeError(-502 /* RuntimeErrorCode.HYDRATION_MISSING_NODE */, `${header}${expected}\n\n${footer}`);
  14897. }
  14898. }
  14899. /**
  14900. * Builds the hydration error message when a node is not found
  14901. *
  14902. * @param lView the LView where the node exists
  14903. * @param tNode the TNode
  14904. */
  14905. function nodeNotFoundError(lView, tNode) {
  14906. const header = 'During serialization, Angular was unable to find an element in the DOM:\n\n';
  14907. const expected = `${describeExpectedDom(lView, tNode, false)}\n\n`;
  14908. const footer = getHydrationErrorFooter();
  14909. throw new RuntimeError(-502 /* RuntimeErrorCode.HYDRATION_MISSING_NODE */, header + expected + footer);
  14910. }
  14911. /**
  14912. * Builds a hydration error message when a node is not found at a path location
  14913. *
  14914. * @param host the Host Node
  14915. * @param path the path to the node
  14916. */
  14917. function nodeNotFoundAtPathError(host, path) {
  14918. const header = `During hydration Angular was unable to locate a node ` +
  14919. `using the "${path}" path, starting from the ${describeRNode(host)} node.\n\n`;
  14920. const footer = getHydrationErrorFooter();
  14921. markRNodeAsHavingHydrationMismatch(host);
  14922. throw new RuntimeError(-502 /* RuntimeErrorCode.HYDRATION_MISSING_NODE */, header + footer);
  14923. }
  14924. /**
  14925. * Builds the hydration error message in the case that dom nodes are created outside of
  14926. * the Angular context and are being used as projected nodes
  14927. *
  14928. * @param lView the LView
  14929. * @param tNode the TNode
  14930. * @returns an error
  14931. */
  14932. function unsupportedProjectionOfDomNodes(rNode) {
  14933. const header = 'During serialization, Angular detected DOM nodes ' +
  14934. 'that were created outside of Angular context and provided as projectable nodes ' +
  14935. '(likely via `ViewContainerRef.createComponent` or `createComponent` APIs). ' +
  14936. 'Hydration is not supported for such cases, consider refactoring the code to avoid ' +
  14937. 'this pattern or using `ngSkipHydration` on the host element of the component.\n\n';
  14938. const actual = `${describeDomFromNode(rNode)}\n\n`;
  14939. const message = header + actual + getHydrationAttributeNote();
  14940. return new RuntimeError(-503 /* RuntimeErrorCode.UNSUPPORTED_PROJECTION_DOM_NODES */, message);
  14941. }
  14942. /**
  14943. * Builds the hydration error message in the case that ngSkipHydration was used on a
  14944. * node that is not a component host element or host binding
  14945. *
  14946. * @param rNode the HTML Element
  14947. * @returns an error
  14948. */
  14949. function invalidSkipHydrationHost(rNode) {
  14950. const header = 'The `ngSkipHydration` flag is applied on a node ' +
  14951. "that doesn't act as a component host. Hydration can be " +
  14952. 'skipped only on per-component basis.\n\n';
  14953. const actual = `${describeDomFromNode(rNode)}\n\n`;
  14954. const footer = 'Please move the `ngSkipHydration` attribute to the component host element.\n\n';
  14955. const message = header + actual + footer;
  14956. return new RuntimeError(-504 /* RuntimeErrorCode.INVALID_SKIP_HYDRATION_HOST */, message);
  14957. }
  14958. // Stringification methods
  14959. /**
  14960. * Stringifies a given TNode's attributes
  14961. *
  14962. * @param tNode a provided TNode
  14963. * @returns string
  14964. */
  14965. function stringifyTNodeAttrs(tNode) {
  14966. const results = [];
  14967. if (tNode.attrs) {
  14968. for (let i = 0; i < tNode.attrs.length;) {
  14969. const attrName = tNode.attrs[i++];
  14970. // Once we reach the first flag, we know that the list of
  14971. // attributes is over.
  14972. if (typeof attrName == 'number') {
  14973. break;
  14974. }
  14975. const attrValue = tNode.attrs[i++];
  14976. results.push(`${attrName}="${shorten(attrValue)}"`);
  14977. }
  14978. }
  14979. return results.join(' ');
  14980. }
  14981. /**
  14982. * The list of internal attributes that should be filtered out while
  14983. * producing an error message.
  14984. */
  14985. const internalAttrs = new Set(['ngh', 'ng-version', 'ng-server-context']);
  14986. /**
  14987. * Stringifies an HTML Element's attributes
  14988. *
  14989. * @param rNode an HTML Element
  14990. * @returns string
  14991. */
  14992. function stringifyRNodeAttrs(rNode) {
  14993. const results = [];
  14994. for (let i = 0; i < rNode.attributes.length; i++) {
  14995. const attr = rNode.attributes[i];
  14996. if (internalAttrs.has(attr.name))
  14997. continue;
  14998. results.push(`${attr.name}="${shorten(attr.value)}"`);
  14999. }
  15000. return results.join(' ');
  15001. }
  15002. // Methods for Describing the DOM
  15003. /**
  15004. * Converts a tNode to a helpful readable string value for use in error messages
  15005. *
  15006. * @param tNode a given TNode
  15007. * @param innerContent the content of the node
  15008. * @returns string
  15009. */
  15010. function describeTNode(tNode, innerContent = '…') {
  15011. switch (tNode.type) {
  15012. case 1 /* TNodeType.Text */:
  15013. const content = tNode.value ? `(${tNode.value})` : '';
  15014. return `#text${content}`;
  15015. case 2 /* TNodeType.Element */:
  15016. const attrs = stringifyTNodeAttrs(tNode);
  15017. const tag = tNode.value.toLowerCase();
  15018. return `<${tag}${attrs ? ' ' + attrs : ''}>${innerContent}</${tag}>`;
  15019. case 8 /* TNodeType.ElementContainer */:
  15020. return '<!-- ng-container -->';
  15021. case 4 /* TNodeType.Container */:
  15022. return '<!-- container -->';
  15023. default:
  15024. const typeAsString = getFriendlyStringFromTNodeType(tNode.type);
  15025. return `#node(${typeAsString})`;
  15026. }
  15027. }
  15028. /**
  15029. * Converts an RNode to a helpful readable string value for use in error messages
  15030. *
  15031. * @param rNode a given RNode
  15032. * @param innerContent the content of the node
  15033. * @returns string
  15034. */
  15035. function describeRNode(rNode, innerContent = '…') {
  15036. const node = rNode;
  15037. switch (node.nodeType) {
  15038. case Node.ELEMENT_NODE:
  15039. const tag = node.tagName.toLowerCase();
  15040. const attrs = stringifyRNodeAttrs(node);
  15041. return `<${tag}${attrs ? ' ' + attrs : ''}>${innerContent}</${tag}>`;
  15042. case Node.TEXT_NODE:
  15043. const content = node.textContent ? shorten(node.textContent) : '';
  15044. return `#text${content ? `(${content})` : ''}`;
  15045. case Node.COMMENT_NODE:
  15046. return `<!-- ${shorten(node.textContent ?? '')} -->`;
  15047. default:
  15048. return `#node(${node.nodeType})`;
  15049. }
  15050. }
  15051. /**
  15052. * Builds the string containing the expected DOM present given the LView and TNode
  15053. * values for a readable error message
  15054. *
  15055. * @param lView the lView containing the DOM
  15056. * @param tNode the tNode
  15057. * @param isViewContainerAnchor boolean
  15058. * @returns string
  15059. */
  15060. function describeExpectedDom(lView, tNode, isViewContainerAnchor) {
  15061. const spacer = ' ';
  15062. let content = '';
  15063. if (tNode.prev) {
  15064. content += spacer + '…\n';
  15065. content += spacer + describeTNode(tNode.prev) + '\n';
  15066. }
  15067. else if (tNode.type && tNode.type & 12 /* TNodeType.AnyContainer */) {
  15068. content += spacer + '…\n';
  15069. }
  15070. if (isViewContainerAnchor) {
  15071. content += spacer + describeTNode(tNode) + '\n';
  15072. content += spacer + `<!-- container --> ${AT_THIS_LOCATION}\n`;
  15073. }
  15074. else {
  15075. content += spacer + describeTNode(tNode) + ` ${AT_THIS_LOCATION}\n`;
  15076. }
  15077. content += spacer + '…\n';
  15078. const parentRNode = tNode.type ? getParentRElement(lView[TVIEW], tNode, lView) : null;
  15079. if (parentRNode) {
  15080. content = describeRNode(parentRNode, '\n' + content);
  15081. }
  15082. return content;
  15083. }
  15084. /**
  15085. * Builds the string containing the DOM present around a given RNode for a
  15086. * readable error message
  15087. *
  15088. * @param node the RNode
  15089. * @returns string
  15090. */
  15091. function describeDomFromNode(node) {
  15092. const spacer = ' ';
  15093. let content = '';
  15094. const currentNode = node;
  15095. if (currentNode.previousSibling) {
  15096. content += spacer + '…\n';
  15097. content += spacer + describeRNode(currentNode.previousSibling) + '\n';
  15098. }
  15099. content += spacer + describeRNode(currentNode) + ` ${AT_THIS_LOCATION}\n`;
  15100. if (node.nextSibling) {
  15101. content += spacer + '…\n';
  15102. }
  15103. if (node.parentNode) {
  15104. content = describeRNode(currentNode.parentNode, '\n' + content);
  15105. }
  15106. return content;
  15107. }
  15108. /**
  15109. * Shortens the description of a given RNode by its type for readability
  15110. *
  15111. * @param nodeType the type of node
  15112. * @param tagName the node tag name
  15113. * @param textContent the text content in the node
  15114. * @returns string
  15115. */
  15116. function shortRNodeDescription(nodeType, tagName, textContent) {
  15117. switch (nodeType) {
  15118. case Node.ELEMENT_NODE:
  15119. return `<${tagName.toLowerCase()}>`;
  15120. case Node.TEXT_NODE:
  15121. const content = textContent ? ` (with the "${shorten(textContent)}" content)` : '';
  15122. return `a text node${content}`;
  15123. case Node.COMMENT_NODE:
  15124. return 'a comment node';
  15125. default:
  15126. return `#node(nodeType=${nodeType})`;
  15127. }
  15128. }
  15129. /**
  15130. * Builds the footer hydration error message
  15131. *
  15132. * @param componentClassName the name of the component class
  15133. * @returns string
  15134. */
  15135. function getHydrationErrorFooter(componentClassName) {
  15136. const componentInfo = componentClassName ? `the "${componentClassName}"` : 'corresponding';
  15137. return (`To fix this problem:\n` +
  15138. ` * check ${componentInfo} component for hydration-related issues\n` +
  15139. ` * check to see if your template has valid HTML structure\n` +
  15140. ` * or skip hydration by adding the \`ngSkipHydration\` attribute ` +
  15141. `to its host node in a template\n\n`);
  15142. }
  15143. /**
  15144. * An attribute related note for hydration errors
  15145. */
  15146. function getHydrationAttributeNote() {
  15147. return ('Note: attributes are only displayed to better represent the DOM' +
  15148. ' but have no effect on hydration mismatches.\n\n');
  15149. }
  15150. // Node string utility functions
  15151. /**
  15152. * Strips all newlines out of a given string
  15153. *
  15154. * @param input a string to be cleared of new line characters
  15155. * @returns
  15156. */
  15157. function stripNewlines(input) {
  15158. return input.replace(/\s+/gm, '');
  15159. }
  15160. /**
  15161. * Reduces a string down to a maximum length of characters with ellipsis for readability
  15162. *
  15163. * @param input a string input
  15164. * @param maxLength a maximum length in characters
  15165. * @returns string
  15166. */
  15167. function shorten(input, maxLength = 50) {
  15168. if (!input) {
  15169. return '';
  15170. }
  15171. input = stripNewlines(input);
  15172. return input.length > maxLength ? `${input.substring(0, maxLength - 1)}…` : input;
  15173. }
  15174. /**
  15175. * Find a node in front of which `currentTNode` should be inserted (takes i18n into account).
  15176. *
  15177. * This method determines the `RNode` in front of which we should insert the `currentRNode`. This
  15178. * takes `TNode.insertBeforeIndex` into account.
  15179. *
  15180. * @param parentTNode parent `TNode`
  15181. * @param currentTNode current `TNode` (The node which we would like to insert into the DOM)
  15182. * @param lView current `LView`
  15183. */
  15184. function getInsertInFrontOfRNodeWithI18n(parentTNode, currentTNode, lView) {
  15185. const tNodeInsertBeforeIndex = currentTNode.insertBeforeIndex;
  15186. const insertBeforeIndex = Array.isArray(tNodeInsertBeforeIndex)
  15187. ? tNodeInsertBeforeIndex[0]
  15188. : tNodeInsertBeforeIndex;
  15189. if (insertBeforeIndex === null) {
  15190. return getInsertInFrontOfRNodeWithNoI18n(parentTNode, currentTNode, lView);
  15191. }
  15192. else {
  15193. ngDevMode && assertIndexInRange(lView, insertBeforeIndex);
  15194. return unwrapRNode(lView[insertBeforeIndex]);
  15195. }
  15196. }
  15197. /**
  15198. * Process `TNode.insertBeforeIndex` by adding i18n text nodes.
  15199. *
  15200. * See `TNode.insertBeforeIndex`
  15201. */
  15202. function processI18nInsertBefore(renderer, childTNode, lView, childRNode, parentRElement) {
  15203. const tNodeInsertBeforeIndex = childTNode.insertBeforeIndex;
  15204. if (Array.isArray(tNodeInsertBeforeIndex)) {
  15205. // An array indicates that there are i18n nodes that need to be added as children of this
  15206. // `childRNode`. These i18n nodes were created before this `childRNode` was available and so
  15207. // only now can be added. The first element of the array is the normal index where we should
  15208. // insert the `childRNode`. Additional elements are the extra nodes to be added as children of
  15209. // `childRNode`.
  15210. ngDevMode && assertDomNode(childRNode);
  15211. let i18nParent = childRNode;
  15212. let anchorRNode = null;
  15213. if (!(childTNode.type & 3 /* TNodeType.AnyRNode */)) {
  15214. anchorRNode = i18nParent;
  15215. i18nParent = parentRElement;
  15216. }
  15217. if (i18nParent !== null && childTNode.componentOffset === -1) {
  15218. for (let i = 1; i < tNodeInsertBeforeIndex.length; i++) {
  15219. // No need to `unwrapRNode` because all of the indexes point to i18n text nodes.
  15220. // see `assertDomNode` below.
  15221. const i18nChild = lView[tNodeInsertBeforeIndex[i]];
  15222. nativeInsertBefore(renderer, i18nParent, i18nChild, anchorRNode, false);
  15223. }
  15224. }
  15225. }
  15226. }
  15227. function getOrCreateTNode(tView, index, type, name, attrs) {
  15228. ngDevMode &&
  15229. index !== 0 && // 0 are bogus nodes and they are OK. See `createContainerRef` in
  15230. // `view_engine_compatibility` for additional context.
  15231. assertGreaterThanOrEqual(index, HEADER_OFFSET, "TNodes can't be in the LView header.");
  15232. // Keep this function short, so that the VM will inline it.
  15233. ngDevMode && assertPureTNodeType(type);
  15234. let tNode = tView.data[index];
  15235. if (tNode === null) {
  15236. tNode = createTNodeAtIndex(tView, index, type, name, attrs);
  15237. if (isInI18nBlock()) {
  15238. // If we are in i18n block then all elements should be pre declared through `Placeholder`
  15239. // See `TNodeType.Placeholder` and `LFrame.inI18n` for more context.
  15240. // If the `TNode` was not pre-declared than it means it was not mentioned which means it was
  15241. // removed, so we mark it as detached.
  15242. tNode.flags |= 32 /* TNodeFlags.isDetached */;
  15243. }
  15244. }
  15245. else if (tNode.type & 64 /* TNodeType.Placeholder */) {
  15246. tNode.type = type;
  15247. tNode.value = name;
  15248. tNode.attrs = attrs;
  15249. const parent = getCurrentParentTNode();
  15250. tNode.injectorIndex = parent === null ? -1 : parent.injectorIndex;
  15251. ngDevMode && assertTNodeForTView(tNode, tView);
  15252. ngDevMode && assertEqual(index, tNode.index, 'Expecting same index');
  15253. }
  15254. setCurrentTNode(tNode, true);
  15255. return tNode;
  15256. }
  15257. function createTNodeAtIndex(tView, index, type, name, attrs) {
  15258. const currentTNode = getCurrentTNodePlaceholderOk();
  15259. const isParent = isCurrentTNodeParent();
  15260. const parent = isParent ? currentTNode : currentTNode && currentTNode.parent;
  15261. // Parents cannot cross component boundaries because components will be used in multiple places.
  15262. const tNode = (tView.data[index] = createTNode(tView, parent, type, index, name, attrs));
  15263. // Assign a pointer to the first child node of a given view. The first node is not always the one
  15264. // at index 0, in case of i18n, index 0 can be the instruction `i18nStart` and the first node has
  15265. // the index 1 or more, so we can't just check node index.
  15266. linkTNodeInTView(tView, tNode, currentTNode, isParent);
  15267. return tNode;
  15268. }
  15269. function linkTNodeInTView(tView, tNode, currentTNode, isParent) {
  15270. if (tView.firstChild === null) {
  15271. tView.firstChild = tNode;
  15272. }
  15273. if (currentTNode !== null) {
  15274. if (isParent) {
  15275. // FIXME(misko): This logic looks unnecessarily complicated. Could we simplify?
  15276. if (currentTNode.child == null && tNode.parent !== null) {
  15277. // We are in the same view, which means we are adding content node to the parent view.
  15278. currentTNode.child = tNode;
  15279. }
  15280. }
  15281. else {
  15282. if (currentTNode.next === null) {
  15283. // In the case of i18n the `currentTNode` may already be linked, in which case we don't want
  15284. // to break the links which i18n created.
  15285. currentTNode.next = tNode;
  15286. tNode.prev = currentTNode;
  15287. }
  15288. }
  15289. }
  15290. }
  15291. function createTNode(tView, tParent, type, index, value, attrs) {
  15292. ngDevMode &&
  15293. index !== 0 && // 0 are bogus nodes and they are OK. See `createContainerRef` in
  15294. // `view_engine_compatibility` for additional context.
  15295. assertGreaterThanOrEqual(index, HEADER_OFFSET, "TNodes can't be in the LView header.");
  15296. ngDevMode && assertNotSame(attrs, undefined, "'undefined' is not valid value for 'attrs'");
  15297. ngDevMode && ngDevMode.tNode++;
  15298. ngDevMode && tParent && assertTNodeForTView(tParent, tView);
  15299. let injectorIndex = tParent ? tParent.injectorIndex : -1;
  15300. let flags = 0;
  15301. if (isInSkipHydrationBlock$1()) {
  15302. flags |= 128 /* TNodeFlags.inSkipHydrationBlock */;
  15303. }
  15304. // TODO: would it be helpful to use a prototypal inheritance here, similar to the way we do so with signals?
  15305. const tNode = {
  15306. type,
  15307. index,
  15308. insertBeforeIndex: null,
  15309. injectorIndex,
  15310. directiveStart: -1,
  15311. directiveEnd: -1,
  15312. directiveStylingLast: -1,
  15313. componentOffset: -1,
  15314. propertyBindings: null,
  15315. flags,
  15316. providerIndexes: 0,
  15317. value: value,
  15318. attrs: attrs,
  15319. mergedAttrs: null,
  15320. localNames: null,
  15321. initialInputs: null,
  15322. inputs: null,
  15323. hostDirectiveInputs: null,
  15324. outputs: null,
  15325. hostDirectiveOutputs: null,
  15326. directiveToIndex: null,
  15327. tView: null,
  15328. next: null,
  15329. prev: null,
  15330. projectionNext: null,
  15331. child: null,
  15332. parent: tParent,
  15333. projection: null,
  15334. styles: null,
  15335. stylesWithoutHost: null,
  15336. residualStyles: undefined,
  15337. classes: null,
  15338. classesWithoutHost: null,
  15339. residualClasses: undefined,
  15340. classBindings: 0,
  15341. styleBindings: 0,
  15342. };
  15343. if (ngDevMode) {
  15344. // For performance reasons it is important that the tNode retains the same shape during runtime.
  15345. // (To make sure that all of the code is monomorphic.) For this reason we seal the object to
  15346. // prevent class transitions.
  15347. Object.seal(tNode);
  15348. }
  15349. return tNode;
  15350. }
  15351. /**
  15352. * Add `tNode` to `previousTNodes` list and update relevant `TNode`s in `previousTNodes` list
  15353. * `tNode.insertBeforeIndex`.
  15354. *
  15355. * Things to keep in mind:
  15356. * 1. All i18n text nodes are encoded as `TNodeType.Element` and are created eagerly by the
  15357. * `ɵɵi18nStart` instruction.
  15358. * 2. All `TNodeType.Placeholder` `TNodes` are elements which will be created later by
  15359. * `ɵɵelementStart` instruction.
  15360. * 3. `ɵɵelementStart` instruction will create `TNode`s in the ascending `TNode.index` order. (So a
  15361. * smaller index `TNode` is guaranteed to be created before a larger one)
  15362. *
  15363. * We use the above three invariants to determine `TNode.insertBeforeIndex`.
  15364. *
  15365. * In an ideal world `TNode.insertBeforeIndex` would always be `TNode.next.index`. However,
  15366. * this will not work because `TNode.next.index` may be larger than `TNode.index` which means that
  15367. * the next node is not yet created and therefore we can't insert in front of it.
  15368. *
  15369. * Rule1: `TNode.insertBeforeIndex = null` if `TNode.next === null` (Initial condition, as we don't
  15370. * know if there will be further `TNode`s inserted after.)
  15371. * Rule2: If `previousTNode` is created after the `tNode` being inserted, then
  15372. * `previousTNode.insertBeforeNode = tNode.index` (So when a new `tNode` is added we check
  15373. * previous to see if we can update its `insertBeforeTNode`)
  15374. *
  15375. * See `TNode.insertBeforeIndex` for more context.
  15376. *
  15377. * @param previousTNodes A list of previous TNodes so that we can easily traverse `TNode`s in
  15378. * reverse order. (If `TNode` would have `previous` this would not be necessary.)
  15379. * @param newTNode A TNode to add to the `previousTNodes` list.
  15380. */
  15381. function addTNodeAndUpdateInsertBeforeIndex(previousTNodes, newTNode) {
  15382. // Start with Rule1
  15383. ngDevMode &&
  15384. assertEqual(newTNode.insertBeforeIndex, null, 'We expect that insertBeforeIndex is not set');
  15385. previousTNodes.push(newTNode);
  15386. if (previousTNodes.length > 1) {
  15387. for (let i = previousTNodes.length - 2; i >= 0; i--) {
  15388. const existingTNode = previousTNodes[i];
  15389. // Text nodes are created eagerly and so they don't need their `indexBeforeIndex` updated.
  15390. // It is safe to ignore them.
  15391. if (!isI18nText(existingTNode)) {
  15392. if (isNewTNodeCreatedBefore(existingTNode, newTNode) &&
  15393. getInsertBeforeIndex(existingTNode) === null) {
  15394. // If it was created before us in time, (and it does not yet have `insertBeforeIndex`)
  15395. // then add the `insertBeforeIndex`.
  15396. setInsertBeforeIndex(existingTNode, newTNode.index);
  15397. }
  15398. }
  15399. }
  15400. }
  15401. }
  15402. function isI18nText(tNode) {
  15403. return !(tNode.type & 64 /* TNodeType.Placeholder */);
  15404. }
  15405. function isNewTNodeCreatedBefore(existingTNode, newTNode) {
  15406. return isI18nText(newTNode) || existingTNode.index > newTNode.index;
  15407. }
  15408. function getInsertBeforeIndex(tNode) {
  15409. const index = tNode.insertBeforeIndex;
  15410. return Array.isArray(index) ? index[0] : index;
  15411. }
  15412. function setInsertBeforeIndex(tNode, value) {
  15413. const index = tNode.insertBeforeIndex;
  15414. if (Array.isArray(index)) {
  15415. // Array is stored if we have to insert child nodes. See `TNode.insertBeforeIndex`
  15416. index[0] = value;
  15417. }
  15418. else {
  15419. setI18nHandling(getInsertInFrontOfRNodeWithI18n, processI18nInsertBefore);
  15420. tNode.insertBeforeIndex = value;
  15421. }
  15422. }
  15423. /**
  15424. * Retrieve `TIcu` at a given `index`.
  15425. *
  15426. * The `TIcu` can be stored either directly (if it is nested ICU) OR
  15427. * it is stored inside tho `TIcuContainer` if it is top level ICU.
  15428. *
  15429. * The reason for this is that the top level ICU need a `TNode` so that they are part of the render
  15430. * tree, but nested ICU's have no TNode, because we don't know ahead of time if the nested ICU is
  15431. * expressed (parent ICU may have selected a case which does not contain it.)
  15432. *
  15433. * @param tView Current `TView`.
  15434. * @param index Index where the value should be read from.
  15435. */
  15436. function getTIcu(tView, index) {
  15437. const value = tView.data[index];
  15438. if (value === null || typeof value === 'string')
  15439. return null;
  15440. if (ngDevMode &&
  15441. !(value.hasOwnProperty('tView') || value.hasOwnProperty('currentCaseLViewIndex'))) {
  15442. throwError("We expect to get 'null'|'TIcu'|'TIcuContainer', but got: " + value);
  15443. }
  15444. // Here the `value.hasOwnProperty('currentCaseLViewIndex')` is a polymorphic read as it can be
  15445. // either TIcu or TIcuContainerNode. This is not ideal, but we still think it is OK because it
  15446. // will be just two cases which fits into the browser inline cache (inline cache can take up to
  15447. // 4)
  15448. const tIcu = value.hasOwnProperty('currentCaseLViewIndex')
  15449. ? value
  15450. : value.value;
  15451. ngDevMode && assertTIcu(tIcu);
  15452. return tIcu;
  15453. }
  15454. /**
  15455. * Store `TIcu` at a give `index`.
  15456. *
  15457. * The `TIcu` can be stored either directly (if it is nested ICU) OR
  15458. * it is stored inside tho `TIcuContainer` if it is top level ICU.
  15459. *
  15460. * The reason for this is that the top level ICU need a `TNode` so that they are part of the render
  15461. * tree, but nested ICU's have no TNode, because we don't know ahead of time if the nested ICU is
  15462. * expressed (parent ICU may have selected a case which does not contain it.)
  15463. *
  15464. * @param tView Current `TView`.
  15465. * @param index Index where the value should be stored at in `Tview.data`
  15466. * @param tIcu The TIcu to store.
  15467. */
  15468. function setTIcu(tView, index, tIcu) {
  15469. const tNode = tView.data[index];
  15470. ngDevMode &&
  15471. assertEqual(tNode === null || tNode.hasOwnProperty('tView'), true, "We expect to get 'null'|'TIcuContainer'");
  15472. if (tNode === null) {
  15473. tView.data[index] = tIcu;
  15474. }
  15475. else {
  15476. ngDevMode && assertTNodeType(tNode, 32 /* TNodeType.Icu */);
  15477. tNode.value = tIcu;
  15478. }
  15479. }
  15480. /**
  15481. * Set `TNode.insertBeforeIndex` taking the `Array` into account.
  15482. *
  15483. * See `TNode.insertBeforeIndex`
  15484. */
  15485. function setTNodeInsertBeforeIndex(tNode, index) {
  15486. ngDevMode && assertTNode(tNode);
  15487. let insertBeforeIndex = tNode.insertBeforeIndex;
  15488. if (insertBeforeIndex === null) {
  15489. setI18nHandling(getInsertInFrontOfRNodeWithI18n, processI18nInsertBefore);
  15490. insertBeforeIndex = tNode.insertBeforeIndex = [
  15491. null /* may be updated to number later */,
  15492. index,
  15493. ];
  15494. }
  15495. else {
  15496. assertEqual(Array.isArray(insertBeforeIndex), true, 'Expecting array here');
  15497. insertBeforeIndex.push(index);
  15498. }
  15499. }
  15500. /**
  15501. * Create `TNode.type=TNodeType.Placeholder` node.
  15502. *
  15503. * See `TNodeType.Placeholder` for more information.
  15504. */
  15505. function createTNodePlaceholder(tView, previousTNodes, index) {
  15506. const tNode = createTNodeAtIndex(tView, index, 64 /* TNodeType.Placeholder */, null, null);
  15507. addTNodeAndUpdateInsertBeforeIndex(previousTNodes, tNode);
  15508. return tNode;
  15509. }
  15510. /**
  15511. * Returns current ICU case.
  15512. *
  15513. * ICU cases are stored as index into the `TIcu.cases`.
  15514. * At times it is necessary to communicate that the ICU case just switched and that next ICU update
  15515. * should update all bindings regardless of the mask. In such a case the we store negative numbers
  15516. * for cases which have just been switched. This function removes the negative flag.
  15517. */
  15518. function getCurrentICUCaseIndex(tIcu, lView) {
  15519. const currentCase = lView[tIcu.currentCaseLViewIndex];
  15520. return currentCase === null ? currentCase : currentCase < 0 ? ~currentCase : currentCase;
  15521. }
  15522. function getParentFromIcuCreateOpCode(mergedCode) {
  15523. return mergedCode >>> 17 /* IcuCreateOpCode.SHIFT_PARENT */;
  15524. }
  15525. function getRefFromIcuCreateOpCode(mergedCode) {
  15526. return (mergedCode & 131070 /* IcuCreateOpCode.MASK_REF */) >>> 1 /* IcuCreateOpCode.SHIFT_REF */;
  15527. }
  15528. function getInstructionFromIcuCreateOpCode(mergedCode) {
  15529. return mergedCode & 1 /* IcuCreateOpCode.MASK_INSTRUCTION */;
  15530. }
  15531. function icuCreateOpCode(opCode, parentIdx, refIdx) {
  15532. ngDevMode && assertGreaterThanOrEqual(parentIdx, 0, 'Missing parent index');
  15533. ngDevMode && assertGreaterThan(refIdx, 0, 'Missing ref index');
  15534. return (opCode | (parentIdx << 17 /* IcuCreateOpCode.SHIFT_PARENT */) | (refIdx << 1 /* IcuCreateOpCode.SHIFT_REF */));
  15535. }
  15536. // Returns whether the given value corresponds to a root template message,
  15537. // or a sub-template.
  15538. function isRootTemplateMessage(subTemplateIndex) {
  15539. return subTemplateIndex === -1;
  15540. }
  15541. function enterIcu(state, tIcu, lView) {
  15542. state.index = 0;
  15543. const currentCase = getCurrentICUCaseIndex(tIcu, lView);
  15544. if (currentCase !== null) {
  15545. ngDevMode && assertNumberInRange(currentCase, 0, tIcu.cases.length - 1);
  15546. state.removes = tIcu.remove[currentCase];
  15547. }
  15548. else {
  15549. state.removes = EMPTY_ARRAY;
  15550. }
  15551. }
  15552. function icuContainerIteratorNext(state) {
  15553. if (state.index < state.removes.length) {
  15554. const removeOpCode = state.removes[state.index++];
  15555. ngDevMode && assertNumber(removeOpCode, 'Expecting OpCode number');
  15556. if (removeOpCode > 0) {
  15557. const rNode = state.lView[removeOpCode];
  15558. ngDevMode && assertDomNode(rNode);
  15559. return rNode;
  15560. }
  15561. else {
  15562. state.stack.push(state.index, state.removes);
  15563. // ICUs are represented by negative indices
  15564. const tIcuIndex = ~removeOpCode;
  15565. const tIcu = state.lView[TVIEW].data[tIcuIndex];
  15566. ngDevMode && assertTIcu(tIcu);
  15567. enterIcu(state, tIcu, state.lView);
  15568. return icuContainerIteratorNext(state);
  15569. }
  15570. }
  15571. else {
  15572. if (state.stack.length === 0) {
  15573. return null;
  15574. }
  15575. else {
  15576. state.removes = state.stack.pop();
  15577. state.index = state.stack.pop();
  15578. return icuContainerIteratorNext(state);
  15579. }
  15580. }
  15581. }
  15582. function loadIcuContainerVisitor() {
  15583. const _state = {
  15584. stack: [],
  15585. index: -1,
  15586. };
  15587. /**
  15588. * Retrieves a set of root nodes from `TIcu.remove`. Used by `TNodeType.ICUContainer`
  15589. * to determine which root belong to the ICU.
  15590. *
  15591. * Example of usage.
  15592. * ```ts
  15593. * const nextRNode = icuContainerIteratorStart(tIcuContainerNode, lView);
  15594. * let rNode: RNode|null;
  15595. * while(rNode = nextRNode()) {
  15596. * console.log(rNode);
  15597. * }
  15598. * ```
  15599. *
  15600. * @param tIcuContainerNode Current `TIcuContainerNode`
  15601. * @param lView `LView` where the `RNode`s should be looked up.
  15602. */
  15603. function icuContainerIteratorStart(tIcuContainerNode, lView) {
  15604. _state.lView = lView;
  15605. while (_state.stack.length)
  15606. _state.stack.pop();
  15607. ngDevMode && assertTNodeForLView(tIcuContainerNode, lView);
  15608. enterIcu(_state, tIcuContainerNode.value, lView);
  15609. return icuContainerIteratorNext.bind(null, _state);
  15610. }
  15611. return icuContainerIteratorStart;
  15612. }
  15613. function createIcuIterator(tIcu, lView) {
  15614. const state = {
  15615. stack: [],
  15616. index: -1,
  15617. lView,
  15618. };
  15619. ngDevMode && assertTIcu(tIcu);
  15620. enterIcu(state, tIcu, lView);
  15621. return icuContainerIteratorNext.bind(null, state);
  15622. }
  15623. /**
  15624. * Regexp that extracts a reference node information from the compressed node location.
  15625. * The reference node is represented as either:
  15626. * - a number which points to an LView slot
  15627. * - the `b` char which indicates that the lookup should start from the `document.body`
  15628. * - the `h` char to start lookup from the component host node (`lView[HOST]`)
  15629. */
  15630. const REF_EXTRACTOR_REGEXP = /* @__PURE__ */ new RegExp(`^(\\d+)*(${REFERENCE_NODE_BODY}|${REFERENCE_NODE_HOST})*(.*)`);
  15631. /**
  15632. * Helper function that takes a reference node location and a set of navigation steps
  15633. * (from the reference node) to a target node and outputs a string that represents
  15634. * a location.
  15635. *
  15636. * For example, given: referenceNode = 'b' (body) and path = ['firstChild', 'firstChild',
  15637. * 'nextSibling'], the function returns: `bf2n`.
  15638. */
  15639. function compressNodeLocation(referenceNode, path) {
  15640. const result = [referenceNode];
  15641. for (const segment of path) {
  15642. const lastIdx = result.length - 1;
  15643. if (lastIdx > 0 && result[lastIdx - 1] === segment) {
  15644. // An empty string in a count slot represents 1 occurrence of an instruction.
  15645. const value = (result[lastIdx] || 1);
  15646. result[lastIdx] = value + 1;
  15647. }
  15648. else {
  15649. // Adding a new segment to the path.
  15650. // Using an empty string in a counter field to avoid encoding `1`s
  15651. // into the path, since they are implicit (e.g. `f1n1` vs `fn`), so
  15652. // it's enough to have a single char in this case.
  15653. result.push(segment, '');
  15654. }
  15655. }
  15656. return result.join('');
  15657. }
  15658. /**
  15659. * Helper function that reverts the `compressNodeLocation` and transforms a given
  15660. * string into an array where at 0th position there is a reference node info and
  15661. * after that it contains information (in pairs) about a navigation step and the
  15662. * number of repetitions.
  15663. *
  15664. * For example, the path like 'bf2n' will be transformed to:
  15665. * ['b', 'firstChild', 2, 'nextSibling', 1].
  15666. *
  15667. * This information is later consumed by the code that navigates the DOM to find
  15668. * a given node by its location.
  15669. */
  15670. function decompressNodeLocation(path) {
  15671. const matches = path.match(REF_EXTRACTOR_REGEXP);
  15672. const [_, refNodeId, refNodeName, rest] = matches;
  15673. // If a reference node is represented by an index, transform it to a number.
  15674. const ref = refNodeId ? parseInt(refNodeId, 10) : refNodeName;
  15675. const steps = [];
  15676. // Match all segments in a path.
  15677. for (const [_, step, count] of rest.matchAll(/(f|n)(\d*)/g)) {
  15678. const repeat = parseInt(count, 10) || 1;
  15679. steps.push(step, repeat);
  15680. }
  15681. return [ref, ...steps];
  15682. }
  15683. /** Whether current TNode is a first node in an <ng-container>. */
  15684. function isFirstElementInNgContainer(tNode) {
  15685. return !tNode.prev && tNode.parent?.type === 8 /* TNodeType.ElementContainer */;
  15686. }
  15687. /** Returns an instruction index (subtracting HEADER_OFFSET). */
  15688. function getNoOffsetIndex(tNode) {
  15689. return tNode.index - HEADER_OFFSET;
  15690. }
  15691. /**
  15692. * Check whether a given node exists, but is disconnected from the DOM.
  15693. */
  15694. function isDisconnectedNode(tNode, lView) {
  15695. return (!(tNode.type & (16 /* TNodeType.Projection */ | 128 /* TNodeType.LetDeclaration */)) &&
  15696. !!lView[tNode.index] &&
  15697. isDisconnectedRNode(unwrapRNode(lView[tNode.index])));
  15698. }
  15699. /**
  15700. * Check whether the given node exists, but is disconnected from the DOM.
  15701. *
  15702. * Note: we leverage the fact that we have this information available in the DOM emulation
  15703. * layer (in Domino) for now. Longer-term solution should not rely on the DOM emulation and
  15704. * only use internal data structures and state to compute this information.
  15705. */
  15706. function isDisconnectedRNode(rNode) {
  15707. return !!rNode && !rNode.isConnected;
  15708. }
  15709. /**
  15710. * Locate a node in an i18n tree that corresponds to a given instruction index.
  15711. *
  15712. * @param hydrationInfo The hydration annotation data
  15713. * @param noOffsetIndex the instruction index
  15714. * @returns an RNode that corresponds to the instruction index
  15715. */
  15716. function locateI18nRNodeByIndex(hydrationInfo, noOffsetIndex) {
  15717. const i18nNodes = hydrationInfo.i18nNodes;
  15718. if (i18nNodes) {
  15719. return i18nNodes.get(noOffsetIndex);
  15720. }
  15721. return undefined;
  15722. }
  15723. /**
  15724. * Attempt to locate an RNode by a path, if it exists.
  15725. *
  15726. * @param hydrationInfo The hydration annotation data
  15727. * @param lView the current lView
  15728. * @param noOffsetIndex the instruction index
  15729. * @returns an RNode that corresponds to the instruction index or null if no path exists
  15730. */
  15731. function tryLocateRNodeByPath(hydrationInfo, lView, noOffsetIndex) {
  15732. const nodes = hydrationInfo.data[NODES];
  15733. const path = nodes?.[noOffsetIndex];
  15734. return path ? locateRNodeByPath(path, lView) : null;
  15735. }
  15736. /**
  15737. * Locate a node in DOM tree that corresponds to a given TNode.
  15738. *
  15739. * @param hydrationInfo The hydration annotation data
  15740. * @param tView the current tView
  15741. * @param lView the current lView
  15742. * @param tNode the current tNode
  15743. * @returns an RNode that represents a given tNode
  15744. */
  15745. function locateNextRNode(hydrationInfo, tView, lView, tNode) {
  15746. const noOffsetIndex = getNoOffsetIndex(tNode);
  15747. let native = locateI18nRNodeByIndex(hydrationInfo, noOffsetIndex);
  15748. if (native === undefined) {
  15749. const nodes = hydrationInfo.data[NODES];
  15750. if (nodes?.[noOffsetIndex]) {
  15751. // We know the exact location of the node.
  15752. native = locateRNodeByPath(nodes[noOffsetIndex], lView);
  15753. }
  15754. else if (tView.firstChild === tNode) {
  15755. // We create a first node in this view, so we use a reference
  15756. // to the first child in this DOM segment.
  15757. native = hydrationInfo.firstChild;
  15758. }
  15759. else {
  15760. // Locate a node based on a previous sibling or a parent node.
  15761. const previousTNodeParent = tNode.prev === null;
  15762. const previousTNode = (tNode.prev ?? tNode.parent);
  15763. ngDevMode &&
  15764. assertDefined(previousTNode, 'Unexpected state: current TNode does not have a connection ' +
  15765. 'to the previous node or a parent node.');
  15766. if (isFirstElementInNgContainer(tNode)) {
  15767. const noOffsetParentIndex = getNoOffsetIndex(tNode.parent);
  15768. native = getSegmentHead(hydrationInfo, noOffsetParentIndex);
  15769. }
  15770. else {
  15771. let previousRElement = getNativeByTNode(previousTNode, lView);
  15772. if (previousTNodeParent) {
  15773. native = previousRElement.firstChild;
  15774. }
  15775. else {
  15776. // If the previous node is an element, but it also has container info,
  15777. // this means that we are processing a node like `<div #vcrTarget>`, which is
  15778. // represented in the DOM as `<div></div>...<!--container-->`.
  15779. // In this case, there are nodes *after* this element and we need to skip
  15780. // all of them to reach an element that we are looking for.
  15781. const noOffsetPrevSiblingIndex = getNoOffsetIndex(previousTNode);
  15782. const segmentHead = getSegmentHead(hydrationInfo, noOffsetPrevSiblingIndex);
  15783. if (previousTNode.type === 2 /* TNodeType.Element */ && segmentHead) {
  15784. const numRootNodesToSkip = calcSerializedContainerSize(hydrationInfo, noOffsetPrevSiblingIndex);
  15785. // `+1` stands for an anchor comment node after all the views in this container.
  15786. const nodesToSkip = numRootNodesToSkip + 1;
  15787. // First node after this segment.
  15788. native = siblingAfter(nodesToSkip, segmentHead);
  15789. }
  15790. else {
  15791. native = previousRElement.nextSibling;
  15792. }
  15793. }
  15794. }
  15795. }
  15796. }
  15797. return native;
  15798. }
  15799. /**
  15800. * Skips over a specified number of nodes and returns the next sibling node after that.
  15801. */
  15802. function siblingAfter(skip, from) {
  15803. let currentNode = from;
  15804. for (let i = 0; i < skip; i++) {
  15805. ngDevMode && validateSiblingNodeExists(currentNode);
  15806. currentNode = currentNode.nextSibling;
  15807. }
  15808. return currentNode;
  15809. }
  15810. /**
  15811. * Helper function to produce a string representation of the navigation steps
  15812. * (in terms of `nextSibling` and `firstChild` navigations). Used in error
  15813. * messages in dev mode.
  15814. */
  15815. function stringifyNavigationInstructions(instructions) {
  15816. const container = [];
  15817. for (let i = 0; i < instructions.length; i += 2) {
  15818. const step = instructions[i];
  15819. const repeat = instructions[i + 1];
  15820. for (let r = 0; r < repeat; r++) {
  15821. container.push(step === NODE_NAVIGATION_STEP_FIRST_CHILD ? 'firstChild' : 'nextSibling');
  15822. }
  15823. }
  15824. return container.join('.');
  15825. }
  15826. /**
  15827. * Helper function that navigates from a starting point node (the `from` node)
  15828. * using provided set of navigation instructions (within `path` argument).
  15829. */
  15830. function navigateToNode(from, instructions) {
  15831. let node = from;
  15832. for (let i = 0; i < instructions.length; i += 2) {
  15833. const step = instructions[i];
  15834. const repeat = instructions[i + 1];
  15835. for (let r = 0; r < repeat; r++) {
  15836. if (ngDevMode && !node) {
  15837. throw nodeNotFoundAtPathError(from, stringifyNavigationInstructions(instructions));
  15838. }
  15839. switch (step) {
  15840. case NODE_NAVIGATION_STEP_FIRST_CHILD:
  15841. node = node.firstChild;
  15842. break;
  15843. case NODE_NAVIGATION_STEP_NEXT_SIBLING:
  15844. node = node.nextSibling;
  15845. break;
  15846. }
  15847. }
  15848. }
  15849. if (ngDevMode && !node) {
  15850. throw nodeNotFoundAtPathError(from, stringifyNavigationInstructions(instructions));
  15851. }
  15852. return node;
  15853. }
  15854. /**
  15855. * Locates an RNode given a set of navigation instructions (which also contains
  15856. * a starting point node info).
  15857. */
  15858. function locateRNodeByPath(path, lView) {
  15859. const [referenceNode, ...navigationInstructions] = decompressNodeLocation(path);
  15860. let ref;
  15861. if (referenceNode === REFERENCE_NODE_HOST) {
  15862. ref = lView[DECLARATION_COMPONENT_VIEW][HOST];
  15863. }
  15864. else if (referenceNode === REFERENCE_NODE_BODY) {
  15865. ref = ɵɵresolveBody(lView[DECLARATION_COMPONENT_VIEW][HOST]);
  15866. }
  15867. else {
  15868. const parentElementId = Number(referenceNode);
  15869. ref = unwrapRNode(lView[parentElementId + HEADER_OFFSET]);
  15870. }
  15871. return navigateToNode(ref, navigationInstructions);
  15872. }
  15873. /**
  15874. * Generate a list of DOM navigation operations to get from node `start` to node `finish`.
  15875. *
  15876. * Note: assumes that node `start` occurs before node `finish` in an in-order traversal of the DOM
  15877. * tree. That is, we should be able to get from `start` to `finish` purely by using `.firstChild`
  15878. * and `.nextSibling` operations.
  15879. */
  15880. function navigateBetween(start, finish) {
  15881. if (start === finish) {
  15882. return [];
  15883. }
  15884. else if (start.parentElement == null || finish.parentElement == null) {
  15885. return null;
  15886. }
  15887. else if (start.parentElement === finish.parentElement) {
  15888. return navigateBetweenSiblings(start, finish);
  15889. }
  15890. else {
  15891. // `finish` is a child of its parent, so the parent will always have a child.
  15892. const parent = finish.parentElement;
  15893. const parentPath = navigateBetween(start, parent);
  15894. const childPath = navigateBetween(parent.firstChild, finish);
  15895. if (!parentPath || !childPath)
  15896. return null;
  15897. return [
  15898. // First navigate to `finish`'s parent
  15899. ...parentPath,
  15900. // Then to its first child.
  15901. NODE_NAVIGATION_STEP_FIRST_CHILD,
  15902. // And finally from that node to `finish` (maybe a no-op if we're already there).
  15903. ...childPath,
  15904. ];
  15905. }
  15906. }
  15907. /**
  15908. * Calculates a path between 2 sibling nodes (generates a number of `NextSibling` navigations).
  15909. * Returns `null` if no such path exists between the given nodes.
  15910. */
  15911. function navigateBetweenSiblings(start, finish) {
  15912. const nav = [];
  15913. let node = null;
  15914. for (node = start; node != null && node !== finish; node = node.nextSibling) {
  15915. nav.push(NODE_NAVIGATION_STEP_NEXT_SIBLING);
  15916. }
  15917. // If the `node` becomes `null` or `undefined` at the end, that means that we
  15918. // didn't find the `end` node, thus return `null` (which would trigger serialization
  15919. // error to be produced).
  15920. return node == null ? null : nav;
  15921. }
  15922. /**
  15923. * Calculates a path between 2 nodes in terms of `nextSibling` and `firstChild`
  15924. * navigations:
  15925. * - the `from` node is a known node, used as an starting point for the lookup
  15926. * (the `fromNodeName` argument is a string representation of the node).
  15927. * - the `to` node is a node that the runtime logic would be looking up,
  15928. * using the path generated by this function.
  15929. */
  15930. function calcPathBetween(from, to, fromNodeName) {
  15931. const path = navigateBetween(from, to);
  15932. return path === null ? null : compressNodeLocation(fromNodeName, path);
  15933. }
  15934. /**
  15935. * Invoked at serialization time (on the server) when a set of navigation
  15936. * instructions needs to be generated for a TNode.
  15937. */
  15938. function calcPathForNode(tNode, lView, excludedParentNodes) {
  15939. let parentTNode = tNode.parent;
  15940. let parentIndex;
  15941. let parentRNode;
  15942. let referenceNodeName;
  15943. // Skip over all parent nodes that are disconnected from the DOM, such nodes
  15944. // can not be used as anchors.
  15945. //
  15946. // This might happen in certain content projection-based use-cases, where
  15947. // a content of an element is projected and used, when a parent element
  15948. // itself remains detached from DOM. In this scenario we try to find a parent
  15949. // element that is attached to DOM and can act as an anchor instead.
  15950. //
  15951. // It can also happen that the parent node should be excluded, for example,
  15952. // because it belongs to an i18n block, which requires paths which aren't
  15953. // relative to other views in an i18n block.
  15954. while (parentTNode !== null &&
  15955. (isDisconnectedNode(parentTNode, lView) || excludedParentNodes?.has(parentTNode.index))) {
  15956. parentTNode = parentTNode.parent;
  15957. }
  15958. if (parentTNode === null || !(parentTNode.type & 3 /* TNodeType.AnyRNode */)) {
  15959. // If there is no parent TNode or a parent TNode does not represent an RNode
  15960. // (i.e. not a DOM node), use component host element as a reference node.
  15961. parentIndex = referenceNodeName = REFERENCE_NODE_HOST;
  15962. parentRNode = lView[DECLARATION_COMPONENT_VIEW][HOST];
  15963. }
  15964. else {
  15965. // Use parent TNode as a reference node.
  15966. parentIndex = parentTNode.index;
  15967. parentRNode = unwrapRNode(lView[parentIndex]);
  15968. referenceNodeName = renderStringify(parentIndex - HEADER_OFFSET);
  15969. }
  15970. let rNode = unwrapRNode(lView[tNode.index]);
  15971. if (tNode.type & (12 /* TNodeType.AnyContainer */ | 32 /* TNodeType.Icu */)) {
  15972. // For <ng-container> nodes, instead of serializing a reference
  15973. // to the anchor comment node, serialize a location of the first
  15974. // DOM element. Paired with the container size (serialized as a part
  15975. // of `ngh.containers`), it should give enough information for runtime
  15976. // to hydrate nodes in this container.
  15977. const firstRNode = getFirstNativeNode(lView, tNode);
  15978. // If container is not empty, use a reference to the first element,
  15979. // otherwise, rNode would point to an anchor comment node.
  15980. if (firstRNode) {
  15981. rNode = firstRNode;
  15982. }
  15983. }
  15984. let path = calcPathBetween(parentRNode, rNode, referenceNodeName);
  15985. if (path === null && parentRNode !== rNode) {
  15986. // Searching for a path between elements within a host node failed.
  15987. // Trying to find a path to an element starting from the `document.body` instead.
  15988. //
  15989. // Important note: this type of reference is relatively unstable, since Angular
  15990. // may not be able to control parts of the page that the runtime logic navigates
  15991. // through. This is mostly needed to cover "portals" use-case (like menus, dialog boxes,
  15992. // etc), where nodes are content-projected (including direct DOM manipulations) outside
  15993. // of the host node. The better solution is to provide APIs to work with "portals",
  15994. // at which point this code path would not be needed.
  15995. const body = parentRNode.ownerDocument.body;
  15996. path = calcPathBetween(body, rNode, REFERENCE_NODE_BODY);
  15997. if (path === null) {
  15998. // If the path is still empty, it's likely that this node is detached and
  15999. // won't be found during hydration.
  16000. throw nodeNotFoundError(lView, tNode);
  16001. }
  16002. }
  16003. return path;
  16004. }
  16005. /**
  16006. * Retrieves all comments nodes that contain ngh comments referring to a defer block
  16007. */
  16008. function gatherDeferBlocksCommentNodes(doc, node) {
  16009. const commentNodesIterator = doc.createNodeIterator(node, NodeFilter.SHOW_COMMENT, { acceptNode });
  16010. let currentNode;
  16011. const nodesByBlockId = new Map();
  16012. while ((currentNode = commentNodesIterator.nextNode())) {
  16013. const nghPattern = 'ngh=';
  16014. const content = currentNode?.textContent;
  16015. const nghIdx = content?.indexOf(nghPattern) ?? -1;
  16016. if (nghIdx > -1) {
  16017. const nghValue = content.substring(nghIdx + nghPattern.length).trim();
  16018. // Make sure the value has an expected format.
  16019. ngDevMode &&
  16020. assertEqual(nghValue.startsWith('d'), true, 'Invalid defer block id found in a comment node.');
  16021. nodesByBlockId.set(nghValue, currentNode);
  16022. }
  16023. }
  16024. return nodesByBlockId;
  16025. }
  16026. function acceptNode(node) {
  16027. return node.textContent?.trimStart().startsWith('ngh=')
  16028. ? NodeFilter.FILTER_ACCEPT
  16029. : NodeFilter.FILTER_REJECT;
  16030. }
  16031. let _isI18nHydrationSupportEnabled = false;
  16032. let _prepareI18nBlockForHydrationImpl = () => {
  16033. // noop unless `enablePrepareI18nBlockForHydrationImpl` is invoked.
  16034. };
  16035. function setIsI18nHydrationSupportEnabled(enabled) {
  16036. _isI18nHydrationSupportEnabled = enabled;
  16037. }
  16038. function isI18nHydrationSupportEnabled() {
  16039. return _isI18nHydrationSupportEnabled;
  16040. }
  16041. /**
  16042. * Prepares an i18n block and its children, located at the given
  16043. * view and instruction index, for hydration.
  16044. *
  16045. * @param lView lView with the i18n block
  16046. * @param index index of the i18n block in the lView
  16047. * @param parentTNode TNode of the parent of the i18n block
  16048. * @param subTemplateIndex sub-template index, or -1 for the main template
  16049. */
  16050. function prepareI18nBlockForHydration(lView, index, parentTNode, subTemplateIndex) {
  16051. _prepareI18nBlockForHydrationImpl(lView, index, parentTNode, subTemplateIndex);
  16052. }
  16053. function enablePrepareI18nBlockForHydrationImpl() {
  16054. _prepareI18nBlockForHydrationImpl = prepareI18nBlockForHydrationImpl;
  16055. }
  16056. function isI18nHydrationEnabled(injector) {
  16057. injector = injector ?? inject(Injector);
  16058. return injector.get(IS_I18N_HYDRATION_ENABLED, false);
  16059. }
  16060. /**
  16061. * Collects, if not already cached, all of the indices in the
  16062. * given TView which are children of an i18n block.
  16063. *
  16064. * Since i18n blocks don't introduce a parent TNode, this is necessary
  16065. * in order to determine which indices in a LView are translated.
  16066. */
  16067. function getOrComputeI18nChildren(tView, context) {
  16068. let i18nChildren = context.i18nChildren.get(tView);
  16069. if (i18nChildren === undefined) {
  16070. i18nChildren = collectI18nChildren(tView);
  16071. context.i18nChildren.set(tView, i18nChildren);
  16072. }
  16073. return i18nChildren;
  16074. }
  16075. function collectI18nChildren(tView) {
  16076. const children = new Set();
  16077. function collectI18nViews(node) {
  16078. children.add(node.index);
  16079. switch (node.kind) {
  16080. case 1 /* I18nNodeKind.ELEMENT */:
  16081. case 2 /* I18nNodeKind.PLACEHOLDER */: {
  16082. for (const childNode of node.children) {
  16083. collectI18nViews(childNode);
  16084. }
  16085. break;
  16086. }
  16087. case 3 /* I18nNodeKind.ICU */: {
  16088. for (const caseNodes of node.cases) {
  16089. for (const caseNode of caseNodes) {
  16090. collectI18nViews(caseNode);
  16091. }
  16092. }
  16093. break;
  16094. }
  16095. }
  16096. }
  16097. // Traverse through the AST of each i18n block in the LView,
  16098. // and collect every instruction index.
  16099. for (let i = HEADER_OFFSET; i < tView.bindingStartIndex; i++) {
  16100. const tI18n = tView.data[i];
  16101. if (!tI18n || !tI18n.ast) {
  16102. continue;
  16103. }
  16104. for (const node of tI18n.ast) {
  16105. collectI18nViews(node);
  16106. }
  16107. }
  16108. return children.size === 0 ? null : children;
  16109. }
  16110. /**
  16111. * Attempts to serialize i18n data for an i18n block, located at
  16112. * the given view and instruction index.
  16113. *
  16114. * @param lView lView with the i18n block
  16115. * @param index index of the i18n block in the lView
  16116. * @param context the hydration context
  16117. * @returns the i18n data, or null if there is no relevant data
  16118. */
  16119. function trySerializeI18nBlock(lView, index, context) {
  16120. if (!context.isI18nHydrationEnabled) {
  16121. return null;
  16122. }
  16123. const tView = lView[TVIEW];
  16124. const tI18n = tView.data[index];
  16125. if (!tI18n || !tI18n.ast) {
  16126. return null;
  16127. }
  16128. const parentTNode = tView.data[tI18n.parentTNodeIndex];
  16129. if (parentTNode && isI18nInSkipHydrationBlock(parentTNode)) {
  16130. return null;
  16131. }
  16132. const serializedI18nBlock = {
  16133. caseQueue: [],
  16134. disconnectedNodes: new Set(),
  16135. disjointNodes: new Set(),
  16136. };
  16137. serializeI18nBlock(lView, serializedI18nBlock, context, tI18n.ast);
  16138. return serializedI18nBlock.caseQueue.length === 0 &&
  16139. serializedI18nBlock.disconnectedNodes.size === 0 &&
  16140. serializedI18nBlock.disjointNodes.size === 0
  16141. ? null
  16142. : serializedI18nBlock;
  16143. }
  16144. function serializeI18nBlock(lView, serializedI18nBlock, context, nodes) {
  16145. let prevRNode = null;
  16146. for (const node of nodes) {
  16147. const nextRNode = serializeI18nNode(lView, serializedI18nBlock, context, node);
  16148. if (nextRNode) {
  16149. if (isDisjointNode(prevRNode, nextRNode)) {
  16150. serializedI18nBlock.disjointNodes.add(node.index - HEADER_OFFSET);
  16151. }
  16152. prevRNode = nextRNode;
  16153. }
  16154. }
  16155. return prevRNode;
  16156. }
  16157. /**
  16158. * Helper to determine whether the given nodes are "disjoint".
  16159. *
  16160. * The i18n hydration process walks through the DOM and i18n nodes
  16161. * at the same time. It expects the sibling DOM node of the previous
  16162. * i18n node to be the first node of the next i18n node.
  16163. *
  16164. * In cases of content projection, this won't always be the case. So
  16165. * when we detect that, we mark the node as "disjoint", ensuring that
  16166. * we will serialize the path to the node. This way, when we hydrate the
  16167. * i18n node, we will be able to find the correct place to start.
  16168. */
  16169. function isDisjointNode(prevNode, nextNode) {
  16170. return prevNode && prevNode.nextSibling !== nextNode;
  16171. }
  16172. /**
  16173. * Process the given i18n node for serialization.
  16174. * Returns the first RNode for the i18n node to begin hydration.
  16175. */
  16176. function serializeI18nNode(lView, serializedI18nBlock, context, node) {
  16177. const maybeRNode = unwrapRNode(lView[node.index]);
  16178. if (!maybeRNode || isDisconnectedRNode(maybeRNode)) {
  16179. serializedI18nBlock.disconnectedNodes.add(node.index - HEADER_OFFSET);
  16180. return null;
  16181. }
  16182. const rNode = maybeRNode;
  16183. switch (node.kind) {
  16184. case 0 /* I18nNodeKind.TEXT */: {
  16185. processTextNodeBeforeSerialization(context, rNode);
  16186. break;
  16187. }
  16188. case 1 /* I18nNodeKind.ELEMENT */:
  16189. case 2 /* I18nNodeKind.PLACEHOLDER */: {
  16190. serializeI18nBlock(lView, serializedI18nBlock, context, node.children);
  16191. break;
  16192. }
  16193. case 3 /* I18nNodeKind.ICU */: {
  16194. const currentCase = lView[node.currentCaseLViewIndex];
  16195. if (currentCase != null) {
  16196. // i18n uses a negative value to signal a change to a new case, so we
  16197. // need to invert it to get the proper value.
  16198. const caseIdx = currentCase < 0 ? ~currentCase : currentCase;
  16199. serializedI18nBlock.caseQueue.push(caseIdx);
  16200. serializeI18nBlock(lView, serializedI18nBlock, context, node.cases[caseIdx]);
  16201. }
  16202. break;
  16203. }
  16204. }
  16205. return getFirstNativeNodeForI18nNode(lView, node);
  16206. }
  16207. /**
  16208. * Helper function to get the first native node to begin hydrating
  16209. * the given i18n node.
  16210. */
  16211. function getFirstNativeNodeForI18nNode(lView, node) {
  16212. const tView = lView[TVIEW];
  16213. const maybeTNode = tView.data[node.index];
  16214. if (isTNodeShape(maybeTNode)) {
  16215. // If the node is backed by an actual TNode, we can simply delegate.
  16216. return getFirstNativeNode(lView, maybeTNode);
  16217. }
  16218. else if (node.kind === 3 /* I18nNodeKind.ICU */) {
  16219. // A nested ICU container won't have an actual TNode. In that case, we can use
  16220. // an iterator to find the first child.
  16221. const icuIterator = createIcuIterator(maybeTNode, lView);
  16222. let rNode = icuIterator();
  16223. // If the ICU container has no nodes, then we use the ICU anchor as the node.
  16224. return rNode ?? unwrapRNode(lView[node.index]);
  16225. }
  16226. else {
  16227. // Otherwise, the node is a text or trivial element in an ICU container,
  16228. // and we can just use the RNode directly.
  16229. return unwrapRNode(lView[node.index]) ?? null;
  16230. }
  16231. }
  16232. function setCurrentNode(state, node) {
  16233. state.currentNode = node;
  16234. }
  16235. /**
  16236. * Marks the current RNode as the hydration root for the given
  16237. * AST node.
  16238. */
  16239. function appendI18nNodeToCollection(context, state, astNode) {
  16240. const noOffsetIndex = astNode.index - HEADER_OFFSET;
  16241. const { disconnectedNodes } = context;
  16242. const currentNode = state.currentNode;
  16243. if (state.isConnected) {
  16244. context.i18nNodes.set(noOffsetIndex, currentNode);
  16245. // We expect the node to be connected, so ensure that it
  16246. // is not in the set, regardless of whether we found it,
  16247. // so that the downstream error handling can provide the
  16248. // proper context.
  16249. disconnectedNodes.delete(noOffsetIndex);
  16250. }
  16251. else {
  16252. disconnectedNodes.add(noOffsetIndex);
  16253. }
  16254. return currentNode;
  16255. }
  16256. /**
  16257. * Skip over some sibling nodes during hydration.
  16258. *
  16259. * Note: we use this instead of `siblingAfter` as it's expected that
  16260. * sometimes we might encounter null nodes. In those cases, we want to
  16261. * defer to downstream error handling to provide proper context.
  16262. */
  16263. function skipSiblingNodes(state, skip) {
  16264. let currentNode = state.currentNode;
  16265. for (let i = 0; i < skip; i++) {
  16266. if (!currentNode) {
  16267. break;
  16268. }
  16269. currentNode = currentNode?.nextSibling ?? null;
  16270. }
  16271. return currentNode;
  16272. }
  16273. /**
  16274. * Fork the given state into a new state for hydrating children.
  16275. */
  16276. function forkHydrationState(state, nextNode) {
  16277. return { currentNode: nextNode, isConnected: state.isConnected };
  16278. }
  16279. function prepareI18nBlockForHydrationImpl(lView, index, parentTNode, subTemplateIndex) {
  16280. const hydrationInfo = lView[HYDRATION];
  16281. if (!hydrationInfo) {
  16282. return;
  16283. }
  16284. if (!isI18nHydrationSupportEnabled() ||
  16285. (parentTNode &&
  16286. (isI18nInSkipHydrationBlock(parentTNode) ||
  16287. isDisconnectedNode$1(hydrationInfo, parentTNode.index - HEADER_OFFSET)))) {
  16288. return;
  16289. }
  16290. const tView = lView[TVIEW];
  16291. const tI18n = tView.data[index];
  16292. ngDevMode &&
  16293. assertDefined(tI18n, 'Expected i18n data to be present in a given TView slot during hydration');
  16294. function findHydrationRoot() {
  16295. if (isRootTemplateMessage(subTemplateIndex)) {
  16296. // This is the root of an i18n block. In this case, our hydration root will
  16297. // depend on where our parent TNode (i.e. the block with i18n applied) is
  16298. // in the DOM.
  16299. ngDevMode && assertDefined(parentTNode, 'Expected parent TNode while hydrating i18n root');
  16300. const rootNode = locateNextRNode(hydrationInfo, tView, lView, parentTNode);
  16301. // If this i18n block is attached to an <ng-container>, then we want to begin
  16302. // hydrating directly with the RNode. Otherwise, for a TNode with a physical DOM
  16303. // element, we want to recurse into the first child and begin there.
  16304. return parentTNode.type & 8 /* TNodeType.ElementContainer */ ? rootNode : rootNode.firstChild;
  16305. }
  16306. // This is a nested template in an i18n block. In this case, the entire view
  16307. // is translated, and part of a dehydrated view in a container. This means that
  16308. // we can simply begin hydration with the first dehydrated child.
  16309. return hydrationInfo?.firstChild;
  16310. }
  16311. const currentNode = findHydrationRoot();
  16312. ngDevMode && assertDefined(currentNode, 'Expected root i18n node during hydration');
  16313. const disconnectedNodes = initDisconnectedNodes(hydrationInfo) ?? new Set();
  16314. const i18nNodes = (hydrationInfo.i18nNodes ??= new Map());
  16315. const caseQueue = hydrationInfo.data[I18N_DATA]?.[index - HEADER_OFFSET] ?? [];
  16316. const dehydratedIcuData = (hydrationInfo.dehydratedIcuData ??= new Map());
  16317. collectI18nNodesFromDom({ hydrationInfo, lView, i18nNodes, disconnectedNodes, caseQueue, dehydratedIcuData }, { currentNode, isConnected: true }, tI18n.ast);
  16318. // Nodes from inactive ICU cases should be considered disconnected. We track them above
  16319. // because they aren't (and shouldn't be) serialized. Since we may mutate or create a
  16320. // new set, we need to be sure to write the expected value back to the DehydratedView.
  16321. hydrationInfo.disconnectedNodes = disconnectedNodes.size === 0 ? null : disconnectedNodes;
  16322. }
  16323. function collectI18nNodesFromDom(context, state, nodeOrNodes) {
  16324. if (Array.isArray(nodeOrNodes)) {
  16325. let nextState = state;
  16326. for (const node of nodeOrNodes) {
  16327. // Whenever a node doesn't directly follow the previous RNode, it
  16328. // is given a path. We need to resume collecting nodes from that location
  16329. // until and unless we find another disjoint node.
  16330. const targetNode = tryLocateRNodeByPath(context.hydrationInfo, context.lView, node.index - HEADER_OFFSET);
  16331. if (targetNode) {
  16332. nextState = forkHydrationState(state, targetNode);
  16333. }
  16334. collectI18nNodesFromDom(context, nextState, node);
  16335. }
  16336. }
  16337. else {
  16338. if (context.disconnectedNodes.has(nodeOrNodes.index - HEADER_OFFSET)) {
  16339. // i18n nodes can be considered disconnected if e.g. they were projected.
  16340. // In that case, we have to make sure to skip over them.
  16341. return;
  16342. }
  16343. switch (nodeOrNodes.kind) {
  16344. case 0 /* I18nNodeKind.TEXT */: {
  16345. // Claim a text node for hydration
  16346. const currentNode = appendI18nNodeToCollection(context, state, nodeOrNodes);
  16347. setCurrentNode(state, currentNode?.nextSibling ?? null);
  16348. break;
  16349. }
  16350. case 1 /* I18nNodeKind.ELEMENT */: {
  16351. // Recurse into the current element's children...
  16352. collectI18nNodesFromDom(context, forkHydrationState(state, state.currentNode?.firstChild ?? null), nodeOrNodes.children);
  16353. // And claim the parent element itself.
  16354. const currentNode = appendI18nNodeToCollection(context, state, nodeOrNodes);
  16355. setCurrentNode(state, currentNode?.nextSibling ?? null);
  16356. break;
  16357. }
  16358. case 2 /* I18nNodeKind.PLACEHOLDER */: {
  16359. const noOffsetIndex = nodeOrNodes.index - HEADER_OFFSET;
  16360. const { hydrationInfo } = context;
  16361. const containerSize = getNgContainerSize(hydrationInfo, noOffsetIndex);
  16362. switch (nodeOrNodes.type) {
  16363. case 0 /* I18nPlaceholderType.ELEMENT */: {
  16364. // Hydration expects to find the head of the element.
  16365. const currentNode = appendI18nNodeToCollection(context, state, nodeOrNodes);
  16366. // A TNode for the node may not yet if we're hydrating during the first pass,
  16367. // so use the serialized data to determine if this is an <ng-container>.
  16368. if (isSerializedElementContainer(hydrationInfo, noOffsetIndex)) {
  16369. // An <ng-container> doesn't have a physical DOM node, so we need to
  16370. // continue hydrating from siblings.
  16371. collectI18nNodesFromDom(context, state, nodeOrNodes.children);
  16372. // Skip over the anchor element. It will be claimed by the
  16373. // downstream container hydration.
  16374. const nextNode = skipSiblingNodes(state, 1);
  16375. setCurrentNode(state, nextNode);
  16376. }
  16377. else {
  16378. // Non-container elements represent an actual node in the DOM, so we
  16379. // need to continue hydration with the children, and claim the node.
  16380. collectI18nNodesFromDom(context, forkHydrationState(state, state.currentNode?.firstChild ?? null), nodeOrNodes.children);
  16381. setCurrentNode(state, currentNode?.nextSibling ?? null);
  16382. // Elements can also be the anchor of a view container, so there may
  16383. // be elements after this node that we need to skip.
  16384. if (containerSize !== null) {
  16385. // `+1` stands for an anchor node after all of the views in the container.
  16386. const nextNode = skipSiblingNodes(state, containerSize + 1);
  16387. setCurrentNode(state, nextNode);
  16388. }
  16389. }
  16390. break;
  16391. }
  16392. case 1 /* I18nPlaceholderType.SUBTEMPLATE */: {
  16393. ngDevMode &&
  16394. assertNotEqual(containerSize, null, 'Expected a container size while hydrating i18n subtemplate');
  16395. // Hydration expects to find the head of the template.
  16396. appendI18nNodeToCollection(context, state, nodeOrNodes);
  16397. // Skip over all of the template children, as well as the anchor
  16398. // node, since the template itself will handle them instead.
  16399. const nextNode = skipSiblingNodes(state, containerSize + 1);
  16400. setCurrentNode(state, nextNode);
  16401. break;
  16402. }
  16403. }
  16404. break;
  16405. }
  16406. case 3 /* I18nNodeKind.ICU */: {
  16407. // If the current node is connected, we need to pop the next case from the
  16408. // queue, so that the active case is also considered connected.
  16409. const selectedCase = state.isConnected ? context.caseQueue.shift() : null;
  16410. const childState = { currentNode: null, isConnected: false };
  16411. // We traverse through each case, even if it's not active,
  16412. // so that we correctly populate disconnected nodes.
  16413. for (let i = 0; i < nodeOrNodes.cases.length; i++) {
  16414. collectI18nNodesFromDom(context, i === selectedCase ? state : childState, nodeOrNodes.cases[i]);
  16415. }
  16416. if (selectedCase !== null) {
  16417. // ICUs represent a branching state, and the selected case could be different
  16418. // than what it was on the server. In that case, we need to be able to clean
  16419. // up the nodes from the original case. To do that, we store the selected case.
  16420. context.dehydratedIcuData.set(nodeOrNodes.index, { case: selectedCase, node: nodeOrNodes });
  16421. }
  16422. // Hydration expects to find the ICU anchor element.
  16423. const currentNode = appendI18nNodeToCollection(context, state, nodeOrNodes);
  16424. setCurrentNode(state, currentNode?.nextSibling ?? null);
  16425. break;
  16426. }
  16427. }
  16428. }
  16429. }
  16430. let _claimDehydratedIcuCaseImpl = () => {
  16431. // noop unless `enableClaimDehydratedIcuCaseImpl` is invoked
  16432. };
  16433. /**
  16434. * Mark the case for the ICU node at the given index in the view as claimed,
  16435. * allowing its nodes to be hydrated and not cleaned up.
  16436. */
  16437. function claimDehydratedIcuCase(lView, icuIndex, caseIndex) {
  16438. _claimDehydratedIcuCaseImpl(lView, icuIndex, caseIndex);
  16439. }
  16440. function enableClaimDehydratedIcuCaseImpl() {
  16441. _claimDehydratedIcuCaseImpl = claimDehydratedIcuCaseImpl;
  16442. }
  16443. function claimDehydratedIcuCaseImpl(lView, icuIndex, caseIndex) {
  16444. const dehydratedIcuDataMap = lView[HYDRATION]?.dehydratedIcuData;
  16445. if (dehydratedIcuDataMap) {
  16446. const dehydratedIcuData = dehydratedIcuDataMap.get(icuIndex);
  16447. if (dehydratedIcuData?.case === caseIndex) {
  16448. // If the case we're attempting to claim matches the dehydrated one,
  16449. // we remove it from the map to mark it as "claimed."
  16450. dehydratedIcuDataMap.delete(icuIndex);
  16451. }
  16452. }
  16453. }
  16454. /**
  16455. * Clean up all i18n hydration data associated with the given view.
  16456. */
  16457. function cleanupI18nHydrationData(lView) {
  16458. const hydrationInfo = lView[HYDRATION];
  16459. if (hydrationInfo) {
  16460. const { i18nNodes, dehydratedIcuData: dehydratedIcuDataMap } = hydrationInfo;
  16461. if (i18nNodes && dehydratedIcuDataMap) {
  16462. const renderer = lView[RENDERER];
  16463. for (const dehydratedIcuData of dehydratedIcuDataMap.values()) {
  16464. cleanupDehydratedIcuData(renderer, i18nNodes, dehydratedIcuData);
  16465. }
  16466. }
  16467. hydrationInfo.i18nNodes = undefined;
  16468. hydrationInfo.dehydratedIcuData = undefined;
  16469. }
  16470. }
  16471. function cleanupDehydratedIcuData(renderer, i18nNodes, dehydratedIcuData) {
  16472. for (const node of dehydratedIcuData.node.cases[dehydratedIcuData.case]) {
  16473. const rNode = i18nNodes.get(node.index - HEADER_OFFSET);
  16474. if (rNode) {
  16475. nativeRemoveNode(renderer, rNode, false);
  16476. }
  16477. }
  16478. }
  16479. /**
  16480. * Removes all dehydrated views from a given LContainer:
  16481. * both in internal data structure, as well as removing
  16482. * corresponding DOM nodes that belong to that dehydrated view.
  16483. */
  16484. function removeDehydratedViews(lContainer) {
  16485. const views = lContainer[DEHYDRATED_VIEWS] ?? [];
  16486. const parentLView = lContainer[PARENT];
  16487. const renderer = parentLView[RENDERER];
  16488. const retainedViews = [];
  16489. for (const view of views) {
  16490. // Do not clean up contents of `@defer` blocks.
  16491. // The cleanup for this content would happen once a given block
  16492. // is triggered and hydrated.
  16493. if (view.data[DEFER_BLOCK_ID] !== undefined) {
  16494. retainedViews.push(view);
  16495. }
  16496. else {
  16497. removeDehydratedView(view, renderer);
  16498. ngDevMode && ngDevMode.dehydratedViewsRemoved++;
  16499. }
  16500. }
  16501. // Reset the value to an array to indicate that no
  16502. // further processing of dehydrated views is needed for
  16503. // this view container (i.e. do not trigger the lookup process
  16504. // once again in case a `ViewContainerRef` is created later).
  16505. lContainer[DEHYDRATED_VIEWS] = retainedViews;
  16506. }
  16507. function removeDehydratedViewList(deferBlock) {
  16508. const { lContainer } = deferBlock;
  16509. const dehydratedViews = lContainer[DEHYDRATED_VIEWS];
  16510. if (dehydratedViews === null)
  16511. return;
  16512. const parentLView = lContainer[PARENT];
  16513. const renderer = parentLView[RENDERER];
  16514. for (const view of dehydratedViews) {
  16515. removeDehydratedView(view, renderer);
  16516. ngDevMode && ngDevMode.dehydratedViewsRemoved++;
  16517. }
  16518. }
  16519. /**
  16520. * Helper function to remove all nodes from a dehydrated view.
  16521. */
  16522. function removeDehydratedView(dehydratedView, renderer) {
  16523. let nodesRemoved = 0;
  16524. let currentRNode = dehydratedView.firstChild;
  16525. if (currentRNode) {
  16526. const numNodes = dehydratedView.data[NUM_ROOT_NODES];
  16527. while (nodesRemoved < numNodes) {
  16528. ngDevMode && validateSiblingNodeExists(currentRNode);
  16529. const nextSibling = currentRNode.nextSibling;
  16530. nativeRemoveNode(renderer, currentRNode, false);
  16531. currentRNode = nextSibling;
  16532. nodesRemoved++;
  16533. }
  16534. }
  16535. }
  16536. /**
  16537. * Walks over all views within this LContainer invokes dehydrated views
  16538. * cleanup function for each one.
  16539. */
  16540. function cleanupLContainer(lContainer) {
  16541. removeDehydratedViews(lContainer);
  16542. // The host could be an LView if this container is on a component node.
  16543. // In this case, descend into host LView for further cleanup. See also
  16544. // LContainer[HOST] docs for additional information.
  16545. const hostLView = lContainer[HOST];
  16546. if (isLView(hostLView)) {
  16547. cleanupLView(hostLView);
  16548. }
  16549. for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
  16550. cleanupLView(lContainer[i]);
  16551. }
  16552. }
  16553. /**
  16554. * Walks over `LContainer`s and components registered within
  16555. * this LView and invokes dehydrated views cleanup function for each one.
  16556. */
  16557. function cleanupLView(lView) {
  16558. cleanupI18nHydrationData(lView);
  16559. const tView = lView[TVIEW];
  16560. for (let i = HEADER_OFFSET; i < tView.bindingStartIndex; i++) {
  16561. if (isLContainer(lView[i])) {
  16562. const lContainer = lView[i];
  16563. cleanupLContainer(lContainer);
  16564. }
  16565. else if (isLView(lView[i])) {
  16566. // This is a component, enter the `cleanupLView` recursively.
  16567. cleanupLView(lView[i]);
  16568. }
  16569. }
  16570. }
  16571. /**
  16572. * Walks over all views registered within the ApplicationRef and removes
  16573. * all dehydrated views from all `LContainer`s along the way.
  16574. */
  16575. function cleanupDehydratedViews(appRef) {
  16576. const viewRefs = appRef._views;
  16577. for (const viewRef of viewRefs) {
  16578. const lNode = getLNodeForHydration(viewRef);
  16579. // An `lView` might be `null` if a `ViewRef` represents
  16580. // an embedded view (not a component view).
  16581. if (lNode !== null && lNode[HOST] !== null) {
  16582. if (isLView(lNode)) {
  16583. cleanupLView(lNode);
  16584. }
  16585. else {
  16586. // Cleanup in all views within this view container
  16587. cleanupLContainer(lNode);
  16588. }
  16589. ngDevMode && ngDevMode.dehydratedViewsCleanupRuns++;
  16590. }
  16591. }
  16592. }
  16593. /**
  16594. * post hydration cleanup handling for defer blocks that were incrementally
  16595. * hydrated. This removes all the jsaction attributes, timers, observers,
  16596. * dehydrated views and containers
  16597. */
  16598. function cleanupHydratedDeferBlocks(deferBlock, hydratedBlocks, registry, appRef) {
  16599. if (deferBlock !== null) {
  16600. registry.cleanup(hydratedBlocks);
  16601. cleanupLContainer(deferBlock.lContainer);
  16602. cleanupDehydratedViews(appRef);
  16603. }
  16604. }
  16605. /**
  16606. * Given a current DOM node and a serialized information about the views
  16607. * in a container, walks over the DOM structure, collecting the list of
  16608. * dehydrated views.
  16609. */
  16610. function locateDehydratedViewsInContainer(currentRNode, serializedViews) {
  16611. const dehydratedViews = [];
  16612. for (const serializedView of serializedViews) {
  16613. // Repeats a view multiple times as needed, based on the serialized information
  16614. // (for example, for *ngFor-produced views).
  16615. for (let i = 0; i < (serializedView[MULTIPLIER] ?? 1); i++) {
  16616. const view = {
  16617. data: serializedView,
  16618. firstChild: null,
  16619. };
  16620. if (serializedView[NUM_ROOT_NODES] > 0) {
  16621. // Keep reference to the first node in this view,
  16622. // so it can be accessed while invoking template instructions.
  16623. view.firstChild = currentRNode;
  16624. // Move over to the next node after this view, which can
  16625. // either be a first node of the next view or an anchor comment
  16626. // node after the last view in a container.
  16627. currentRNode = siblingAfter(serializedView[NUM_ROOT_NODES], currentRNode);
  16628. }
  16629. dehydratedViews.push(view);
  16630. }
  16631. }
  16632. return [currentRNode, dehydratedViews];
  16633. }
  16634. /**
  16635. * Reference to a function that searches for a matching dehydrated views
  16636. * stored on a given lContainer.
  16637. * Returns `null` by default, when hydration is not enabled.
  16638. */
  16639. let _findMatchingDehydratedViewImpl = () => null;
  16640. /**
  16641. * Retrieves the next dehydrated view from the LContainer and verifies that
  16642. * it matches a given template id (from the TView that was used to create this
  16643. * instance of a view). If the id doesn't match, that means that we are in an
  16644. * unexpected state and can not complete the reconciliation process. Thus,
  16645. * all dehydrated views from this LContainer are removed (including corresponding
  16646. * DOM nodes) and the rendering is performed as if there were no dehydrated views
  16647. * in this container.
  16648. */
  16649. function findMatchingDehydratedViewImpl(lContainer, template) {
  16650. const views = lContainer[DEHYDRATED_VIEWS];
  16651. if (!template || views === null || views.length === 0) {
  16652. return null;
  16653. }
  16654. const view = views[0];
  16655. // Verify whether the first dehydrated view in the container matches
  16656. // the template id passed to this function (that originated from a TView
  16657. // that was used to create an instance of an embedded or component views.
  16658. if (view.data[TEMPLATE_ID] === template) {
  16659. // If the template id matches - extract the first view and return it.
  16660. return views.shift();
  16661. }
  16662. else {
  16663. // Otherwise, we are at the state when reconciliation can not be completed,
  16664. // thus we remove all dehydrated views within this container (remove them
  16665. // from internal data structures as well as delete associated elements from
  16666. // the DOM tree).
  16667. removeDehydratedViews(lContainer);
  16668. return null;
  16669. }
  16670. }
  16671. function enableFindMatchingDehydratedViewImpl() {
  16672. _findMatchingDehydratedViewImpl = findMatchingDehydratedViewImpl;
  16673. }
  16674. function findMatchingDehydratedView(lContainer, template) {
  16675. return _findMatchingDehydratedViewImpl(lContainer, template);
  16676. }
  16677. /**
  16678. * Represents a component created by a `ComponentFactory`.
  16679. * Provides access to the component instance and related objects,
  16680. * and provides the means of destroying the instance.
  16681. *
  16682. * @publicApi
  16683. */
  16684. let ComponentRef$1 = class ComponentRef {
  16685. };
  16686. /**
  16687. * Base class for a factory that can create a component dynamically.
  16688. * Instantiate a factory for a given type of component with `resolveComponentFactory()`.
  16689. * Use the resulting `ComponentFactory.create()` method to create a component of that type.
  16690. *
  16691. * @publicApi
  16692. *
  16693. * @deprecated Angular no longer requires Component factories. Please use other APIs where
  16694. * Component class can be used directly.
  16695. */
  16696. let ComponentFactory$1 = class ComponentFactory {
  16697. };
  16698. class _NullComponentFactoryResolver {
  16699. resolveComponentFactory(component) {
  16700. throw Error(`No component factory found for ${stringify(component)}.`);
  16701. }
  16702. }
  16703. /**
  16704. * A simple registry that maps `Components` to generated `ComponentFactory` classes
  16705. * that can be used to create instances of components.
  16706. * Use to obtain the factory for a given component type,
  16707. * then use the factory's `create()` method to create a component of that type.
  16708. *
  16709. * Note: since v13, dynamic component creation via
  16710. * [`ViewContainerRef.createComponent`](api/core/ViewContainerRef#createComponent)
  16711. * does **not** require resolving component factory: component class can be used directly.
  16712. *
  16713. * @publicApi
  16714. *
  16715. * @deprecated Angular no longer requires Component factories. Please use other APIs where
  16716. * Component class can be used directly.
  16717. */
  16718. let ComponentFactoryResolver$1 = class ComponentFactoryResolver {
  16719. static NULL = new _NullComponentFactoryResolver();
  16720. };
  16721. /**
  16722. * Creates and initializes a custom renderer that implements the `Renderer2` base class.
  16723. *
  16724. * @publicApi
  16725. */
  16726. class RendererFactory2 {
  16727. }
  16728. /**
  16729. * Extend this base class to implement custom rendering. By default, Angular
  16730. * renders a template into DOM. You can use custom rendering to intercept
  16731. * rendering calls, or to render to something other than DOM.
  16732. *
  16733. * Create your custom renderer using `RendererFactory2`.
  16734. *
  16735. * Use a custom renderer to bypass Angular's templating and
  16736. * make custom UI changes that can't be expressed declaratively.
  16737. * For example if you need to set a property or an attribute whose name is
  16738. * not statically known, use the `setProperty()` or
  16739. * `setAttribute()` method.
  16740. *
  16741. * @publicApi
  16742. */
  16743. class Renderer2 {
  16744. /**
  16745. * If null or undefined, the view engine won't call it.
  16746. * This is used as a performance optimization for production mode.
  16747. */
  16748. destroyNode = null;
  16749. /**
  16750. * @internal
  16751. * @nocollapse
  16752. */
  16753. static __NG_ELEMENT_ID__ = () => injectRenderer2();
  16754. }
  16755. /** Injects a Renderer2 for the current component. */
  16756. function injectRenderer2() {
  16757. // We need the Renderer to be based on the component that it's being injected into, however since
  16758. // DI happens before we've entered its view, `getLView` will return the parent view instead.
  16759. const lView = getLView();
  16760. const tNode = getCurrentTNode();
  16761. const nodeAtIndex = getComponentLViewByIndex(tNode.index, lView);
  16762. return (isLView(nodeAtIndex) ? nodeAtIndex : lView)[RENDERER];
  16763. }
  16764. /**
  16765. * Sanitizer is used by the views to sanitize potentially dangerous values.
  16766. *
  16767. * @publicApi
  16768. */
  16769. class Sanitizer {
  16770. /** @nocollapse */
  16771. static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
  16772. token: Sanitizer,
  16773. providedIn: 'root',
  16774. factory: () => null,
  16775. });
  16776. }
  16777. function isModuleWithProviders(value) {
  16778. return value.ngModule !== undefined;
  16779. }
  16780. function isNgModule(value) {
  16781. return !!getNgModuleDef(value);
  16782. }
  16783. function isPipe(value) {
  16784. return !!getPipeDef$1(value);
  16785. }
  16786. function isDirective(value) {
  16787. return !!getDirectiveDef(value);
  16788. }
  16789. function isComponent(value) {
  16790. return !!getComponentDef(value);
  16791. }
  16792. function getDependencyTypeForError(type) {
  16793. if (getComponentDef(type))
  16794. return 'component';
  16795. if (getDirectiveDef(type))
  16796. return 'directive';
  16797. if (getPipeDef$1(type))
  16798. return 'pipe';
  16799. return 'type';
  16800. }
  16801. function verifyStandaloneImport(depType, importingType) {
  16802. if (isForwardRef(depType)) {
  16803. depType = resolveForwardRef(depType);
  16804. if (!depType) {
  16805. throw new Error(`Expected forwardRef function, imported from "${stringifyForError(importingType)}", to return a standalone entity or NgModule but got "${stringifyForError(depType) || depType}".`);
  16806. }
  16807. }
  16808. if (getNgModuleDef(depType) == null) {
  16809. const def = getComponentDef(depType) || getDirectiveDef(depType) || getPipeDef$1(depType);
  16810. if (def != null) {
  16811. // if a component, directive or pipe is imported make sure that it is standalone
  16812. if (!def.standalone) {
  16813. throw new Error(`The "${stringifyForError(depType)}" ${getDependencyTypeForError(depType)}, imported from "${stringifyForError(importingType)}", is not standalone. Did you forget to add the standalone: true flag?`);
  16814. }
  16815. }
  16816. else {
  16817. // it can be either a module with provider or an unknown (not annotated) type
  16818. if (isModuleWithProviders(depType)) {
  16819. throw new Error(`A module with providers was imported from "${stringifyForError(importingType)}". Modules with providers are not supported in standalone components imports.`);
  16820. }
  16821. else {
  16822. throw new Error(`The "${stringifyForError(depType)}" type, imported from "${stringifyForError(importingType)}", must be a standalone component / directive / pipe or an NgModule. Did you forget to add the required @Component / @Directive / @Pipe or @NgModule annotation?`);
  16823. }
  16824. }
  16825. }
  16826. }
  16827. /**
  16828. * Indicates whether to use the runtime dependency tracker for scope calculation in JIT compilation.
  16829. * The value "false" means the old code path based on patching scope info into the types will be
  16830. * used.
  16831. *
  16832. * @deprecated For migration purposes only, to be removed soon.
  16833. */
  16834. const USE_RUNTIME_DEPS_TRACKER_FOR_JIT = true;
  16835. /**
  16836. * An implementation of DepsTrackerApi which will be used for JIT and local compilation.
  16837. */
  16838. class DepsTracker {
  16839. ownerNgModule = new Map();
  16840. ngModulesWithSomeUnresolvedDecls = new Set();
  16841. ngModulesScopeCache = new Map();
  16842. standaloneComponentsScopeCache = new Map();
  16843. /**
  16844. * Attempts to resolve ng module's forward ref declarations as much as possible and add them to
  16845. * the `ownerNgModule` map. This method normally should be called after the initial parsing when
  16846. * all the forward refs are resolved (e.g., when trying to render a component)
  16847. */
  16848. resolveNgModulesDecls() {
  16849. if (this.ngModulesWithSomeUnresolvedDecls.size === 0) {
  16850. return;
  16851. }
  16852. for (const moduleType of this.ngModulesWithSomeUnresolvedDecls) {
  16853. const def = getNgModuleDef(moduleType);
  16854. if (def?.declarations) {
  16855. for (const decl of maybeUnwrapFn(def.declarations)) {
  16856. if (isComponent(decl)) {
  16857. this.ownerNgModule.set(decl, moduleType);
  16858. }
  16859. }
  16860. }
  16861. }
  16862. this.ngModulesWithSomeUnresolvedDecls.clear();
  16863. }
  16864. /** @override */
  16865. getComponentDependencies(type, rawImports) {
  16866. this.resolveNgModulesDecls();
  16867. const def = getComponentDef(type);
  16868. if (def === null) {
  16869. throw new Error(`Attempting to get component dependencies for a type that is not a component: ${type}`);
  16870. }
  16871. if (def.standalone) {
  16872. const scope = this.getStandaloneComponentScope(type, rawImports);
  16873. if (scope.compilation.isPoisoned) {
  16874. return { dependencies: [] };
  16875. }
  16876. return {
  16877. dependencies: [
  16878. ...scope.compilation.directives,
  16879. ...scope.compilation.pipes,
  16880. ...scope.compilation.ngModules,
  16881. ],
  16882. };
  16883. }
  16884. else {
  16885. if (!this.ownerNgModule.has(type)) {
  16886. // This component is orphan! No need to handle the error since the component rendering
  16887. // pipeline (e.g., view_container_ref) will check for this error based on configs.
  16888. return { dependencies: [] };
  16889. }
  16890. const scope = this.getNgModuleScope(this.ownerNgModule.get(type));
  16891. if (scope.compilation.isPoisoned) {
  16892. return { dependencies: [] };
  16893. }
  16894. return {
  16895. dependencies: [...scope.compilation.directives, ...scope.compilation.pipes],
  16896. };
  16897. }
  16898. }
  16899. /**
  16900. * @override
  16901. * This implementation does not make use of param scopeInfo since it assumes the scope info is
  16902. * already added to the type itself through methods like {@link ɵɵsetNgModuleScope}
  16903. */
  16904. registerNgModule(type, scopeInfo) {
  16905. if (!isNgModule(type)) {
  16906. throw new Error(`Attempting to register a Type which is not NgModule as NgModule: ${type}`);
  16907. }
  16908. // Lazily process the NgModules later when needed.
  16909. this.ngModulesWithSomeUnresolvedDecls.add(type);
  16910. }
  16911. /** @override */
  16912. clearScopeCacheFor(type) {
  16913. this.ngModulesScopeCache.delete(type);
  16914. this.standaloneComponentsScopeCache.delete(type);
  16915. }
  16916. /** @override */
  16917. getNgModuleScope(type) {
  16918. if (this.ngModulesScopeCache.has(type)) {
  16919. return this.ngModulesScopeCache.get(type);
  16920. }
  16921. const scope = this.computeNgModuleScope(type);
  16922. this.ngModulesScopeCache.set(type, scope);
  16923. return scope;
  16924. }
  16925. /** Compute NgModule scope afresh. */
  16926. computeNgModuleScope(type) {
  16927. const def = getNgModuleDef(type, true);
  16928. const scope = {
  16929. exported: { directives: new Set(), pipes: new Set() },
  16930. compilation: { directives: new Set(), pipes: new Set() },
  16931. };
  16932. // Analyzing imports
  16933. for (const imported of maybeUnwrapFn(def.imports)) {
  16934. if (isNgModule(imported)) {
  16935. const importedScope = this.getNgModuleScope(imported);
  16936. // When this module imports another, the imported module's exported directives and pipes
  16937. // are added to the compilation scope of this module.
  16938. addSet(importedScope.exported.directives, scope.compilation.directives);
  16939. addSet(importedScope.exported.pipes, scope.compilation.pipes);
  16940. }
  16941. else if (isStandalone(imported)) {
  16942. if (isDirective(imported) || isComponent(imported)) {
  16943. scope.compilation.directives.add(imported);
  16944. }
  16945. else if (isPipe(imported)) {
  16946. scope.compilation.pipes.add(imported);
  16947. }
  16948. else {
  16949. // The standalone thing is neither a component nor a directive nor a pipe ... (what?)
  16950. throw new RuntimeError(980 /* RuntimeErrorCode.RUNTIME_DEPS_INVALID_IMPORTED_TYPE */, 'The standalone imported type is neither a component nor a directive nor a pipe');
  16951. }
  16952. }
  16953. else {
  16954. // The import is neither a module nor a module-with-providers nor a standalone thing. This
  16955. // is going to be an error. So we short circuit.
  16956. scope.compilation.isPoisoned = true;
  16957. break;
  16958. }
  16959. }
  16960. // Analyzing declarations
  16961. if (!scope.compilation.isPoisoned) {
  16962. for (const decl of maybeUnwrapFn(def.declarations)) {
  16963. // Cannot declare another NgModule or a standalone thing
  16964. if (isNgModule(decl) || isStandalone(decl)) {
  16965. scope.compilation.isPoisoned = true;
  16966. break;
  16967. }
  16968. if (isPipe(decl)) {
  16969. scope.compilation.pipes.add(decl);
  16970. }
  16971. else {
  16972. // decl is either a directive or a component. The component may not yet have the ɵcmp due
  16973. // to async compilation.
  16974. scope.compilation.directives.add(decl);
  16975. }
  16976. }
  16977. }
  16978. // Analyzing exports
  16979. for (const exported of maybeUnwrapFn(def.exports)) {
  16980. if (isNgModule(exported)) {
  16981. // When this module exports another, the exported module's exported directives and pipes
  16982. // are added to both the compilation and exported scopes of this module.
  16983. const exportedScope = this.getNgModuleScope(exported);
  16984. // Based on the current logic there is no way to have poisoned exported scope. So no need to
  16985. // check for it.
  16986. addSet(exportedScope.exported.directives, scope.exported.directives);
  16987. addSet(exportedScope.exported.pipes, scope.exported.pipes);
  16988. // Some test toolings which run in JIT mode depend on this behavior that the exported scope
  16989. // should also be present in the compilation scope, even though AoT does not support this
  16990. // and it is also in odds with NgModule metadata definitions. Without this some tests in
  16991. // Google will fail.
  16992. addSet(exportedScope.exported.directives, scope.compilation.directives);
  16993. addSet(exportedScope.exported.pipes, scope.compilation.pipes);
  16994. }
  16995. else if (isPipe(exported)) {
  16996. scope.exported.pipes.add(exported);
  16997. }
  16998. else {
  16999. scope.exported.directives.add(exported);
  17000. }
  17001. }
  17002. return scope;
  17003. }
  17004. /** @override */
  17005. getStandaloneComponentScope(type, rawImports) {
  17006. if (this.standaloneComponentsScopeCache.has(type)) {
  17007. return this.standaloneComponentsScopeCache.get(type);
  17008. }
  17009. const ans = this.computeStandaloneComponentScope(type, rawImports);
  17010. this.standaloneComponentsScopeCache.set(type, ans);
  17011. return ans;
  17012. }
  17013. computeStandaloneComponentScope(type, rawImports) {
  17014. const ans = {
  17015. compilation: {
  17016. // Standalone components are always able to self-reference.
  17017. directives: new Set([type]),
  17018. pipes: new Set(),
  17019. ngModules: new Set(),
  17020. },
  17021. };
  17022. for (const rawImport of flatten(rawImports ?? [])) {
  17023. const imported = resolveForwardRef(rawImport);
  17024. try {
  17025. verifyStandaloneImport(imported, type);
  17026. }
  17027. catch (e) {
  17028. // Short-circuit if an import is not valid
  17029. ans.compilation.isPoisoned = true;
  17030. return ans;
  17031. }
  17032. if (isNgModule(imported)) {
  17033. ans.compilation.ngModules.add(imported);
  17034. const importedScope = this.getNgModuleScope(imported);
  17035. // Short-circuit if an imported NgModule has corrupted exported scope.
  17036. if (importedScope.exported.isPoisoned) {
  17037. ans.compilation.isPoisoned = true;
  17038. return ans;
  17039. }
  17040. addSet(importedScope.exported.directives, ans.compilation.directives);
  17041. addSet(importedScope.exported.pipes, ans.compilation.pipes);
  17042. }
  17043. else if (isPipe(imported)) {
  17044. ans.compilation.pipes.add(imported);
  17045. }
  17046. else if (isDirective(imported) || isComponent(imported)) {
  17047. ans.compilation.directives.add(imported);
  17048. }
  17049. else {
  17050. // The imported thing is not module/pipe/directive/component, so we error and short-circuit
  17051. // here
  17052. ans.compilation.isPoisoned = true;
  17053. return ans;
  17054. }
  17055. }
  17056. return ans;
  17057. }
  17058. /** @override */
  17059. isOrphanComponent(cmp) {
  17060. const def = getComponentDef(cmp);
  17061. if (!def || def.standalone) {
  17062. return false;
  17063. }
  17064. this.resolveNgModulesDecls();
  17065. return !this.ownerNgModule.has(cmp);
  17066. }
  17067. }
  17068. function addSet(sourceSet, targetSet) {
  17069. for (const m of sourceSet) {
  17070. targetSet.add(m);
  17071. }
  17072. }
  17073. /** The deps tracker to be used in the current Angular app in dev mode. */
  17074. const depsTracker = new DepsTracker();
  17075. /**
  17076. * Compute the static styling (class/style) from `TAttributes`.
  17077. *
  17078. * This function should be called during `firstCreatePass` only.
  17079. *
  17080. * @param tNode The `TNode` into which the styling information should be loaded.
  17081. * @param attrs `TAttributes` containing the styling information.
  17082. * @param writeToHost Where should the resulting static styles be written?
  17083. * - `false` Write to `TNode.stylesWithoutHost` / `TNode.classesWithoutHost`
  17084. * - `true` Write to `TNode.styles` / `TNode.classes`
  17085. */
  17086. function computeStaticStyling(tNode, attrs, writeToHost) {
  17087. ngDevMode &&
  17088. assertFirstCreatePass(getTView(), 'Expecting to be called in first template pass only');
  17089. let styles = writeToHost ? tNode.styles : null;
  17090. let classes = writeToHost ? tNode.classes : null;
  17091. let mode = 0;
  17092. if (attrs !== null) {
  17093. for (let i = 0; i < attrs.length; i++) {
  17094. const value = attrs[i];
  17095. if (typeof value === 'number') {
  17096. mode = value;
  17097. }
  17098. else if (mode == 1 /* AttributeMarker.Classes */) {
  17099. classes = concatStringsWithSpace(classes, value);
  17100. }
  17101. else if (mode == 2 /* AttributeMarker.Styles */) {
  17102. const style = value;
  17103. const styleValue = attrs[++i];
  17104. styles = concatStringsWithSpace(styles, style + ': ' + styleValue + ';');
  17105. }
  17106. }
  17107. }
  17108. writeToHost ? (tNode.styles = styles) : (tNode.stylesWithoutHost = styles);
  17109. writeToHost ? (tNode.classes = classes) : (tNode.classesWithoutHost = classes);
  17110. }
  17111. function ɵɵdirectiveInject(token, flags = InjectFlags.Default) {
  17112. const lView = getLView();
  17113. // Fall back to inject() if view hasn't been created. This situation can happen in tests
  17114. // if inject utilities are used before bootstrapping.
  17115. if (lView === null) {
  17116. // Verify that we will not get into infinite loop.
  17117. ngDevMode && assertInjectImplementationNotEqual(ɵɵdirectiveInject);
  17118. return ɵɵinject(token, flags);
  17119. }
  17120. const tNode = getCurrentTNode();
  17121. const value = getOrCreateInjectable(tNode, lView, resolveForwardRef(token), flags);
  17122. ngDevMode && emitInjectEvent(token, value, flags);
  17123. return value;
  17124. }
  17125. /**
  17126. * Throws an error indicating that a factory function could not be generated by the compiler for a
  17127. * particular class.
  17128. *
  17129. * This instruction allows the actual error message to be optimized away when ngDevMode is turned
  17130. * off, saving bytes of generated code while still providing a good experience in dev mode.
  17131. *
  17132. * The name of the class is not mentioned here, but will be in the generated factory function name
  17133. * and thus in the stack trace.
  17134. *
  17135. * @codeGenApi
  17136. */
  17137. function ɵɵinvalidFactory() {
  17138. const msg = ngDevMode
  17139. ? `This constructor was not compatible with Dependency Injection.`
  17140. : 'invalid';
  17141. throw new Error(msg);
  17142. }
  17143. /**
  17144. * Resolve the matched directives on a node.
  17145. */
  17146. function resolveDirectives(tView, lView, tNode, localRefs, directiveMatcher) {
  17147. // Please make sure to have explicit type for `exportsMap`. Inferred type triggers bug in tsickle.
  17148. ngDevMode && assertFirstCreatePass(tView);
  17149. const exportsMap = localRefs === null ? null : { '': -1 };
  17150. const matchedDirectiveDefs = directiveMatcher(tView, tNode);
  17151. if (matchedDirectiveDefs !== null) {
  17152. let directiveDefs;
  17153. let hostDirectiveDefs = null;
  17154. let hostDirectiveRanges = null;
  17155. const hostDirectiveResolution = resolveHostDirectives(matchedDirectiveDefs);
  17156. if (hostDirectiveResolution === null) {
  17157. directiveDefs = matchedDirectiveDefs;
  17158. }
  17159. else {
  17160. [directiveDefs, hostDirectiveDefs, hostDirectiveRanges] = hostDirectiveResolution;
  17161. }
  17162. initializeDirectives(tView, lView, tNode, directiveDefs, exportsMap, hostDirectiveDefs, hostDirectiveRanges);
  17163. }
  17164. if (exportsMap !== null && localRefs !== null) {
  17165. cacheMatchingLocalNames(tNode, localRefs, exportsMap);
  17166. }
  17167. }
  17168. /** Caches local names and their matching directive indices for query and template lookups. */
  17169. function cacheMatchingLocalNames(tNode, localRefs, exportsMap) {
  17170. const localNames = (tNode.localNames = []);
  17171. // Local names must be stored in tNode in the same order that localRefs are defined
  17172. // in the template to ensure the data is loaded in the same slots as their refs
  17173. // in the template (for template queries).
  17174. for (let i = 0; i < localRefs.length; i += 2) {
  17175. const index = exportsMap[localRefs[i + 1]];
  17176. if (index == null)
  17177. throw new RuntimeError(-301 /* RuntimeErrorCode.EXPORT_NOT_FOUND */, ngDevMode && `Export of name '${localRefs[i + 1]}' not found!`);
  17178. localNames.push(localRefs[i], index);
  17179. }
  17180. }
  17181. function resolveHostDirectives(matches) {
  17182. let componentDef = null;
  17183. let hasHostDirectives = false;
  17184. for (let i = 0; i < matches.length; i++) {
  17185. const def = matches[i];
  17186. if (i === 0 && isComponentDef(def)) {
  17187. componentDef = def;
  17188. }
  17189. if (def.findHostDirectiveDefs !== null) {
  17190. hasHostDirectives = true;
  17191. break;
  17192. }
  17193. }
  17194. if (!hasHostDirectives) {
  17195. return null;
  17196. }
  17197. let allDirectiveDefs = null;
  17198. let hostDirectiveDefs = null;
  17199. let hostDirectiveRanges = null;
  17200. // Components are inserted at the front of the matches array so that their lifecycle
  17201. // hooks run before any directive lifecycle hooks. This appears to be for ViewEngine
  17202. // compatibility. This logic doesn't make sense with host directives, because it
  17203. // would allow the host directives to undo any overrides the host may have made.
  17204. // To handle this case, the host directives of components are inserted at the beginning
  17205. // of the array, followed by the component. As such, the insertion order is as follows:
  17206. // 1. Host directives belonging to the selector-matched component.
  17207. // 2. Selector-matched component.
  17208. // 3. Host directives belonging to selector-matched directives.
  17209. // 4. Selector-matched dir
  17210. for (const def of matches) {
  17211. if (def.findHostDirectiveDefs !== null) {
  17212. allDirectiveDefs ??= [];
  17213. hostDirectiveDefs ??= new Map();
  17214. hostDirectiveRanges ??= new Map();
  17215. resolveHostDirectivesForDef(def, allDirectiveDefs, hostDirectiveRanges, hostDirectiveDefs);
  17216. }
  17217. // Component definition needs to be pushed early to maintain the correct ordering.
  17218. if (def === componentDef) {
  17219. allDirectiveDefs ??= [];
  17220. allDirectiveDefs.push(def);
  17221. }
  17222. }
  17223. if (allDirectiveDefs !== null) {
  17224. allDirectiveDefs.push(...(componentDef === null ? matches : matches.slice(1)));
  17225. ngDevMode && assertNoDuplicateDirectives(allDirectiveDefs);
  17226. return [allDirectiveDefs, hostDirectiveDefs, hostDirectiveRanges];
  17227. }
  17228. return null;
  17229. }
  17230. function resolveHostDirectivesForDef(def, allDirectiveDefs, hostDirectiveRanges, hostDirectiveDefs) {
  17231. ngDevMode && assertDefined(def.findHostDirectiveDefs, 'Expected host directive resolve function');
  17232. const start = allDirectiveDefs.length;
  17233. // TODO(pk): probably could return matches instead of taking in an array to fill in?
  17234. def.findHostDirectiveDefs(def, allDirectiveDefs, hostDirectiveDefs);
  17235. // Note that these indexes are within the offset by `directiveStart`. We can't do the
  17236. // offsetting here, because `directiveStart` hasn't been initialized on the TNode yet.
  17237. hostDirectiveRanges.set(def, [start, allDirectiveDefs.length - 1]);
  17238. }
  17239. /**
  17240. * Marks a given TNode as a component's host. This consists of:
  17241. * - setting the component offset on the TNode.
  17242. * - storing index of component's host element so it will be queued for view refresh during CD.
  17243. */
  17244. function markAsComponentHost(tView, hostTNode, componentOffset) {
  17245. ngDevMode && assertFirstCreatePass(tView);
  17246. ngDevMode && assertGreaterThan(componentOffset, -1, 'componentOffset must be great than -1');
  17247. hostTNode.componentOffset = componentOffset;
  17248. (tView.components ??= []).push(hostTNode.index);
  17249. }
  17250. /** Initializes the data structures necessary for a list of directives to be instantiated. */
  17251. function initializeDirectives(tView, lView, tNode, directives, exportsMap, hostDirectiveDefs, hostDirectiveRanges) {
  17252. ngDevMode && assertFirstCreatePass(tView);
  17253. const directivesLength = directives.length;
  17254. let hasSeenComponent = false;
  17255. // Publishes the directive types to DI so they can be injected. Needs to
  17256. // happen in a separate pass before the TNode flags have been initialized.
  17257. for (let i = 0; i < directivesLength; i++) {
  17258. const def = directives[i];
  17259. if (!hasSeenComponent && isComponentDef(def)) {
  17260. hasSeenComponent = true;
  17261. markAsComponentHost(tView, tNode, i);
  17262. }
  17263. diPublicInInjector(getOrCreateNodeInjectorForNode(tNode, lView), tView, def.type);
  17264. }
  17265. initTNodeFlags(tNode, tView.data.length, directivesLength);
  17266. // When the same token is provided by several directives on the same node, some rules apply in
  17267. // the viewEngine:
  17268. // - viewProviders have priority over providers
  17269. // - the last directive in NgModule.declarations has priority over the previous one
  17270. // So to match these rules, the order in which providers are added in the arrays is very
  17271. // important.
  17272. for (let i = 0; i < directivesLength; i++) {
  17273. const def = directives[i];
  17274. if (def.providersResolver)
  17275. def.providersResolver(def);
  17276. }
  17277. let preOrderHooksFound = false;
  17278. let preOrderCheckHooksFound = false;
  17279. let directiveIdx = allocExpando(tView, lView, directivesLength, null);
  17280. ngDevMode &&
  17281. assertSame(directiveIdx, tNode.directiveStart, 'TNode.directiveStart should point to just allocated space');
  17282. // If there's at least one directive, we'll have to track it so initialize the map.
  17283. if (directivesLength > 0) {
  17284. tNode.directiveToIndex = new Map();
  17285. }
  17286. for (let i = 0; i < directivesLength; i++) {
  17287. const def = directives[i];
  17288. // Merge the attrs in the order of matches. This assumes that the first directive is the
  17289. // component itself, so that the component has the least priority.
  17290. tNode.mergedAttrs = mergeHostAttrs(tNode.mergedAttrs, def.hostAttrs);
  17291. configureViewWithDirective(tView, tNode, lView, directiveIdx, def);
  17292. saveNameToExportMap(directiveIdx, def, exportsMap);
  17293. // If a directive has host directives, we need to track both its index and the range within
  17294. // the host directives are declared. Host directives are not tracked, but should be resolved
  17295. // by looking up the host and getting its indexes from there.
  17296. if (hostDirectiveRanges !== null && hostDirectiveRanges.has(def)) {
  17297. const [start, end] = hostDirectiveRanges.get(def);
  17298. tNode.directiveToIndex.set(def.type, [
  17299. directiveIdx,
  17300. start + tNode.directiveStart,
  17301. end + tNode.directiveStart,
  17302. ]);
  17303. }
  17304. else if (hostDirectiveDefs === null || !hostDirectiveDefs.has(def)) {
  17305. tNode.directiveToIndex.set(def.type, directiveIdx);
  17306. }
  17307. if (def.contentQueries !== null)
  17308. tNode.flags |= 4 /* TNodeFlags.hasContentQuery */;
  17309. if (def.hostBindings !== null || def.hostAttrs !== null || def.hostVars !== 0)
  17310. tNode.flags |= 64 /* TNodeFlags.hasHostBindings */;
  17311. const lifeCycleHooks = def.type.prototype;
  17312. // Only push a node index into the preOrderHooks array if this is the first
  17313. // pre-order hook found on this node.
  17314. if (!preOrderHooksFound &&
  17315. (lifeCycleHooks.ngOnChanges || lifeCycleHooks.ngOnInit || lifeCycleHooks.ngDoCheck)) {
  17316. // We will push the actual hook function into this array later during dir instantiation.
  17317. // We cannot do it now because we must ensure hooks are registered in the same
  17318. // order that directives are created (i.e. injection order).
  17319. (tView.preOrderHooks ??= []).push(tNode.index);
  17320. preOrderHooksFound = true;
  17321. }
  17322. if (!preOrderCheckHooksFound && (lifeCycleHooks.ngOnChanges || lifeCycleHooks.ngDoCheck)) {
  17323. (tView.preOrderCheckHooks ??= []).push(tNode.index);
  17324. preOrderCheckHooksFound = true;
  17325. }
  17326. directiveIdx++;
  17327. }
  17328. initializeInputAndOutputAliases(tView, tNode, hostDirectiveDefs);
  17329. }
  17330. /**
  17331. * Initializes data structures required to work with directive inputs and outputs.
  17332. * Initialization is done for all directives matched on a given TNode.
  17333. */
  17334. function initializeInputAndOutputAliases(tView, tNode, hostDirectiveDefs) {
  17335. ngDevMode && assertFirstCreatePass(tView);
  17336. for (let index = tNode.directiveStart; index < tNode.directiveEnd; index++) {
  17337. const directiveDef = tView.data[index];
  17338. if (hostDirectiveDefs === null || !hostDirectiveDefs.has(directiveDef)) {
  17339. setupSelectorMatchedInputsOrOutputs(0 /* BindingType.Inputs */, tNode, directiveDef, index);
  17340. setupSelectorMatchedInputsOrOutputs(1 /* BindingType.Outputs */, tNode, directiveDef, index);
  17341. setupInitialInputs(tNode, index, false);
  17342. }
  17343. else {
  17344. const hostDirectiveDef = hostDirectiveDefs.get(directiveDef);
  17345. setupHostDirectiveInputsOrOutputs(0 /* BindingType.Inputs */, tNode, hostDirectiveDef, index);
  17346. setupHostDirectiveInputsOrOutputs(1 /* BindingType.Outputs */, tNode, hostDirectiveDef, index);
  17347. setupInitialInputs(tNode, index, true);
  17348. }
  17349. }
  17350. }
  17351. /**
  17352. * Sets up the input/output bindings for a directive that was matched in the template through its
  17353. * selector. This method is called repeatedly to build up all of the available inputs on a node.
  17354. *
  17355. * @param mode Whether inputs or outputs are being contructed.
  17356. * @param tNode Node on which the bindings are being set up.
  17357. * @param def Directive definition for which the bindings are being set up.
  17358. * @param directiveIndex Index at which the directive instance will be stored in the LView.
  17359. */
  17360. function setupSelectorMatchedInputsOrOutputs(mode, tNode, def, directiveIndex) {
  17361. const aliasMap = mode === 0 /* BindingType.Inputs */ ? def.inputs : def.outputs;
  17362. for (const publicName in aliasMap) {
  17363. if (aliasMap.hasOwnProperty(publicName)) {
  17364. let bindings;
  17365. if (mode === 0 /* BindingType.Inputs */) {
  17366. bindings = tNode.inputs ??= {};
  17367. }
  17368. else {
  17369. bindings = tNode.outputs ??= {};
  17370. }
  17371. bindings[publicName] ??= [];
  17372. bindings[publicName].push(directiveIndex);
  17373. setShadowStylingInputFlags(tNode, publicName);
  17374. }
  17375. }
  17376. }
  17377. /**
  17378. * Sets up input/output bindings that were defined through host directives on a specific node.
  17379. * @param mode Whether inputs or outputs are being contructed.
  17380. * @param tNode Node on which the bindings are being set up.
  17381. * @param config Host directive definition that is being set up.
  17382. * @param directiveIndex Index at which the directive instance will be stored in the LView.
  17383. */
  17384. function setupHostDirectiveInputsOrOutputs(mode, tNode, config, directiveIndex) {
  17385. const aliasMap = mode === 0 /* BindingType.Inputs */ ? config.inputs : config.outputs;
  17386. for (const initialName in aliasMap) {
  17387. if (aliasMap.hasOwnProperty(initialName)) {
  17388. const publicName = aliasMap[initialName];
  17389. let bindings;
  17390. if (mode === 0 /* BindingType.Inputs */) {
  17391. bindings = tNode.hostDirectiveInputs ??= {};
  17392. }
  17393. else {
  17394. bindings = tNode.hostDirectiveOutputs ??= {};
  17395. }
  17396. bindings[publicName] ??= [];
  17397. bindings[publicName].push(directiveIndex, initialName);
  17398. setShadowStylingInputFlags(tNode, publicName);
  17399. }
  17400. }
  17401. }
  17402. function setShadowStylingInputFlags(tNode, publicName) {
  17403. if (publicName === 'class') {
  17404. tNode.flags |= 8 /* TNodeFlags.hasClassInput */;
  17405. }
  17406. else if (publicName === 'style') {
  17407. tNode.flags |= 16 /* TNodeFlags.hasStyleInput */;
  17408. }
  17409. }
  17410. /**
  17411. * Sets up the initialInputData for a node and stores it in the template's static storage
  17412. * so subsequent template invocations don't have to recalculate it.
  17413. *
  17414. * initialInputData is an array containing values that need to be set as input properties
  17415. * for directives on this node, but only once on creation. We need this array to support
  17416. * the case where you set an @Input property of a directive using attribute-like syntax.
  17417. * e.g. if you have a `name` @Input, you can set it once like this:
  17418. *
  17419. * <my-component name="Bess"></my-component>
  17420. *
  17421. * @param tNode TNode on which to set up the initial inputs.
  17422. * @param directiveIndex Index of the directive that is currently being processed.
  17423. */
  17424. function setupInitialInputs(tNode, directiveIndex, isHostDirective) {
  17425. const { attrs, inputs, hostDirectiveInputs } = tNode;
  17426. if (attrs === null ||
  17427. (!isHostDirective && inputs === null) ||
  17428. (isHostDirective && hostDirectiveInputs === null) ||
  17429. // Do not use unbound attributes as inputs to structural directives, since structural
  17430. // directive inputs can only be set using microsyntax (e.g. `<div *dir="exp">`).
  17431. isInlineTemplate(tNode)) {
  17432. tNode.initialInputs ??= [];
  17433. tNode.initialInputs.push(null);
  17434. return;
  17435. }
  17436. let inputsToStore = null;
  17437. let i = 0;
  17438. while (i < attrs.length) {
  17439. const attrName = attrs[i];
  17440. if (attrName === 0 /* AttributeMarker.NamespaceURI */) {
  17441. // We do not allow inputs on namespaced attributes.
  17442. i += 4;
  17443. continue;
  17444. }
  17445. else if (attrName === 5 /* AttributeMarker.ProjectAs */) {
  17446. // Skip over the `ngProjectAs` value.
  17447. i += 2;
  17448. continue;
  17449. }
  17450. else if (typeof attrName === 'number') {
  17451. // If we hit any other attribute markers, we're done anyway. None of those are valid inputs.
  17452. break;
  17453. }
  17454. if (!isHostDirective && inputs.hasOwnProperty(attrName)) {
  17455. // Find the input's public name from the input store. Note that we can be found easier
  17456. // through the directive def, but we want to do it using the inputs store so that it can
  17457. // account for host directive aliases.
  17458. const inputConfig = inputs[attrName];
  17459. for (const index of inputConfig) {
  17460. if (index === directiveIndex) {
  17461. inputsToStore ??= [];
  17462. inputsToStore.push(attrName, attrs[i + 1]);
  17463. // A directive can't have multiple inputs with the same name so we can break here.
  17464. break;
  17465. }
  17466. }
  17467. }
  17468. else if (isHostDirective && hostDirectiveInputs.hasOwnProperty(attrName)) {
  17469. const config = hostDirectiveInputs[attrName];
  17470. for (let j = 0; j < config.length; j += 2) {
  17471. if (config[j] === directiveIndex) {
  17472. inputsToStore ??= [];
  17473. inputsToStore.push(config[j + 1], attrs[i + 1]);
  17474. break;
  17475. }
  17476. }
  17477. }
  17478. i += 2;
  17479. }
  17480. tNode.initialInputs ??= [];
  17481. tNode.initialInputs.push(inputsToStore);
  17482. }
  17483. /**
  17484. * Setup directive for instantiation.
  17485. *
  17486. * We need to create a `NodeInjectorFactory` which is then inserted in both the `Blueprint` as well
  17487. * as `LView`. `TView` gets the `DirectiveDef`.
  17488. *
  17489. * @param tView `TView`
  17490. * @param tNode `TNode`
  17491. * @param lView `LView`
  17492. * @param directiveIndex Index where the directive will be stored in the Expando.
  17493. * @param def `DirectiveDef`
  17494. */
  17495. function configureViewWithDirective(tView, tNode, lView, directiveIndex, def) {
  17496. ngDevMode &&
  17497. assertGreaterThanOrEqual(directiveIndex, HEADER_OFFSET, 'Must be in Expando section');
  17498. tView.data[directiveIndex] = def;
  17499. const directiveFactory = def.factory || (def.factory = getFactoryDef(def.type, true));
  17500. // Even though `directiveFactory` will already be using `ɵɵdirectiveInject` in its generated code,
  17501. // we also want to support `inject()` directly from the directive constructor context so we set
  17502. // `ɵɵdirectiveInject` as the inject implementation here too.
  17503. const nodeInjectorFactory = new NodeInjectorFactory(directiveFactory, isComponentDef(def), ɵɵdirectiveInject);
  17504. tView.blueprint[directiveIndex] = nodeInjectorFactory;
  17505. lView[directiveIndex] = nodeInjectorFactory;
  17506. registerHostBindingOpCodes(tView, tNode, directiveIndex, allocExpando(tView, lView, def.hostVars, NO_CHANGE), def);
  17507. }
  17508. /**
  17509. * Add `hostBindings` to the `TView.hostBindingOpCodes`.
  17510. *
  17511. * @param tView `TView` to which the `hostBindings` should be added.
  17512. * @param tNode `TNode` the element which contains the directive
  17513. * @param directiveIdx Directive index in view.
  17514. * @param directiveVarsIdx Where will the directive's vars be stored
  17515. * @param def `ComponentDef`/`DirectiveDef`, which contains the `hostVars`/`hostBindings` to add.
  17516. */
  17517. function registerHostBindingOpCodes(tView, tNode, directiveIdx, directiveVarsIdx, def) {
  17518. ngDevMode && assertFirstCreatePass(tView);
  17519. const hostBindings = def.hostBindings;
  17520. if (hostBindings) {
  17521. let hostBindingOpCodes = tView.hostBindingOpCodes;
  17522. if (hostBindingOpCodes === null) {
  17523. hostBindingOpCodes = tView.hostBindingOpCodes = [];
  17524. }
  17525. const elementIndx = ~tNode.index;
  17526. if (lastSelectedElementIdx(hostBindingOpCodes) != elementIndx) {
  17527. // Conditionally add select element so that we are more efficient in execution.
  17528. // NOTE: this is strictly not necessary and it trades code size for runtime perf.
  17529. // (We could just always add it.)
  17530. hostBindingOpCodes.push(elementIndx);
  17531. }
  17532. hostBindingOpCodes.push(directiveIdx, directiveVarsIdx, hostBindings);
  17533. }
  17534. }
  17535. /**
  17536. * Returns the last selected element index in the `HostBindingOpCodes`
  17537. *
  17538. * For perf reasons we don't need to update the selected element index in `HostBindingOpCodes` only
  17539. * if it changes. This method returns the last index (or '0' if not found.)
  17540. *
  17541. * Selected element index are only the ones which are negative.
  17542. */
  17543. function lastSelectedElementIdx(hostBindingOpCodes) {
  17544. let i = hostBindingOpCodes.length;
  17545. while (i > 0) {
  17546. const value = hostBindingOpCodes[--i];
  17547. if (typeof value === 'number' && value < 0) {
  17548. return value;
  17549. }
  17550. }
  17551. return 0;
  17552. }
  17553. /**
  17554. * Builds up an export map as directives are created, so local refs can be quickly mapped
  17555. * to their directive instances.
  17556. */
  17557. function saveNameToExportMap(directiveIdx, def, exportsMap) {
  17558. if (exportsMap) {
  17559. if (def.exportAs) {
  17560. for (let i = 0; i < def.exportAs.length; i++) {
  17561. exportsMap[def.exportAs[i]] = directiveIdx;
  17562. }
  17563. }
  17564. if (isComponentDef(def))
  17565. exportsMap[''] = directiveIdx;
  17566. }
  17567. }
  17568. /**
  17569. * Initializes the flags on the current node, setting all indices to the initial index,
  17570. * the directive count to 0, and adding the isComponent flag.
  17571. * @param index the initial index
  17572. */
  17573. function initTNodeFlags(tNode, index, numberOfDirectives) {
  17574. ngDevMode &&
  17575. assertNotEqual(numberOfDirectives, tNode.directiveEnd - tNode.directiveStart, 'Reached the max number of directives');
  17576. tNode.flags |= 1 /* TNodeFlags.isDirectiveHost */;
  17577. // When the first directive is created on a node, save the index
  17578. tNode.directiveStart = index;
  17579. tNode.directiveEnd = index + numberOfDirectives;
  17580. tNode.providerIndexes = index;
  17581. }
  17582. function assertNoDuplicateDirectives(directives) {
  17583. // The array needs at least two elements in order to have duplicates.
  17584. if (directives.length < 2) {
  17585. return;
  17586. }
  17587. const seenDirectives = new Set();
  17588. for (const current of directives) {
  17589. if (seenDirectives.has(current)) {
  17590. throw new RuntimeError(309 /* RuntimeErrorCode.DUPLICATE_DIRECTIVE */, `Directive ${current.type.name} matches multiple times on the same element. ` +
  17591. `Directives can only match an element once.`);
  17592. }
  17593. seenDirectives.add(current);
  17594. }
  17595. }
  17596. function elementStartFirstCreatePass(index, tView, lView, name, directiveMatcher, bindingsEnabled, attrsIndex, localRefsIndex) {
  17597. ngDevMode && assertFirstCreatePass(tView);
  17598. ngDevMode && ngDevMode.firstCreatePass++;
  17599. const tViewConsts = tView.consts;
  17600. const attrs = getConstant(tViewConsts, attrsIndex);
  17601. const tNode = getOrCreateTNode(tView, index, 2 /* TNodeType.Element */, name, attrs);
  17602. if (bindingsEnabled) {
  17603. resolveDirectives(tView, lView, tNode, getConstant(tViewConsts, localRefsIndex), directiveMatcher);
  17604. }
  17605. // Merge the template attrs last so that they have the highest priority.
  17606. tNode.mergedAttrs = mergeHostAttrs(tNode.mergedAttrs, tNode.attrs);
  17607. if (tNode.attrs !== null) {
  17608. computeStaticStyling(tNode, tNode.attrs, false);
  17609. }
  17610. if (tNode.mergedAttrs !== null) {
  17611. computeStaticStyling(tNode, tNode.mergedAttrs, true);
  17612. }
  17613. if (tView.queries !== null) {
  17614. tView.queries.elementStart(tView, tNode);
  17615. }
  17616. return tNode;
  17617. }
  17618. function elementEndFirstCreatePass(tView, tNode) {
  17619. ngDevMode && assertFirstCreatePass(tView);
  17620. registerPostOrderHooks(tView, tNode);
  17621. if (isContentQueryHost(tNode)) {
  17622. tView.queries.elementEnd(tNode);
  17623. }
  17624. }
  17625. class ComponentFactoryResolver extends ComponentFactoryResolver$1 {
  17626. ngModule;
  17627. /**
  17628. * @param ngModule The NgModuleRef to which all resolved factories are bound.
  17629. */
  17630. constructor(ngModule) {
  17631. super();
  17632. this.ngModule = ngModule;
  17633. }
  17634. resolveComponentFactory(component) {
  17635. ngDevMode && assertComponentType(component);
  17636. const componentDef = getComponentDef(component);
  17637. return new ComponentFactory(componentDef, this.ngModule);
  17638. }
  17639. }
  17640. function toInputRefArray(map) {
  17641. return Object.keys(map).map((name) => {
  17642. const [propName, flags, transform] = map[name];
  17643. const inputData = {
  17644. propName: propName,
  17645. templateName: name,
  17646. isSignal: (flags & InputFlags.SignalBased) !== 0,
  17647. };
  17648. if (transform) {
  17649. inputData.transform = transform;
  17650. }
  17651. return inputData;
  17652. });
  17653. }
  17654. function toOutputRefArray(map) {
  17655. return Object.keys(map).map((name) => ({ propName: map[name], templateName: name }));
  17656. }
  17657. function verifyNotAnOrphanComponent(componentDef) {
  17658. // TODO(pk): create assert that verifies ngDevMode
  17659. if ((typeof ngJitMode === 'undefined' || ngJitMode) &&
  17660. componentDef.debugInfo?.forbidOrphanRendering) {
  17661. if (depsTracker.isOrphanComponent(componentDef.type)) {
  17662. throw new RuntimeError(981 /* RuntimeErrorCode.RUNTIME_DEPS_ORPHAN_COMPONENT */, `Orphan component found! Trying to render the component ${debugStringifyTypeForError(componentDef.type)} without first loading the NgModule that declares it. It is recommended to make this component standalone in order to avoid this error. If this is not possible now, import the component's NgModule in the appropriate NgModule, or the standalone component in which you are trying to render this component. If this is a lazy import, load the NgModule lazily as well and use its module injector.`);
  17663. }
  17664. }
  17665. }
  17666. function createRootViewInjector(componentDef, environmentInjector, injector) {
  17667. let realEnvironmentInjector = environmentInjector instanceof EnvironmentInjector
  17668. ? environmentInjector
  17669. : environmentInjector?.injector;
  17670. if (realEnvironmentInjector && componentDef.getStandaloneInjector !== null) {
  17671. realEnvironmentInjector =
  17672. componentDef.getStandaloneInjector(realEnvironmentInjector) || realEnvironmentInjector;
  17673. }
  17674. const rootViewInjector = realEnvironmentInjector
  17675. ? new ChainedInjector(injector, realEnvironmentInjector)
  17676. : injector;
  17677. return rootViewInjector;
  17678. }
  17679. function createRootLViewEnvironment(rootLViewInjector) {
  17680. const rendererFactory = rootLViewInjector.get(RendererFactory2, null);
  17681. if (rendererFactory === null) {
  17682. throw new RuntimeError(407 /* RuntimeErrorCode.RENDERER_NOT_FOUND */, ngDevMode &&
  17683. 'Angular was not able to inject a renderer (RendererFactory2). ' +
  17684. 'Likely this is due to a broken DI hierarchy. ' +
  17685. 'Make sure that any injector used to create this component has a correct parent.');
  17686. }
  17687. const sanitizer = rootLViewInjector.get(Sanitizer, null);
  17688. const changeDetectionScheduler = rootLViewInjector.get(ChangeDetectionScheduler, null);
  17689. return {
  17690. rendererFactory,
  17691. sanitizer,
  17692. changeDetectionScheduler,
  17693. };
  17694. }
  17695. function createHostElement(componentDef, render) {
  17696. // Determine a tag name used for creating host elements when this component is created
  17697. // dynamically. Default to 'div' if this component did not specify any tag name in its
  17698. // selector.
  17699. const tagName = (componentDef.selectors[0][0] || 'div').toLowerCase();
  17700. const namespace = tagName === 'svg' ? SVG_NAMESPACE : tagName === 'math' ? MATH_ML_NAMESPACE : null;
  17701. return createElementNode(render, tagName, namespace);
  17702. }
  17703. /**
  17704. * ComponentFactory interface implementation.
  17705. */
  17706. class ComponentFactory extends ComponentFactory$1 {
  17707. componentDef;
  17708. ngModule;
  17709. selector;
  17710. componentType;
  17711. ngContentSelectors;
  17712. isBoundToModule;
  17713. cachedInputs = null;
  17714. cachedOutputs = null;
  17715. get inputs() {
  17716. this.cachedInputs ??= toInputRefArray(this.componentDef.inputs);
  17717. return this.cachedInputs;
  17718. }
  17719. get outputs() {
  17720. this.cachedOutputs ??= toOutputRefArray(this.componentDef.outputs);
  17721. return this.cachedOutputs;
  17722. }
  17723. /**
  17724. * @param componentDef The component definition.
  17725. * @param ngModule The NgModuleRef to which the factory is bound.
  17726. */
  17727. constructor(componentDef, ngModule) {
  17728. super();
  17729. this.componentDef = componentDef;
  17730. this.ngModule = ngModule;
  17731. this.componentType = componentDef.type;
  17732. this.selector = stringifyCSSSelectorList(componentDef.selectors);
  17733. this.ngContentSelectors = componentDef.ngContentSelectors ?? [];
  17734. this.isBoundToModule = !!ngModule;
  17735. }
  17736. create(injector, projectableNodes, rootSelectorOrNode, environmentInjector) {
  17737. profiler(22 /* ProfilerEvent.DynamicComponentStart */);
  17738. const prevConsumer = setActiveConsumer$1(null);
  17739. try {
  17740. const cmpDef = this.componentDef;
  17741. ngDevMode && verifyNotAnOrphanComponent(cmpDef);
  17742. const tAttributes = rootSelectorOrNode
  17743. ? ['ng-version', '19.2.4']
  17744. : // Extract attributes and classes from the first selector only to match VE behavior.
  17745. extractAttrsAndClassesFromSelector(this.componentDef.selectors[0]);
  17746. // Create the root view. Uses empty TView and ContentTemplate.
  17747. const rootTView = createTView(0 /* TViewType.Root */, null, null, 1, 0, null, null, null, null, [tAttributes], null);
  17748. const rootViewInjector = createRootViewInjector(cmpDef, environmentInjector || this.ngModule, injector);
  17749. const environment = createRootLViewEnvironment(rootViewInjector);
  17750. const hostRenderer = environment.rendererFactory.createRenderer(null, cmpDef);
  17751. const hostElement = rootSelectorOrNode
  17752. ? locateHostElement(hostRenderer, rootSelectorOrNode, cmpDef.encapsulation, rootViewInjector)
  17753. : createHostElement(cmpDef, hostRenderer);
  17754. const rootLView = createLView(null, rootTView, null, 512 /* LViewFlags.IsRoot */ | getInitialLViewFlagsFromDef(cmpDef), null, null, environment, hostRenderer, rootViewInjector, null, retrieveHydrationInfo(hostElement, rootViewInjector, true /* isRootView */));
  17755. rootLView[HEADER_OFFSET] = hostElement;
  17756. // rootView is the parent when bootstrapping
  17757. // TODO(misko): it looks like we are entering view here but we don't really need to as
  17758. // `renderView` does that. However as the code is written it is needed because
  17759. // `createRootComponentView` and `createRootComponent` both read global state. Fixing those
  17760. // issues would allow us to drop this.
  17761. enterView(rootLView);
  17762. let componentView = null;
  17763. try {
  17764. const hostTNode = elementStartFirstCreatePass(HEADER_OFFSET, rootTView, rootLView, '#host', () => [this.componentDef], true, 0);
  17765. // ---- element instruction
  17766. // TODO(crisbeto): in practice `hostRNode` should always be defined, but there are some
  17767. // tests where the renderer is mocked out and `undefined` is returned. We should update the
  17768. // tests so that this check can be removed.
  17769. if (hostElement) {
  17770. setupStaticAttributes(hostRenderer, hostElement, hostTNode);
  17771. attachPatchData(hostElement, rootLView);
  17772. }
  17773. // TODO(pk): this logic is similar to the instruction code where a node can have directives
  17774. createDirectivesInstances(rootTView, rootLView, hostTNode);
  17775. executeContentQueries(rootTView, hostTNode, rootLView);
  17776. elementEndFirstCreatePass(rootTView, hostTNode);
  17777. if (projectableNodes !== undefined) {
  17778. projectNodes(hostTNode, this.ngContentSelectors, projectableNodes);
  17779. }
  17780. componentView = getComponentLViewByIndex(hostTNode.index, rootLView);
  17781. // TODO(pk): why do we need this logic?
  17782. rootLView[CONTEXT] = componentView[CONTEXT];
  17783. renderView(rootTView, rootLView, null);
  17784. }
  17785. catch (e) {
  17786. // Stop tracking the views if creation failed since
  17787. // the consumer won't have a way to dereference them.
  17788. if (componentView !== null) {
  17789. unregisterLView(componentView);
  17790. }
  17791. unregisterLView(rootLView);
  17792. throw e;
  17793. }
  17794. finally {
  17795. profiler(23 /* ProfilerEvent.DynamicComponentEnd */);
  17796. leaveView();
  17797. }
  17798. return new ComponentRef(this.componentType, rootLView);
  17799. }
  17800. finally {
  17801. setActiveConsumer$1(prevConsumer);
  17802. }
  17803. }
  17804. }
  17805. /**
  17806. * Represents an instance of a Component created via a {@link ComponentFactory}.
  17807. *
  17808. * `ComponentRef` provides access to the Component Instance as well other objects related to this
  17809. * Component Instance and allows you to destroy the Component Instance via the {@link #destroy}
  17810. * method.
  17811. *
  17812. */
  17813. class ComponentRef extends ComponentRef$1 {
  17814. _rootLView;
  17815. instance;
  17816. hostView;
  17817. changeDetectorRef;
  17818. componentType;
  17819. location;
  17820. previousInputValues = null;
  17821. _tNode;
  17822. constructor(componentType, _rootLView) {
  17823. super();
  17824. this._rootLView = _rootLView;
  17825. this._tNode = getTNode(_rootLView[TVIEW], HEADER_OFFSET);
  17826. this.location = createElementRef(this._tNode, _rootLView);
  17827. this.instance = getComponentLViewByIndex(this._tNode.index, _rootLView)[CONTEXT];
  17828. this.hostView = this.changeDetectorRef = new ViewRef$1(_rootLView, undefined /* _cdRefInjectingView */, false /* notifyErrorHandler */);
  17829. this.componentType = componentType;
  17830. }
  17831. setInput(name, value) {
  17832. const tNode = this._tNode;
  17833. this.previousInputValues ??= new Map();
  17834. // Do not set the input if it is the same as the last value
  17835. // This behavior matches `bindingUpdated` when binding inputs in templates.
  17836. if (this.previousInputValues.has(name) &&
  17837. Object.is(this.previousInputValues.get(name), value)) {
  17838. return;
  17839. }
  17840. const lView = this._rootLView;
  17841. const hasSetInput = setAllInputsForProperty(tNode, lView[TVIEW], lView, name, value);
  17842. this.previousInputValues.set(name, value);
  17843. const childComponentLView = getComponentLViewByIndex(tNode.index, lView);
  17844. markViewDirty(childComponentLView, 1 /* NotificationSource.SetInput */);
  17845. if (ngDevMode && !hasSetInput) {
  17846. const cmpNameForError = stringifyForError(this.componentType);
  17847. let message = `Can't set value of the '${name}' input on the '${cmpNameForError}' component. `;
  17848. message += `Make sure that the '${name}' property is annotated with @Input() or a mapped @Input('${name}') exists.`;
  17849. reportUnknownPropertyError(message);
  17850. }
  17851. }
  17852. get injector() {
  17853. return new NodeInjector(this._tNode, this._rootLView);
  17854. }
  17855. destroy() {
  17856. this.hostView.destroy();
  17857. }
  17858. onDestroy(callback) {
  17859. this.hostView.onDestroy(callback);
  17860. }
  17861. }
  17862. /** Projects the `projectableNodes` that were specified when creating a root component. */
  17863. function projectNodes(tNode, ngContentSelectors, projectableNodes) {
  17864. const projection = (tNode.projection = []);
  17865. for (let i = 0; i < ngContentSelectors.length; i++) {
  17866. const nodesforSlot = projectableNodes[i];
  17867. // Projectable nodes can be passed as array of arrays or an array of iterables (ngUpgrade
  17868. // case). Here we do normalize passed data structure to be an array of arrays to avoid
  17869. // complex checks down the line.
  17870. // We also normalize the length of the passed in projectable nodes (to match the number of
  17871. // <ng-container> slots defined by a component).
  17872. projection.push(nodesforSlot != null && nodesforSlot.length ? Array.from(nodesforSlot) : null);
  17873. }
  17874. }
  17875. /**
  17876. * Represents a container where one or more views can be attached to a component.
  17877. *
  17878. * Can contain *host views* (created by instantiating a
  17879. * component with the `createComponent()` method), and *embedded views*
  17880. * (created by instantiating a `TemplateRef` with the `createEmbeddedView()` method).
  17881. *
  17882. * A view container instance can contain other view containers,
  17883. * creating a view hierarchy.
  17884. *
  17885. * @usageNotes
  17886. *
  17887. * The example below demonstrates how the `createComponent` function can be used
  17888. * to create an instance of a ComponentRef dynamically and attach it to an ApplicationRef,
  17889. * so that it gets included into change detection cycles.
  17890. *
  17891. * Note: the example uses standalone components, but the function can also be used for
  17892. * non-standalone components (declared in an NgModule) as well.
  17893. *
  17894. * ```angular-ts
  17895. * @Component({
  17896. * standalone: true,
  17897. * selector: 'dynamic',
  17898. * template: `<span>This is a content of a dynamic component.</span>`,
  17899. * })
  17900. * class DynamicComponent {
  17901. * vcr = inject(ViewContainerRef);
  17902. * }
  17903. *
  17904. * @Component({
  17905. * standalone: true,
  17906. * selector: 'app',
  17907. * template: `<main>Hi! This is the main content.</main>`,
  17908. * })
  17909. * class AppComponent {
  17910. * vcr = inject(ViewContainerRef);
  17911. *
  17912. * ngAfterViewInit() {
  17913. * const compRef = this.vcr.createComponent(DynamicComponent);
  17914. * compRef.changeDetectorRef.detectChanges();
  17915. * }
  17916. * }
  17917. * ```
  17918. *
  17919. * @see {@link ComponentRef}
  17920. * @see {@link EmbeddedViewRef}
  17921. *
  17922. * @publicApi
  17923. */
  17924. class ViewContainerRef {
  17925. /**
  17926. * @internal
  17927. * @nocollapse
  17928. */
  17929. static __NG_ELEMENT_ID__ = injectViewContainerRef;
  17930. }
  17931. /**
  17932. * Creates a ViewContainerRef and stores it on the injector. Or, if the ViewContainerRef
  17933. * already exists, retrieves the existing ViewContainerRef.
  17934. *
  17935. * @returns The ViewContainerRef instance to use
  17936. */
  17937. function injectViewContainerRef() {
  17938. const previousTNode = getCurrentTNode();
  17939. return createContainerRef(previousTNode, getLView());
  17940. }
  17941. const VE_ViewContainerRef = ViewContainerRef;
  17942. // TODO(alxhub): cleaning up this indirection triggers a subtle bug in Closure in g3. Once the fix
  17943. // for that lands, this can be cleaned up.
  17944. const R3ViewContainerRef = class ViewContainerRef extends VE_ViewContainerRef {
  17945. _lContainer;
  17946. _hostTNode;
  17947. _hostLView;
  17948. constructor(_lContainer, _hostTNode, _hostLView) {
  17949. super();
  17950. this._lContainer = _lContainer;
  17951. this._hostTNode = _hostTNode;
  17952. this._hostLView = _hostLView;
  17953. }
  17954. get element() {
  17955. return createElementRef(this._hostTNode, this._hostLView);
  17956. }
  17957. get injector() {
  17958. return new NodeInjector(this._hostTNode, this._hostLView);
  17959. }
  17960. /** @deprecated No replacement */
  17961. get parentInjector() {
  17962. const parentLocation = getParentInjectorLocation(this._hostTNode, this._hostLView);
  17963. if (hasParentInjector(parentLocation)) {
  17964. const parentView = getParentInjectorView(parentLocation, this._hostLView);
  17965. const injectorIndex = getParentInjectorIndex(parentLocation);
  17966. ngDevMode && assertNodeInjector(parentView, injectorIndex);
  17967. const parentTNode = parentView[TVIEW].data[injectorIndex + 8 /* NodeInjectorOffset.TNODE */];
  17968. return new NodeInjector(parentTNode, parentView);
  17969. }
  17970. else {
  17971. return new NodeInjector(null, this._hostLView);
  17972. }
  17973. }
  17974. clear() {
  17975. while (this.length > 0) {
  17976. this.remove(this.length - 1);
  17977. }
  17978. }
  17979. get(index) {
  17980. const viewRefs = getViewRefs(this._lContainer);
  17981. return (viewRefs !== null && viewRefs[index]) || null;
  17982. }
  17983. get length() {
  17984. return this._lContainer.length - CONTAINER_HEADER_OFFSET;
  17985. }
  17986. createEmbeddedView(templateRef, context, indexOrOptions) {
  17987. let index;
  17988. let injector;
  17989. if (typeof indexOrOptions === 'number') {
  17990. index = indexOrOptions;
  17991. }
  17992. else if (indexOrOptions != null) {
  17993. index = indexOrOptions.index;
  17994. injector = indexOrOptions.injector;
  17995. }
  17996. const dehydratedView = findMatchingDehydratedView(this._lContainer, templateRef.ssrId);
  17997. const viewRef = templateRef.createEmbeddedViewImpl(context || {}, injector, dehydratedView);
  17998. this.insertImpl(viewRef, index, shouldAddViewToDom(this._hostTNode, dehydratedView));
  17999. return viewRef;
  18000. }
  18001. createComponent(componentFactoryOrType, indexOrOptions, injector, projectableNodes, environmentInjector) {
  18002. const isComponentFactory = componentFactoryOrType && !isType(componentFactoryOrType);
  18003. let index;
  18004. // This function supports 2 signatures and we need to handle options correctly for both:
  18005. // 1. When first argument is a Component type. This signature also requires extra
  18006. // options to be provided as object (more ergonomic option).
  18007. // 2. First argument is a Component factory. In this case extra options are represented as
  18008. // positional arguments. This signature is less ergonomic and will be deprecated.
  18009. if (isComponentFactory) {
  18010. if (ngDevMode) {
  18011. assertEqual(typeof indexOrOptions !== 'object', true, 'It looks like Component factory was provided as the first argument ' +
  18012. 'and an options object as the second argument. This combination of arguments ' +
  18013. 'is incompatible. You can either change the first argument to provide Component ' +
  18014. 'type or change the second argument to be a number (representing an index at ' +
  18015. "which to insert the new component's host view into this container)");
  18016. }
  18017. index = indexOrOptions;
  18018. }
  18019. else {
  18020. if (ngDevMode) {
  18021. assertDefined(getComponentDef(componentFactoryOrType), `Provided Component class doesn't contain Component definition. ` +
  18022. `Please check whether provided class has @Component decorator.`);
  18023. assertEqual(typeof indexOrOptions !== 'number', true, 'It looks like Component type was provided as the first argument ' +
  18024. "and a number (representing an index at which to insert the new component's " +
  18025. 'host view into this container as the second argument. This combination of arguments ' +
  18026. 'is incompatible. Please use an object as the second argument instead.');
  18027. }
  18028. const options = (indexOrOptions || {});
  18029. if (ngDevMode && options.environmentInjector && options.ngModuleRef) {
  18030. throwError(`Cannot pass both environmentInjector and ngModuleRef options to createComponent().`);
  18031. }
  18032. index = options.index;
  18033. injector = options.injector;
  18034. projectableNodes = options.projectableNodes;
  18035. environmentInjector = options.environmentInjector || options.ngModuleRef;
  18036. }
  18037. const componentFactory = isComponentFactory
  18038. ? componentFactoryOrType
  18039. : new ComponentFactory(getComponentDef(componentFactoryOrType));
  18040. const contextInjector = injector || this.parentInjector;
  18041. // If an `NgModuleRef` is not provided explicitly, try retrieving it from the DI tree.
  18042. if (!environmentInjector && componentFactory.ngModule == null) {
  18043. // For the `ComponentFactory` case, entering this logic is very unlikely, since we expect that
  18044. // an instance of a `ComponentFactory`, resolved via `ComponentFactoryResolver` would have an
  18045. // `ngModule` field. This is possible in some test scenarios and potentially in some JIT-based
  18046. // use-cases. For the `ComponentFactory` case we preserve backwards-compatibility and try
  18047. // using a provided injector first, then fall back to the parent injector of this
  18048. // `ViewContainerRef` instance.
  18049. //
  18050. // For the factory-less case, it's critical to establish a connection with the module
  18051. // injector tree (by retrieving an instance of an `NgModuleRef` and accessing its injector),
  18052. // so that a component can use DI tokens provided in MgModules. For this reason, we can not
  18053. // rely on the provided injector, since it might be detached from the DI tree (for example, if
  18054. // it was created via `Injector.create` without specifying a parent injector, or if an
  18055. // injector is retrieved from an `NgModuleRef` created via `createNgModule` using an
  18056. // NgModule outside of a module tree). Instead, we always use `ViewContainerRef`'s parent
  18057. // injector, which is normally connected to the DI tree, which includes module injector
  18058. // subtree.
  18059. const _injector = isComponentFactory ? contextInjector : this.parentInjector;
  18060. // DO NOT REFACTOR. The code here used to have a `injector.get(NgModuleRef, null) ||
  18061. // undefined` expression which seems to cause internal google apps to fail. This is documented
  18062. // in the following internal bug issue: go/b/142967802
  18063. const result = _injector.get(EnvironmentInjector, null);
  18064. if (result) {
  18065. environmentInjector = result;
  18066. }
  18067. }
  18068. const componentDef = getComponentDef(componentFactory.componentType ?? {});
  18069. const dehydratedView = findMatchingDehydratedView(this._lContainer, componentDef?.id ?? null);
  18070. const rNode = dehydratedView?.firstChild ?? null;
  18071. const componentRef = componentFactory.create(contextInjector, projectableNodes, rNode, environmentInjector);
  18072. this.insertImpl(componentRef.hostView, index, shouldAddViewToDom(this._hostTNode, dehydratedView));
  18073. return componentRef;
  18074. }
  18075. insert(viewRef, index) {
  18076. return this.insertImpl(viewRef, index, true);
  18077. }
  18078. insertImpl(viewRef, index, addToDOM) {
  18079. const lView = viewRef._lView;
  18080. if (ngDevMode && viewRef.destroyed) {
  18081. throw new Error('Cannot insert a destroyed View in a ViewContainer!');
  18082. }
  18083. if (viewAttachedToContainer(lView)) {
  18084. // If view is already attached, detach it first so we clean up references appropriately.
  18085. const prevIdx = this.indexOf(viewRef);
  18086. // A view might be attached either to this or a different container. The `prevIdx` for
  18087. // those cases will be:
  18088. // equal to -1 for views attached to this ViewContainerRef
  18089. // >= 0 for views attached to a different ViewContainerRef
  18090. if (prevIdx !== -1) {
  18091. this.detach(prevIdx);
  18092. }
  18093. else {
  18094. const prevLContainer = lView[PARENT];
  18095. ngDevMode &&
  18096. assertEqual(isLContainer(prevLContainer), true, 'An attached view should have its PARENT point to a container.');
  18097. // We need to re-create a R3ViewContainerRef instance since those are not stored on
  18098. // LView (nor anywhere else).
  18099. const prevVCRef = new R3ViewContainerRef(prevLContainer, prevLContainer[T_HOST], prevLContainer[PARENT]);
  18100. prevVCRef.detach(prevVCRef.indexOf(viewRef));
  18101. }
  18102. }
  18103. // Logical operation of adding `LView` to `LContainer`
  18104. const adjustedIdx = this._adjustIndex(index);
  18105. const lContainer = this._lContainer;
  18106. addLViewToLContainer(lContainer, lView, adjustedIdx, addToDOM);
  18107. viewRef.attachToViewContainerRef();
  18108. addToArray(getOrCreateViewRefs(lContainer), adjustedIdx, viewRef);
  18109. return viewRef;
  18110. }
  18111. move(viewRef, newIndex) {
  18112. if (ngDevMode && viewRef.destroyed) {
  18113. throw new Error('Cannot move a destroyed View in a ViewContainer!');
  18114. }
  18115. return this.insert(viewRef, newIndex);
  18116. }
  18117. indexOf(viewRef) {
  18118. const viewRefsArr = getViewRefs(this._lContainer);
  18119. return viewRefsArr !== null ? viewRefsArr.indexOf(viewRef) : -1;
  18120. }
  18121. remove(index) {
  18122. const adjustedIdx = this._adjustIndex(index, -1);
  18123. const detachedView = detachView(this._lContainer, adjustedIdx);
  18124. if (detachedView) {
  18125. // Before destroying the view, remove it from the container's array of `ViewRef`s.
  18126. // This ensures the view container length is updated before calling
  18127. // `destroyLView`, which could recursively call view container methods that
  18128. // rely on an accurate container length.
  18129. // (e.g. a method on this view container being called by a child directive's OnDestroy
  18130. // lifecycle hook)
  18131. removeFromArray(getOrCreateViewRefs(this._lContainer), adjustedIdx);
  18132. destroyLView(detachedView[TVIEW], detachedView);
  18133. }
  18134. }
  18135. detach(index) {
  18136. const adjustedIdx = this._adjustIndex(index, -1);
  18137. const view = detachView(this._lContainer, adjustedIdx);
  18138. const wasDetached = view && removeFromArray(getOrCreateViewRefs(this._lContainer), adjustedIdx) != null;
  18139. return wasDetached ? new ViewRef$1(view) : null;
  18140. }
  18141. _adjustIndex(index, shift = 0) {
  18142. if (index == null) {
  18143. return this.length + shift;
  18144. }
  18145. if (ngDevMode) {
  18146. assertGreaterThan(index, -1, `ViewRef index must be positive, got ${index}`);
  18147. // +1 because it's legal to insert at the end.
  18148. assertLessThan(index, this.length + 1 + shift, 'index');
  18149. }
  18150. return index;
  18151. }
  18152. };
  18153. function getViewRefs(lContainer) {
  18154. return lContainer[VIEW_REFS];
  18155. }
  18156. function getOrCreateViewRefs(lContainer) {
  18157. return (lContainer[VIEW_REFS] || (lContainer[VIEW_REFS] = []));
  18158. }
  18159. /**
  18160. * Creates a ViewContainerRef and stores it on the injector.
  18161. *
  18162. * @param hostTNode The node that is requesting a ViewContainerRef
  18163. * @param hostLView The view to which the node belongs
  18164. * @returns The ViewContainerRef instance to use
  18165. */
  18166. function createContainerRef(hostTNode, hostLView) {
  18167. ngDevMode && assertTNodeType(hostTNode, 12 /* TNodeType.AnyContainer */ | 3 /* TNodeType.AnyRNode */);
  18168. let lContainer;
  18169. const slotValue = hostLView[hostTNode.index];
  18170. if (isLContainer(slotValue)) {
  18171. // If the host is a container, we don't need to create a new LContainer
  18172. lContainer = slotValue;
  18173. }
  18174. else {
  18175. // An LContainer anchor can not be `null`, but we set it here temporarily
  18176. // and update to the actual value later in this function (see
  18177. // `_locateOrCreateAnchorNode`).
  18178. lContainer = createLContainer(slotValue, hostLView, null, hostTNode);
  18179. hostLView[hostTNode.index] = lContainer;
  18180. addToEndOfViewTree(hostLView, lContainer);
  18181. }
  18182. _locateOrCreateAnchorNode(lContainer, hostLView, hostTNode, slotValue);
  18183. return new R3ViewContainerRef(lContainer, hostTNode, hostLView);
  18184. }
  18185. /**
  18186. * Creates and inserts a comment node that acts as an anchor for a view container.
  18187. *
  18188. * If the host is a regular element, we have to insert a comment node manually which will
  18189. * be used as an anchor when inserting elements. In this specific case we use low-level DOM
  18190. * manipulation to insert it.
  18191. */
  18192. function insertAnchorNode(hostLView, hostTNode) {
  18193. const renderer = hostLView[RENDERER];
  18194. ngDevMode && ngDevMode.rendererCreateComment++;
  18195. const commentNode = renderer.createComment(ngDevMode ? 'container' : '');
  18196. const hostNative = getNativeByTNode(hostTNode, hostLView);
  18197. const parentOfHostNative = renderer.parentNode(hostNative);
  18198. nativeInsertBefore(renderer, parentOfHostNative, commentNode, renderer.nextSibling(hostNative), false);
  18199. return commentNode;
  18200. }
  18201. let _locateOrCreateAnchorNode = createAnchorNode;
  18202. let _populateDehydratedViewsInLContainer = () => false; // noop by default
  18203. /**
  18204. * Looks up dehydrated views that belong to a given LContainer and populates
  18205. * this information into the `LContainer[DEHYDRATED_VIEWS]` slot. When running
  18206. * in client-only mode, this function is a noop.
  18207. *
  18208. * @param lContainer LContainer that should be populated.
  18209. * @param tNode Corresponding TNode.
  18210. * @param hostLView LView that hosts LContainer.
  18211. * @returns a boolean flag that indicates whether a populating operation
  18212. * was successful. The operation might be unsuccessful in case is has completed
  18213. * previously, we are rendering in client-only mode or this content is located
  18214. * in a skip hydration section.
  18215. */
  18216. function populateDehydratedViewsInLContainer(lContainer, tNode, hostLView) {
  18217. return _populateDehydratedViewsInLContainer(lContainer, tNode, hostLView);
  18218. }
  18219. /**
  18220. * Regular creation mode: an anchor is created and
  18221. * assigned to the `lContainer[NATIVE]` slot.
  18222. */
  18223. function createAnchorNode(lContainer, hostLView, hostTNode, slotValue) {
  18224. // We already have a native element (anchor) set, return.
  18225. if (lContainer[NATIVE])
  18226. return;
  18227. let commentNode;
  18228. // If the host is an element container, the native host element is guaranteed to be a
  18229. // comment and we can reuse that comment as anchor element for the new LContainer.
  18230. // The comment node in question is already part of the DOM structure so we don't need to append
  18231. // it again.
  18232. if (hostTNode.type & 8 /* TNodeType.ElementContainer */) {
  18233. commentNode = unwrapRNode(slotValue);
  18234. }
  18235. else {
  18236. commentNode = insertAnchorNode(hostLView, hostTNode);
  18237. }
  18238. lContainer[NATIVE] = commentNode;
  18239. }
  18240. /**
  18241. * Hydration logic that looks up all dehydrated views in this container
  18242. * and puts them into `lContainer[DEHYDRATED_VIEWS]` slot.
  18243. *
  18244. * @returns a boolean flag that indicates whether a populating operation
  18245. * was successful. The operation might be unsuccessful in case is has completed
  18246. * previously, we are rendering in client-only mode or this content is located
  18247. * in a skip hydration section.
  18248. */
  18249. function populateDehydratedViewsInLContainerImpl(lContainer, tNode, hostLView) {
  18250. // We already have a native element (anchor) set and the process
  18251. // of finding dehydrated views happened (so the `lContainer[DEHYDRATED_VIEWS]`
  18252. // is not null), exit early.
  18253. if (lContainer[NATIVE] && lContainer[DEHYDRATED_VIEWS]) {
  18254. return true;
  18255. }
  18256. const hydrationInfo = hostLView[HYDRATION];
  18257. const noOffsetIndex = tNode.index - HEADER_OFFSET;
  18258. const isNodeCreationMode = !hydrationInfo ||
  18259. isInSkipHydrationBlock(tNode) ||
  18260. isDisconnectedNode$1(hydrationInfo, noOffsetIndex);
  18261. // Regular creation mode.
  18262. if (isNodeCreationMode) {
  18263. return false;
  18264. }
  18265. // Hydration mode, looking up an anchor node and dehydrated views in DOM.
  18266. const currentRNode = getSegmentHead(hydrationInfo, noOffsetIndex);
  18267. const serializedViews = hydrationInfo.data[CONTAINERS]?.[noOffsetIndex];
  18268. ngDevMode &&
  18269. assertDefined(serializedViews, 'Unexpected state: no hydration info available for a given TNode, ' +
  18270. 'which represents a view container.');
  18271. const [commentNode, dehydratedViews] = locateDehydratedViewsInContainer(currentRNode, serializedViews);
  18272. if (ngDevMode) {
  18273. validateMatchingNode(commentNode, Node.COMMENT_NODE, null, hostLView, tNode, true);
  18274. // Do not throw in case this node is already claimed (thus `false` as a second
  18275. // argument). If this container is created based on an `<ng-template>`, the comment
  18276. // node would be already claimed from the `template` instruction. If an element acts
  18277. // as an anchor (e.g. <div #vcRef>), a separate comment node would be created/located,
  18278. // so we need to claim it here.
  18279. markRNodeAsClaimedByHydration(commentNode, false);
  18280. }
  18281. lContainer[NATIVE] = commentNode;
  18282. lContainer[DEHYDRATED_VIEWS] = dehydratedViews;
  18283. return true;
  18284. }
  18285. function locateOrCreateAnchorNode(lContainer, hostLView, hostTNode, slotValue) {
  18286. if (!_populateDehydratedViewsInLContainer(lContainer, hostTNode, hostLView)) {
  18287. // Populating dehydrated views operation returned `false`, which indicates
  18288. // that the logic was running in client-only mode, this an anchor comment
  18289. // node should be created for this container.
  18290. createAnchorNode(lContainer, hostLView, hostTNode, slotValue);
  18291. }
  18292. }
  18293. function enableLocateOrCreateContainerRefImpl() {
  18294. _locateOrCreateAnchorNode = locateOrCreateAnchorNode;
  18295. _populateDehydratedViewsInLContainer = populateDehydratedViewsInLContainerImpl;
  18296. }
  18297. class LQuery_ {
  18298. queryList;
  18299. matches = null;
  18300. constructor(queryList) {
  18301. this.queryList = queryList;
  18302. }
  18303. clone() {
  18304. return new LQuery_(this.queryList);
  18305. }
  18306. setDirty() {
  18307. this.queryList.setDirty();
  18308. }
  18309. }
  18310. class LQueries_ {
  18311. queries;
  18312. constructor(queries = []) {
  18313. this.queries = queries;
  18314. }
  18315. createEmbeddedView(tView) {
  18316. const tQueries = tView.queries;
  18317. if (tQueries !== null) {
  18318. const noOfInheritedQueries = tView.contentQueries !== null ? tView.contentQueries[0] : tQueries.length;
  18319. const viewLQueries = [];
  18320. // An embedded view has queries propagated from a declaration view at the beginning of the
  18321. // TQueries collection and up until a first content query declared in the embedded view. Only
  18322. // propagated LQueries are created at this point (LQuery corresponding to declared content
  18323. // queries will be instantiated from the content query instructions for each directive).
  18324. for (let i = 0; i < noOfInheritedQueries; i++) {
  18325. const tQuery = tQueries.getByIndex(i);
  18326. const parentLQuery = this.queries[tQuery.indexInDeclarationView];
  18327. viewLQueries.push(parentLQuery.clone());
  18328. }
  18329. return new LQueries_(viewLQueries);
  18330. }
  18331. return null;
  18332. }
  18333. insertView(tView) {
  18334. this.dirtyQueriesWithMatches(tView);
  18335. }
  18336. detachView(tView) {
  18337. this.dirtyQueriesWithMatches(tView);
  18338. }
  18339. finishViewCreation(tView) {
  18340. this.dirtyQueriesWithMatches(tView);
  18341. }
  18342. dirtyQueriesWithMatches(tView) {
  18343. for (let i = 0; i < this.queries.length; i++) {
  18344. if (getTQuery(tView, i).matches !== null) {
  18345. this.queries[i].setDirty();
  18346. }
  18347. }
  18348. }
  18349. }
  18350. class TQueryMetadata_ {
  18351. flags;
  18352. read;
  18353. predicate;
  18354. constructor(predicate, flags, read = null) {
  18355. this.flags = flags;
  18356. this.read = read;
  18357. // Compiler might not be able to pre-optimize and split multiple selectors.
  18358. if (typeof predicate === 'string') {
  18359. this.predicate = splitQueryMultiSelectors(predicate);
  18360. }
  18361. else {
  18362. this.predicate = predicate;
  18363. }
  18364. }
  18365. }
  18366. class TQueries_ {
  18367. queries;
  18368. constructor(queries = []) {
  18369. this.queries = queries;
  18370. }
  18371. elementStart(tView, tNode) {
  18372. ngDevMode &&
  18373. assertFirstCreatePass(tView, 'Queries should collect results on the first template pass only');
  18374. for (let i = 0; i < this.queries.length; i++) {
  18375. this.queries[i].elementStart(tView, tNode);
  18376. }
  18377. }
  18378. elementEnd(tNode) {
  18379. for (let i = 0; i < this.queries.length; i++) {
  18380. this.queries[i].elementEnd(tNode);
  18381. }
  18382. }
  18383. embeddedTView(tNode) {
  18384. let queriesForTemplateRef = null;
  18385. for (let i = 0; i < this.length; i++) {
  18386. const childQueryIndex = queriesForTemplateRef !== null ? queriesForTemplateRef.length : 0;
  18387. const tqueryClone = this.getByIndex(i).embeddedTView(tNode, childQueryIndex);
  18388. if (tqueryClone) {
  18389. tqueryClone.indexInDeclarationView = i;
  18390. if (queriesForTemplateRef !== null) {
  18391. queriesForTemplateRef.push(tqueryClone);
  18392. }
  18393. else {
  18394. queriesForTemplateRef = [tqueryClone];
  18395. }
  18396. }
  18397. }
  18398. return queriesForTemplateRef !== null ? new TQueries_(queriesForTemplateRef) : null;
  18399. }
  18400. template(tView, tNode) {
  18401. ngDevMode &&
  18402. assertFirstCreatePass(tView, 'Queries should collect results on the first template pass only');
  18403. for (let i = 0; i < this.queries.length; i++) {
  18404. this.queries[i].template(tView, tNode);
  18405. }
  18406. }
  18407. getByIndex(index) {
  18408. ngDevMode && assertIndexInRange(this.queries, index);
  18409. return this.queries[index];
  18410. }
  18411. get length() {
  18412. return this.queries.length;
  18413. }
  18414. track(tquery) {
  18415. this.queries.push(tquery);
  18416. }
  18417. }
  18418. class TQuery_ {
  18419. metadata;
  18420. matches = null;
  18421. indexInDeclarationView = -1;
  18422. crossesNgTemplate = false;
  18423. /**
  18424. * A node index on which a query was declared (-1 for view queries and ones inherited from the
  18425. * declaration template). We use this index (alongside with _appliesToNextNode flag) to know
  18426. * when to apply content queries to elements in a template.
  18427. */
  18428. _declarationNodeIndex;
  18429. /**
  18430. * A flag indicating if a given query still applies to nodes it is crossing. We use this flag
  18431. * (alongside with _declarationNodeIndex) to know when to stop applying content queries to
  18432. * elements in a template.
  18433. */
  18434. _appliesToNextNode = true;
  18435. constructor(metadata, nodeIndex = -1) {
  18436. this.metadata = metadata;
  18437. this._declarationNodeIndex = nodeIndex;
  18438. }
  18439. elementStart(tView, tNode) {
  18440. if (this.isApplyingToNode(tNode)) {
  18441. this.matchTNode(tView, tNode);
  18442. }
  18443. }
  18444. elementEnd(tNode) {
  18445. if (this._declarationNodeIndex === tNode.index) {
  18446. this._appliesToNextNode = false;
  18447. }
  18448. }
  18449. template(tView, tNode) {
  18450. this.elementStart(tView, tNode);
  18451. }
  18452. embeddedTView(tNode, childQueryIndex) {
  18453. if (this.isApplyingToNode(tNode)) {
  18454. this.crossesNgTemplate = true;
  18455. // A marker indicating a `<ng-template>` element (a placeholder for query results from
  18456. // embedded views created based on this `<ng-template>`).
  18457. this.addMatch(-tNode.index, childQueryIndex);
  18458. return new TQuery_(this.metadata);
  18459. }
  18460. return null;
  18461. }
  18462. isApplyingToNode(tNode) {
  18463. if (this._appliesToNextNode &&
  18464. (this.metadata.flags & 1 /* QueryFlags.descendants */) !== 1 /* QueryFlags.descendants */) {
  18465. const declarationNodeIdx = this._declarationNodeIndex;
  18466. let parent = tNode.parent;
  18467. // Determine if a given TNode is a "direct" child of a node on which a content query was
  18468. // declared (only direct children of query's host node can match with the descendants: false
  18469. // option). There are 3 main use-case / conditions to consider here:
  18470. // - <needs-target><i #target></i></needs-target>: here <i #target> parent node is a query
  18471. // host node;
  18472. // - <needs-target><ng-template [ngIf]="true"><i #target></i></ng-template></needs-target>:
  18473. // here <i #target> parent node is null;
  18474. // - <needs-target><ng-container><i #target></i></ng-container></needs-target>: here we need
  18475. // to go past `<ng-container>` to determine <i #target> parent node (but we shouldn't traverse
  18476. // up past the query's host node!).
  18477. while (parent !== null &&
  18478. parent.type & 8 /* TNodeType.ElementContainer */ &&
  18479. parent.index !== declarationNodeIdx) {
  18480. parent = parent.parent;
  18481. }
  18482. return declarationNodeIdx === (parent !== null ? parent.index : -1);
  18483. }
  18484. return this._appliesToNextNode;
  18485. }
  18486. matchTNode(tView, tNode) {
  18487. const predicate = this.metadata.predicate;
  18488. if (Array.isArray(predicate)) {
  18489. for (let i = 0; i < predicate.length; i++) {
  18490. const name = predicate[i];
  18491. this.matchTNodeWithReadOption(tView, tNode, getIdxOfMatchingSelector(tNode, name));
  18492. // Also try matching the name to a provider since strings can be used as DI tokens too.
  18493. this.matchTNodeWithReadOption(tView, tNode, locateDirectiveOrProvider(tNode, tView, name, false, false));
  18494. }
  18495. }
  18496. else {
  18497. if (predicate === TemplateRef) {
  18498. if (tNode.type & 4 /* TNodeType.Container */) {
  18499. this.matchTNodeWithReadOption(tView, tNode, -1);
  18500. }
  18501. }
  18502. else {
  18503. this.matchTNodeWithReadOption(tView, tNode, locateDirectiveOrProvider(tNode, tView, predicate, false, false));
  18504. }
  18505. }
  18506. }
  18507. matchTNodeWithReadOption(tView, tNode, nodeMatchIdx) {
  18508. if (nodeMatchIdx !== null) {
  18509. const read = this.metadata.read;
  18510. if (read !== null) {
  18511. if (read === ElementRef ||
  18512. read === ViewContainerRef ||
  18513. (read === TemplateRef && tNode.type & 4 /* TNodeType.Container */)) {
  18514. this.addMatch(tNode.index, -2);
  18515. }
  18516. else {
  18517. const directiveOrProviderIdx = locateDirectiveOrProvider(tNode, tView, read, false, false);
  18518. if (directiveOrProviderIdx !== null) {
  18519. this.addMatch(tNode.index, directiveOrProviderIdx);
  18520. }
  18521. }
  18522. }
  18523. else {
  18524. this.addMatch(tNode.index, nodeMatchIdx);
  18525. }
  18526. }
  18527. }
  18528. addMatch(tNodeIdx, matchIdx) {
  18529. if (this.matches === null) {
  18530. this.matches = [tNodeIdx, matchIdx];
  18531. }
  18532. else {
  18533. this.matches.push(tNodeIdx, matchIdx);
  18534. }
  18535. }
  18536. }
  18537. /**
  18538. * Iterates over local names for a given node and returns directive index
  18539. * (or -1 if a local name points to an element).
  18540. *
  18541. * @param tNode static data of a node to check
  18542. * @param selector selector to match
  18543. * @returns directive index, -1 or null if a selector didn't match any of the local names
  18544. */
  18545. function getIdxOfMatchingSelector(tNode, selector) {
  18546. const localNames = tNode.localNames;
  18547. if (localNames !== null) {
  18548. for (let i = 0; i < localNames.length; i += 2) {
  18549. if (localNames[i] === selector) {
  18550. return localNames[i + 1];
  18551. }
  18552. }
  18553. }
  18554. return null;
  18555. }
  18556. function createResultByTNodeType(tNode, currentView) {
  18557. if (tNode.type & (3 /* TNodeType.AnyRNode */ | 8 /* TNodeType.ElementContainer */)) {
  18558. return createElementRef(tNode, currentView);
  18559. }
  18560. else if (tNode.type & 4 /* TNodeType.Container */) {
  18561. return createTemplateRef(tNode, currentView);
  18562. }
  18563. return null;
  18564. }
  18565. function createResultForNode(lView, tNode, matchingIdx, read) {
  18566. if (matchingIdx === -1) {
  18567. // if read token and / or strategy is not specified, detect it using appropriate tNode type
  18568. return createResultByTNodeType(tNode, lView);
  18569. }
  18570. else if (matchingIdx === -2) {
  18571. // read a special token from a node injector
  18572. return createSpecialToken(lView, tNode, read);
  18573. }
  18574. else {
  18575. // read a token
  18576. return getNodeInjectable(lView, lView[TVIEW], matchingIdx, tNode);
  18577. }
  18578. }
  18579. function createSpecialToken(lView, tNode, read) {
  18580. if (read === ElementRef) {
  18581. return createElementRef(tNode, lView);
  18582. }
  18583. else if (read === TemplateRef) {
  18584. return createTemplateRef(tNode, lView);
  18585. }
  18586. else if (read === ViewContainerRef) {
  18587. ngDevMode && assertTNodeType(tNode, 3 /* TNodeType.AnyRNode */ | 12 /* TNodeType.AnyContainer */);
  18588. return createContainerRef(tNode, lView);
  18589. }
  18590. else {
  18591. ngDevMode &&
  18592. throwError(`Special token to read should be one of ElementRef, TemplateRef or ViewContainerRef but got ${stringify(read)}.`);
  18593. }
  18594. }
  18595. /**
  18596. * A helper function that creates query results for a given view. This function is meant to do the
  18597. * processing once and only once for a given view instance (a set of results for a given view
  18598. * doesn't change).
  18599. */
  18600. function materializeViewResults(tView, lView, tQuery, queryIndex) {
  18601. const lQuery = lView[QUERIES].queries[queryIndex];
  18602. if (lQuery.matches === null) {
  18603. const tViewData = tView.data;
  18604. const tQueryMatches = tQuery.matches;
  18605. const result = [];
  18606. for (let i = 0; tQueryMatches !== null && i < tQueryMatches.length; i += 2) {
  18607. const matchedNodeIdx = tQueryMatches[i];
  18608. if (matchedNodeIdx < 0) {
  18609. // we at the <ng-template> marker which might have results in views created based on this
  18610. // <ng-template> - those results will be in separate views though, so here we just leave
  18611. // null as a placeholder
  18612. result.push(null);
  18613. }
  18614. else {
  18615. ngDevMode && assertIndexInRange(tViewData, matchedNodeIdx);
  18616. const tNode = tViewData[matchedNodeIdx];
  18617. result.push(createResultForNode(lView, tNode, tQueryMatches[i + 1], tQuery.metadata.read));
  18618. }
  18619. }
  18620. lQuery.matches = result;
  18621. }
  18622. return lQuery.matches;
  18623. }
  18624. /**
  18625. * A helper function that collects (already materialized) query results from a tree of views,
  18626. * starting with a provided LView.
  18627. */
  18628. function collectQueryResults(tView, lView, queryIndex, result) {
  18629. const tQuery = tView.queries.getByIndex(queryIndex);
  18630. const tQueryMatches = tQuery.matches;
  18631. if (tQueryMatches !== null) {
  18632. const lViewResults = materializeViewResults(tView, lView, tQuery, queryIndex);
  18633. for (let i = 0; i < tQueryMatches.length; i += 2) {
  18634. const tNodeIdx = tQueryMatches[i];
  18635. if (tNodeIdx > 0) {
  18636. result.push(lViewResults[i / 2]);
  18637. }
  18638. else {
  18639. const childQueryIndex = tQueryMatches[i + 1];
  18640. const declarationLContainer = lView[-tNodeIdx];
  18641. ngDevMode && assertLContainer(declarationLContainer);
  18642. // collect matches for views inserted in this container
  18643. for (let i = CONTAINER_HEADER_OFFSET; i < declarationLContainer.length; i++) {
  18644. const embeddedLView = declarationLContainer[i];
  18645. if (embeddedLView[DECLARATION_LCONTAINER] === embeddedLView[PARENT]) {
  18646. collectQueryResults(embeddedLView[TVIEW], embeddedLView, childQueryIndex, result);
  18647. }
  18648. }
  18649. // collect matches for views created from this declaration container and inserted into
  18650. // different containers
  18651. if (declarationLContainer[MOVED_VIEWS] !== null) {
  18652. const embeddedLViews = declarationLContainer[MOVED_VIEWS];
  18653. for (let i = 0; i < embeddedLViews.length; i++) {
  18654. const embeddedLView = embeddedLViews[i];
  18655. collectQueryResults(embeddedLView[TVIEW], embeddedLView, childQueryIndex, result);
  18656. }
  18657. }
  18658. }
  18659. }
  18660. }
  18661. return result;
  18662. }
  18663. function loadQueryInternal(lView, queryIndex) {
  18664. ngDevMode &&
  18665. assertDefined(lView[QUERIES], 'LQueries should be defined when trying to load a query');
  18666. ngDevMode && assertIndexInRange(lView[QUERIES].queries, queryIndex);
  18667. return lView[QUERIES].queries[queryIndex].queryList;
  18668. }
  18669. /**
  18670. * Creates a new instance of LQuery and returns its index in the collection of LQuery objects.
  18671. *
  18672. * @returns index in the collection of LQuery objects
  18673. */
  18674. function createLQuery(tView, lView, flags) {
  18675. const queryList = new QueryList((flags & 4 /* QueryFlags.emitDistinctChangesOnly */) === 4 /* QueryFlags.emitDistinctChangesOnly */);
  18676. storeCleanupWithContext(tView, lView, queryList, queryList.destroy);
  18677. const lQueries = (lView[QUERIES] ??= new LQueries_()).queries;
  18678. return lQueries.push(new LQuery_(queryList)) - 1;
  18679. }
  18680. function createViewQuery(predicate, flags, read) {
  18681. ngDevMode && assertNumber(flags, 'Expecting flags');
  18682. const tView = getTView();
  18683. if (tView.firstCreatePass) {
  18684. createTQuery(tView, new TQueryMetadata_(predicate, flags, read), -1);
  18685. if ((flags & 2 /* QueryFlags.isStatic */) === 2 /* QueryFlags.isStatic */) {
  18686. tView.staticViewQueries = true;
  18687. }
  18688. }
  18689. return createLQuery(tView, getLView(), flags);
  18690. }
  18691. function createContentQuery(directiveIndex, predicate, flags, read) {
  18692. ngDevMode && assertNumber(flags, 'Expecting flags');
  18693. const tView = getTView();
  18694. if (tView.firstCreatePass) {
  18695. const tNode = getCurrentTNode();
  18696. createTQuery(tView, new TQueryMetadata_(predicate, flags, read), tNode.index);
  18697. saveContentQueryAndDirectiveIndex(tView, directiveIndex);
  18698. if ((flags & 2 /* QueryFlags.isStatic */) === 2 /* QueryFlags.isStatic */) {
  18699. tView.staticContentQueries = true;
  18700. }
  18701. }
  18702. return createLQuery(tView, getLView(), flags);
  18703. }
  18704. /** Splits multiple selectors in the locator. */
  18705. function splitQueryMultiSelectors(locator) {
  18706. return locator.split(',').map((s) => s.trim());
  18707. }
  18708. function createTQuery(tView, metadata, nodeIndex) {
  18709. if (tView.queries === null)
  18710. tView.queries = new TQueries_();
  18711. tView.queries.track(new TQuery_(metadata, nodeIndex));
  18712. }
  18713. function saveContentQueryAndDirectiveIndex(tView, directiveIndex) {
  18714. const tViewContentQueries = tView.contentQueries || (tView.contentQueries = []);
  18715. const lastSavedDirectiveIndex = tViewContentQueries.length
  18716. ? tViewContentQueries[tViewContentQueries.length - 1]
  18717. : -1;
  18718. if (directiveIndex !== lastSavedDirectiveIndex) {
  18719. tViewContentQueries.push(tView.queries.length - 1, directiveIndex);
  18720. }
  18721. }
  18722. function getTQuery(tView, index) {
  18723. ngDevMode && assertDefined(tView.queries, 'TQueries must be defined to retrieve a TQuery');
  18724. return tView.queries.getByIndex(index);
  18725. }
  18726. /**
  18727. * A helper function collecting results from all the views where a given query was active.
  18728. * @param lView
  18729. * @param queryIndex
  18730. */
  18731. function getQueryResults(lView, queryIndex) {
  18732. const tView = lView[TVIEW];
  18733. const tQuery = getTQuery(tView, queryIndex);
  18734. return tQuery.crossesNgTemplate
  18735. ? collectQueryResults(tView, lView, queryIndex, [])
  18736. : materializeViewResults(tView, lView, tQuery, queryIndex);
  18737. }
  18738. /**
  18739. * A signal factory function in charge of creating a new computed signal capturing query
  18740. * results. This centralized creation function is used by all types of queries (child / children,
  18741. * required / optional).
  18742. *
  18743. * @param firstOnly indicates if all or only the first result should be returned
  18744. * @param required indicates if at least one result is required
  18745. * @returns a read-only signal with query results
  18746. */
  18747. function createQuerySignalFn(firstOnly, required, opts) {
  18748. let node;
  18749. const signalFn = createComputed(() => {
  18750. // A dedicated signal that increments its value every time a query changes its dirty status. By
  18751. // using this signal we can implement a query as computed and avoid creation of a specialized
  18752. // reactive node type. Please note that a query gets marked dirty under the following
  18753. // circumstances:
  18754. // - a view (where a query is active) finished its first creation pass;
  18755. // - a new view is inserted / deleted and it impacts query results.
  18756. node._dirtyCounter();
  18757. const value = refreshSignalQuery(node, firstOnly);
  18758. if (required && value === undefined) {
  18759. throw new RuntimeError(-951 /* RuntimeErrorCode.REQUIRED_QUERY_NO_VALUE */, ngDevMode && 'Child query result is required but no value is available.');
  18760. }
  18761. return value;
  18762. });
  18763. node = signalFn[SIGNAL];
  18764. node._dirtyCounter = signal(0);
  18765. node._flatValue = undefined;
  18766. if (ngDevMode) {
  18767. signalFn.toString = () => `[Query Signal]`;
  18768. node.debugName = opts?.debugName;
  18769. }
  18770. return signalFn;
  18771. }
  18772. function createSingleResultOptionalQuerySignalFn(opts) {
  18773. return createQuerySignalFn(/* firstOnly */ true, /* required */ false, opts);
  18774. }
  18775. function createSingleResultRequiredQuerySignalFn(opts) {
  18776. return createQuerySignalFn(/* firstOnly */ true, /* required */ true, opts);
  18777. }
  18778. function createMultiResultQuerySignalFn(opts) {
  18779. return createQuerySignalFn(/* firstOnly */ false, /* required */ false, opts);
  18780. }
  18781. function bindQueryToSignal(target, queryIndex) {
  18782. const node = target[SIGNAL];
  18783. node._lView = getLView();
  18784. node._queryIndex = queryIndex;
  18785. node._queryList = loadQueryInternal(node._lView, queryIndex);
  18786. node._queryList.onDirty(() => node._dirtyCounter.update((v) => v + 1));
  18787. }
  18788. function refreshSignalQuery(node, firstOnly) {
  18789. const lView = node._lView;
  18790. const queryIndex = node._queryIndex;
  18791. // There are 2 conditions under which we want to return "empty" results instead of the ones
  18792. // collected by a query:
  18793. //
  18794. // 1) a given query wasn't created yet (this is a period of time between the directive creation
  18795. // and execution of the query creation function) - in this case a query doesn't exist yet and we
  18796. // don't have any results to return.
  18797. //
  18798. // 2) we are in the process of constructing a view (the first
  18799. // creation pass didn't finish) and a query might have partial results, but we don't want to
  18800. // return those - instead we do delay results collection until all nodes had a chance of matching
  18801. // and we can present consistent, "atomic" (on a view level) results.
  18802. if (lView === undefined || queryIndex === undefined || lView[FLAGS] & 4 /* LViewFlags.CreationMode */) {
  18803. return (firstOnly ? undefined : EMPTY_ARRAY);
  18804. }
  18805. const queryList = loadQueryInternal(lView, queryIndex);
  18806. const results = getQueryResults(lView, queryIndex);
  18807. queryList.reset(results, unwrapElementRef);
  18808. if (firstOnly) {
  18809. return queryList.first;
  18810. }
  18811. else {
  18812. // TODO: remove access to the private _changesDetected field by abstracting / removing usage of
  18813. // QueryList in the signal-based queries (perf follow-up)
  18814. const resultChanged = queryList._changesDetected;
  18815. if (resultChanged || node._flatValue === undefined) {
  18816. return (node._flatValue = queryList.toArray());
  18817. }
  18818. return node._flatValue;
  18819. }
  18820. }
  18821. function viewChildFn(locator, opts) {
  18822. ngDevMode && assertInInjectionContext(viewChild);
  18823. return createSingleResultOptionalQuerySignalFn(opts);
  18824. }
  18825. function viewChildRequiredFn(locator, opts) {
  18826. ngDevMode && assertInInjectionContext(viewChild);
  18827. return createSingleResultRequiredQuerySignalFn(opts);
  18828. }
  18829. /**
  18830. * Initializes a view child query.
  18831. *
  18832. * Consider using `viewChild.required` for queries that should always match.
  18833. *
  18834. * @usageNotes
  18835. * Create a child query in your component by declaring a
  18836. * class field and initializing it with the `viewChild()` function.
  18837. *
  18838. * ```angular-ts
  18839. * @Component({template: '<div #el></div><my-component #cmp />'})
  18840. * export class TestComponent {
  18841. * divEl = viewChild<ElementRef>('el'); // Signal<ElementRef|undefined>
  18842. * divElRequired = viewChild.required<ElementRef>('el'); // Signal<ElementRef>
  18843. * cmp = viewChild(MyComponent); // Signal<MyComponent|undefined>
  18844. * cmpRequired = viewChild.required(MyComponent); // Signal<MyComponent>
  18845. * }
  18846. * ```
  18847. *
  18848. * @publicAPI
  18849. * @initializerApiFunction
  18850. */
  18851. const viewChild = (() => {
  18852. // Note: This may be considered a side-effect, but nothing will depend on
  18853. // this assignment, unless this `viewChild` constant export is accessed. It's a
  18854. // self-contained side effect that is local to the user facing `viewChild` export.
  18855. viewChildFn.required = viewChildRequiredFn;
  18856. return viewChildFn;
  18857. })();
  18858. /**
  18859. * Initializes a view children query.
  18860. *
  18861. * Query results are represented as a signal of a read-only collection containing all matched
  18862. * elements.
  18863. *
  18864. * @usageNotes
  18865. * Create a children query in your component by declaring a
  18866. * class field and initializing it with the `viewChildren()` function.
  18867. *
  18868. * ```ts
  18869. * @Component({...})
  18870. * export class TestComponent {
  18871. * divEls = viewChildren<ElementRef>('el'); // Signal<ReadonlyArray<ElementRef>>
  18872. * }
  18873. * ```
  18874. *
  18875. * @initializerApiFunction
  18876. * @publicAPI
  18877. */
  18878. function viewChildren(locator, opts) {
  18879. ngDevMode && assertInInjectionContext(viewChildren);
  18880. return createMultiResultQuerySignalFn(opts);
  18881. }
  18882. function contentChildFn(locator, opts) {
  18883. ngDevMode && assertInInjectionContext(contentChild);
  18884. return createSingleResultOptionalQuerySignalFn(opts);
  18885. }
  18886. function contentChildRequiredFn(locator, opts) {
  18887. ngDevMode && assertInInjectionContext(contentChildren);
  18888. return createSingleResultRequiredQuerySignalFn(opts);
  18889. }
  18890. /**
  18891. * Initializes a content child query. Consider using `contentChild.required` for queries that should
  18892. * always match.
  18893. *
  18894. * @usageNotes
  18895. * Create a child query in your component by declaring a
  18896. * class field and initializing it with the `contentChild()` function.
  18897. *
  18898. * ```ts
  18899. * @Component({...})
  18900. * export class TestComponent {
  18901. * headerEl = contentChild<ElementRef>('h'); // Signal<ElementRef|undefined>
  18902. * headerElElRequired = contentChild.required<ElementRef>('h'); // Signal<ElementRef>
  18903. * header = contentChild(MyHeader); // Signal<MyHeader|undefined>
  18904. * headerRequired = contentChild.required(MyHeader); // Signal<MyHeader>
  18905. * }
  18906. * ```
  18907. *
  18908. * @initializerApiFunction
  18909. * @publicAPI
  18910. */
  18911. const contentChild = (() => {
  18912. // Note: This may be considered a side-effect, but nothing will depend on
  18913. // this assignment, unless this `viewChild` constant export is accessed. It's a
  18914. // self-contained side effect that is local to the user facing `viewChild` export.
  18915. contentChildFn.required = contentChildRequiredFn;
  18916. return contentChildFn;
  18917. })();
  18918. /**
  18919. * Initializes a content children query.
  18920. *
  18921. * Query results are represented as a signal of a read-only collection containing all matched
  18922. * elements.
  18923. *
  18924. * @usageNotes
  18925. * Create a children query in your component by declaring a
  18926. * class field and initializing it with the `contentChildren()` function.
  18927. *
  18928. * ```ts
  18929. * @Component({...})
  18930. * export class TestComponent {
  18931. * headerEl = contentChildren<ElementRef>('h'); // Signal<ReadonlyArray<ElementRef>>
  18932. * }
  18933. * ```
  18934. *
  18935. * @initializerApiFunction
  18936. * @publicAPI
  18937. */
  18938. function contentChildren(locator, opts) {
  18939. return createMultiResultQuerySignalFn(opts);
  18940. }
  18941. /**
  18942. * Creates a model signal.
  18943. *
  18944. * @param initialValue The initial value.
  18945. * Can be set to {@link REQUIRED_UNSET_VALUE} for required model signals.
  18946. * @param options Additional options for the model.
  18947. */
  18948. function createModelSignal(initialValue, opts) {
  18949. const node = Object.create(INPUT_SIGNAL_NODE);
  18950. const emitterRef = new OutputEmitterRef();
  18951. node.value = initialValue;
  18952. function getter() {
  18953. producerAccessed(node);
  18954. assertModelSet(node.value);
  18955. return node.value;
  18956. }
  18957. getter[SIGNAL] = node;
  18958. getter.asReadonly = signalAsReadonlyFn.bind(getter);
  18959. // TODO: Should we throw an error when updating a destroyed model?
  18960. getter.set = (newValue) => {
  18961. if (!node.equal(node.value, newValue)) {
  18962. signalSetFn(node, newValue);
  18963. emitterRef.emit(newValue);
  18964. }
  18965. };
  18966. getter.update = (updateFn) => {
  18967. assertModelSet(node.value);
  18968. getter.set(updateFn(node.value));
  18969. };
  18970. getter.subscribe = emitterRef.subscribe.bind(emitterRef);
  18971. getter.destroyRef = emitterRef.destroyRef;
  18972. if (ngDevMode) {
  18973. getter.toString = () => `[Model Signal: ${getter()}]`;
  18974. node.debugName = opts?.debugName;
  18975. }
  18976. return getter;
  18977. }
  18978. /** Asserts that a model's value is set. */
  18979. function assertModelSet(value) {
  18980. if (value === REQUIRED_UNSET_VALUE) {
  18981. throw new RuntimeError(952 /* RuntimeErrorCode.REQUIRED_MODEL_NO_VALUE */, ngDevMode && 'Model is required but no value is available yet.');
  18982. }
  18983. }
  18984. function modelFunction(initialValue, opts) {
  18985. ngDevMode && assertInInjectionContext(model);
  18986. return createModelSignal(initialValue, opts);
  18987. }
  18988. function modelRequiredFunction(opts) {
  18989. ngDevMode && assertInInjectionContext(model);
  18990. return createModelSignal(REQUIRED_UNSET_VALUE, opts);
  18991. }
  18992. /**
  18993. * `model` declares a writeable signal that is exposed as an input/output
  18994. * pair on the containing directive.
  18995. *
  18996. * The input name is taken either from the class member or from the `alias` option.
  18997. * The output name is generated by taking the input name and appending `Change`.
  18998. *
  18999. * @usageNotes
  19000. *
  19001. * To use `model()`, import the function from `@angular/core`.
  19002. *
  19003. * ```ts
  19004. * import {model} from '@angular/core`;
  19005. * ```
  19006. *
  19007. * Inside your component, introduce a new class member and initialize
  19008. * it with a call to `model` or `model.required`.
  19009. *
  19010. * ```ts
  19011. * @Directive({
  19012. * ...
  19013. * })
  19014. * export class MyDir {
  19015. * firstName = model<string>(); // ModelSignal<string|undefined>
  19016. * lastName = model.required<string>(); // ModelSignal<string>
  19017. * age = model(0); // ModelSignal<number>
  19018. * }
  19019. * ```
  19020. *
  19021. * Inside your component template, you can display the value of a `model`
  19022. * by calling the signal.
  19023. *
  19024. * ```html
  19025. * <span>{{firstName()}}</span>
  19026. * ```
  19027. *
  19028. * Updating the `model` is equivalent to updating a writable signal.
  19029. *
  19030. * ```ts
  19031. * updateName(newFirstName: string): void {
  19032. * this.firstName.set(newFirstName);
  19033. * }
  19034. * ```
  19035. *
  19036. * @publicAPI
  19037. * @initializerApiFunction
  19038. */
  19039. const model = (() => {
  19040. // Note: This may be considered a side-effect, but nothing will depend on
  19041. // this assignment, unless this `model` constant export is accessed. It's a
  19042. // self-contained side effect that is local to the user facing `model` export.
  19043. modelFunction.required = modelRequiredFunction;
  19044. return modelFunction;
  19045. })();
  19046. // Stores the default value of `emitDistinctChangesOnly` when the `emitDistinctChangesOnly` is not
  19047. // explicitly set.
  19048. const emitDistinctChangesOnlyDefaultValue = true;
  19049. /**
  19050. * Base class for query metadata.
  19051. *
  19052. * @see {@link ContentChildren}
  19053. * @see {@link ContentChild}
  19054. * @see {@link ViewChildren}
  19055. * @see {@link ViewChild}
  19056. *
  19057. * @publicApi
  19058. */
  19059. class Query {
  19060. }
  19061. /**
  19062. * ContentChildren decorator and metadata.
  19063. *
  19064. *
  19065. * @Annotation
  19066. * @publicApi
  19067. */
  19068. const ContentChildren = makePropDecorator('ContentChildren', (selector, opts = {}) => ({
  19069. selector,
  19070. first: false,
  19071. isViewQuery: false,
  19072. descendants: false,
  19073. emitDistinctChangesOnly: emitDistinctChangesOnlyDefaultValue,
  19074. ...opts,
  19075. }), Query);
  19076. /**
  19077. * ContentChild decorator and metadata.
  19078. *
  19079. *
  19080. * @Annotation
  19081. *
  19082. * @publicApi
  19083. */
  19084. const ContentChild = makePropDecorator('ContentChild', (selector, opts = {}) => ({
  19085. selector,
  19086. first: true,
  19087. isViewQuery: false,
  19088. descendants: true,
  19089. ...opts,
  19090. }), Query);
  19091. /**
  19092. * ViewChildren decorator and metadata.
  19093. *
  19094. * @Annotation
  19095. * @publicApi
  19096. */
  19097. const ViewChildren = makePropDecorator('ViewChildren', (selector, opts = {}) => ({
  19098. selector,
  19099. first: false,
  19100. isViewQuery: true,
  19101. descendants: true,
  19102. emitDistinctChangesOnly: emitDistinctChangesOnlyDefaultValue,
  19103. ...opts,
  19104. }), Query);
  19105. /**
  19106. * ViewChild decorator and metadata.
  19107. *
  19108. * @Annotation
  19109. * @publicApi
  19110. */
  19111. const ViewChild = makePropDecorator('ViewChild', (selector, opts) => ({
  19112. selector,
  19113. first: true,
  19114. isViewQuery: true,
  19115. descendants: true,
  19116. ...opts,
  19117. }), Query);
  19118. /**
  19119. * Used to resolve resource URLs on `@Component` when used with JIT compilation.
  19120. *
  19121. * Example:
  19122. * ```ts
  19123. * @Component({
  19124. * selector: 'my-comp',
  19125. * templateUrl: 'my-comp.html', // This requires asynchronous resolution
  19126. * })
  19127. * class MyComponent{
  19128. * }
  19129. *
  19130. * // Calling `renderComponent` will fail because `renderComponent` is a synchronous process
  19131. * // and `MyComponent`'s `@Component.templateUrl` needs to be resolved asynchronously.
  19132. *
  19133. * // Calling `resolveComponentResources()` will resolve `@Component.templateUrl` into
  19134. * // `@Component.template`, which allows `renderComponent` to proceed in a synchronous manner.
  19135. *
  19136. * // Use browser's `fetch()` function as the default resource resolution strategy.
  19137. * resolveComponentResources(fetch).then(() => {
  19138. * // After resolution all URLs have been converted into `template` strings.
  19139. * renderComponent(MyComponent);
  19140. * });
  19141. *
  19142. * ```
  19143. *
  19144. * NOTE: In AOT the resolution happens during compilation, and so there should be no need
  19145. * to call this method outside JIT mode.
  19146. *
  19147. * @param resourceResolver a function which is responsible for returning a `Promise` to the
  19148. * contents of the resolved URL. Browser's `fetch()` method is a good default implementation.
  19149. */
  19150. function resolveComponentResources(resourceResolver) {
  19151. // Store all promises which are fetching the resources.
  19152. const componentResolved = [];
  19153. // Cache so that we don't fetch the same resource more than once.
  19154. const urlMap = new Map();
  19155. function cachedResourceResolve(url) {
  19156. let promise = urlMap.get(url);
  19157. if (!promise) {
  19158. const resp = resourceResolver(url);
  19159. urlMap.set(url, (promise = resp.then(unwrapResponse)));
  19160. }
  19161. return promise;
  19162. }
  19163. componentResourceResolutionQueue.forEach((component, type) => {
  19164. const promises = [];
  19165. if (component.templateUrl) {
  19166. promises.push(cachedResourceResolve(component.templateUrl).then((template) => {
  19167. component.template = template;
  19168. }));
  19169. }
  19170. const styles = typeof component.styles === 'string' ? [component.styles] : component.styles || [];
  19171. component.styles = styles;
  19172. if (component.styleUrl && component.styleUrls?.length) {
  19173. throw new Error('@Component cannot define both `styleUrl` and `styleUrls`. ' +
  19174. 'Use `styleUrl` if the component has one stylesheet, or `styleUrls` if it has multiple');
  19175. }
  19176. else if (component.styleUrls?.length) {
  19177. const styleOffset = component.styles.length;
  19178. const styleUrls = component.styleUrls;
  19179. component.styleUrls.forEach((styleUrl, index) => {
  19180. styles.push(''); // pre-allocate array.
  19181. promises.push(cachedResourceResolve(styleUrl).then((style) => {
  19182. styles[styleOffset + index] = style;
  19183. styleUrls.splice(styleUrls.indexOf(styleUrl), 1);
  19184. if (styleUrls.length == 0) {
  19185. component.styleUrls = undefined;
  19186. }
  19187. }));
  19188. });
  19189. }
  19190. else if (component.styleUrl) {
  19191. promises.push(cachedResourceResolve(component.styleUrl).then((style) => {
  19192. styles.push(style);
  19193. component.styleUrl = undefined;
  19194. }));
  19195. }
  19196. const fullyResolved = Promise.all(promises).then(() => componentDefResolved(type));
  19197. componentResolved.push(fullyResolved);
  19198. });
  19199. clearResolutionOfComponentResourcesQueue();
  19200. return Promise.all(componentResolved).then(() => undefined);
  19201. }
  19202. let componentResourceResolutionQueue = new Map();
  19203. // Track when existing ɵcmp for a Type is waiting on resources.
  19204. const componentDefPendingResolution = new Set();
  19205. function maybeQueueResolutionOfComponentResources(type, metadata) {
  19206. if (componentNeedsResolution(metadata)) {
  19207. componentResourceResolutionQueue.set(type, metadata);
  19208. componentDefPendingResolution.add(type);
  19209. }
  19210. }
  19211. function isComponentDefPendingResolution(type) {
  19212. return componentDefPendingResolution.has(type);
  19213. }
  19214. function componentNeedsResolution(component) {
  19215. return !!((component.templateUrl && !component.hasOwnProperty('template')) ||
  19216. (component.styleUrls && component.styleUrls.length) ||
  19217. component.styleUrl);
  19218. }
  19219. function clearResolutionOfComponentResourcesQueue() {
  19220. const old = componentResourceResolutionQueue;
  19221. componentResourceResolutionQueue = new Map();
  19222. return old;
  19223. }
  19224. function restoreComponentResolutionQueue(queue) {
  19225. componentDefPendingResolution.clear();
  19226. queue.forEach((_, type) => componentDefPendingResolution.add(type));
  19227. componentResourceResolutionQueue = queue;
  19228. }
  19229. function isComponentResourceResolutionQueueEmpty() {
  19230. return componentResourceResolutionQueue.size === 0;
  19231. }
  19232. function unwrapResponse(response) {
  19233. return typeof response == 'string' ? response : response.text();
  19234. }
  19235. function componentDefResolved(type) {
  19236. componentDefPendingResolution.delete(type);
  19237. }
  19238. /**
  19239. * Map of module-id to the corresponding NgModule.
  19240. */
  19241. const modules = new Map();
  19242. /**
  19243. * Whether to check for duplicate NgModule registrations.
  19244. *
  19245. * This can be disabled for testing.
  19246. */
  19247. let checkForDuplicateNgModules = true;
  19248. function assertSameOrNotExisting(id, type, incoming) {
  19249. if (type && type !== incoming && checkForDuplicateNgModules) {
  19250. throw new Error(`Duplicate module registered for ${id} - ${stringify(type)} vs ${stringify(type.name)}`);
  19251. }
  19252. }
  19253. /**
  19254. * Adds the given NgModule type to Angular's NgModule registry.
  19255. *
  19256. * This is generated as a side-effect of NgModule compilation. Note that the `id` is passed in
  19257. * explicitly and not read from the NgModule definition. This is for two reasons: it avoids a
  19258. * megamorphic read, and in JIT there's a chicken-and-egg problem where the NgModule may not be
  19259. * fully resolved when it's registered.
  19260. *
  19261. * @codeGenApi
  19262. */
  19263. function registerNgModuleType(ngModuleType, id) {
  19264. const existing = modules.get(id) || null;
  19265. assertSameOrNotExisting(id, existing, ngModuleType);
  19266. modules.set(id, ngModuleType);
  19267. }
  19268. function getRegisteredNgModuleType(id) {
  19269. return modules.get(id);
  19270. }
  19271. /**
  19272. * Control whether the NgModule registration system enforces that each NgModule type registered has
  19273. * a unique id.
  19274. *
  19275. * This is useful for testing as the NgModule registry cannot be properly reset between tests with
  19276. * Angular's current API.
  19277. */
  19278. function setAllowDuplicateNgModuleIdsForTest(allowDuplicates) {
  19279. checkForDuplicateNgModules = !allowDuplicates;
  19280. }
  19281. /**
  19282. * Validation function invoked at runtime for each binding that might potentially
  19283. * represent a security-sensitive attribute of an <iframe>.
  19284. * See `IFRAME_SECURITY_SENSITIVE_ATTRS` in the
  19285. * `packages/compiler/src/schema/dom_security_schema.ts` script for the full list
  19286. * of such attributes.
  19287. *
  19288. * @codeGenApi
  19289. */
  19290. function ɵɵvalidateIframeAttribute(attrValue, tagName, attrName) {
  19291. const lView = getLView();
  19292. const tNode = getSelectedTNode();
  19293. const element = getNativeByTNode(tNode, lView);
  19294. // Restrict any dynamic bindings of security-sensitive attributes/properties
  19295. // on an <iframe> for security reasons.
  19296. if (tNode.type === 2 /* TNodeType.Element */ && tagName.toLowerCase() === 'iframe') {
  19297. const iframe = element;
  19298. // Unset previously applied `src` and `srcdoc` if we come across a situation when
  19299. // a security-sensitive attribute is set later via an attribute/property binding.
  19300. iframe.src = '';
  19301. iframe.srcdoc = trustedHTMLFromString('');
  19302. // Also remove the <iframe> from the document.
  19303. nativeRemoveNode(lView[RENDERER], iframe);
  19304. const errorMessage = ngDevMode &&
  19305. `Angular has detected that the \`${attrName}\` was applied ` +
  19306. `as a binding to an <iframe>${getTemplateLocationDetails(lView)}. ` +
  19307. `For security reasons, the \`${attrName}\` can be set on an <iframe> ` +
  19308. `as a static attribute only. \n` +
  19309. `To fix this, switch the \`${attrName}\` binding to a static attribute ` +
  19310. `in a template or in host bindings section.`;
  19311. throw new RuntimeError(-910 /* RuntimeErrorCode.UNSAFE_IFRAME_ATTRS */, errorMessage);
  19312. }
  19313. return attrValue;
  19314. }
  19315. /**
  19316. * Represents an instance of an `NgModule` created by an `NgModuleFactory`.
  19317. * Provides access to the `NgModule` instance and related objects.
  19318. *
  19319. * @publicApi
  19320. */
  19321. let NgModuleRef$1 = class NgModuleRef {
  19322. };
  19323. /**
  19324. * @publicApi
  19325. *
  19326. * @deprecated
  19327. * This class was mostly used as a part of ViewEngine-based JIT API and is no longer needed in Ivy
  19328. * JIT mode. Angular provides APIs that accept NgModule classes directly (such as
  19329. * [PlatformRef.bootstrapModule](api/core/PlatformRef#bootstrapModule) and
  19330. * [createNgModule](api/core/createNgModule)), consider switching to those APIs instead of
  19331. * using factory-based ones.
  19332. */
  19333. let NgModuleFactory$1 = class NgModuleFactory {
  19334. };
  19335. /**
  19336. * Returns a new NgModuleRef instance based on the NgModule class and parent injector provided.
  19337. *
  19338. * @param ngModule NgModule class.
  19339. * @param parentInjector Optional injector instance to use as a parent for the module injector. If
  19340. * not provided, `NullInjector` will be used instead.
  19341. * @returns NgModuleRef that represents an NgModule instance.
  19342. *
  19343. * @publicApi
  19344. */
  19345. function createNgModule(ngModule, parentInjector) {
  19346. return new NgModuleRef(ngModule, parentInjector ?? null, []);
  19347. }
  19348. /**
  19349. * The `createNgModule` function alias for backwards-compatibility.
  19350. * Please avoid using it directly and use `createNgModule` instead.
  19351. *
  19352. * @deprecated Use `createNgModule` instead.
  19353. */
  19354. const createNgModuleRef = createNgModule;
  19355. class NgModuleRef extends NgModuleRef$1 {
  19356. ngModuleType;
  19357. _parent;
  19358. // tslint:disable-next-line:require-internal-with-underscore
  19359. _bootstrapComponents = [];
  19360. _r3Injector;
  19361. instance;
  19362. destroyCbs = [];
  19363. // When bootstrapping a module we have a dependency graph that looks like this:
  19364. // ApplicationRef -> ComponentFactoryResolver -> NgModuleRef. The problem is that if the
  19365. // module being resolved tries to inject the ComponentFactoryResolver, it'll create a
  19366. // circular dependency which will result in a runtime error, because the injector doesn't
  19367. // exist yet. We work around the issue by creating the ComponentFactoryResolver ourselves
  19368. // and providing it, rather than letting the injector resolve it.
  19369. componentFactoryResolver = new ComponentFactoryResolver(this);
  19370. constructor(ngModuleType, _parent, additionalProviders, runInjectorInitializers = true) {
  19371. super();
  19372. this.ngModuleType = ngModuleType;
  19373. this._parent = _parent;
  19374. const ngModuleDef = getNgModuleDef(ngModuleType);
  19375. ngDevMode &&
  19376. assertDefined(ngModuleDef, `NgModule '${stringify(ngModuleType)}' is not a subtype of 'NgModuleType'.`);
  19377. this._bootstrapComponents = maybeUnwrapFn(ngModuleDef.bootstrap);
  19378. this._r3Injector = createInjectorWithoutInjectorInstances(ngModuleType, _parent, [
  19379. { provide: NgModuleRef$1, useValue: this },
  19380. {
  19381. provide: ComponentFactoryResolver$1,
  19382. useValue: this.componentFactoryResolver,
  19383. },
  19384. ...additionalProviders,
  19385. ], stringify(ngModuleType), new Set(['environment']));
  19386. // We need to resolve the injector types separately from the injector creation, because
  19387. // the module might be trying to use this ref in its constructor for DI which will cause a
  19388. // circular error that will eventually error out, because the injector isn't created yet.
  19389. if (runInjectorInitializers) {
  19390. this.resolveInjectorInitializers();
  19391. }
  19392. }
  19393. resolveInjectorInitializers() {
  19394. this._r3Injector.resolveInjectorInitializers();
  19395. this.instance = this._r3Injector.get(this.ngModuleType);
  19396. }
  19397. get injector() {
  19398. return this._r3Injector;
  19399. }
  19400. destroy() {
  19401. ngDevMode && assertDefined(this.destroyCbs, 'NgModule already destroyed');
  19402. const injector = this._r3Injector;
  19403. !injector.destroyed && injector.destroy();
  19404. this.destroyCbs.forEach((fn) => fn());
  19405. this.destroyCbs = null;
  19406. }
  19407. onDestroy(callback) {
  19408. ngDevMode && assertDefined(this.destroyCbs, 'NgModule already destroyed');
  19409. this.destroyCbs.push(callback);
  19410. }
  19411. }
  19412. class NgModuleFactory extends NgModuleFactory$1 {
  19413. moduleType;
  19414. constructor(moduleType) {
  19415. super();
  19416. this.moduleType = moduleType;
  19417. }
  19418. create(parentInjector) {
  19419. return new NgModuleRef(this.moduleType, parentInjector, []);
  19420. }
  19421. }
  19422. function createNgModuleRefWithProviders(moduleType, parentInjector, additionalProviders) {
  19423. return new NgModuleRef(moduleType, parentInjector, additionalProviders, false);
  19424. }
  19425. class EnvironmentNgModuleRefAdapter extends NgModuleRef$1 {
  19426. injector;
  19427. componentFactoryResolver = new ComponentFactoryResolver(this);
  19428. instance = null;
  19429. constructor(config) {
  19430. super();
  19431. const injector = new R3Injector([
  19432. ...config.providers,
  19433. { provide: NgModuleRef$1, useValue: this },
  19434. { provide: ComponentFactoryResolver$1, useValue: this.componentFactoryResolver },
  19435. ], config.parent || getNullInjector(), config.debugName, new Set(['environment']));
  19436. this.injector = injector;
  19437. if (config.runEnvironmentInitializers) {
  19438. injector.resolveInjectorInitializers();
  19439. }
  19440. }
  19441. destroy() {
  19442. this.injector.destroy();
  19443. }
  19444. onDestroy(callback) {
  19445. this.injector.onDestroy(callback);
  19446. }
  19447. }
  19448. /**
  19449. * Create a new environment injector.
  19450. *
  19451. * @param providers An array of providers.
  19452. * @param parent A parent environment injector.
  19453. * @param debugName An optional name for this injector instance, which will be used in error
  19454. * messages.
  19455. *
  19456. * @publicApi
  19457. */
  19458. function createEnvironmentInjector(providers, parent, debugName = null) {
  19459. const adapter = new EnvironmentNgModuleRefAdapter({
  19460. providers,
  19461. parent,
  19462. debugName,
  19463. runEnvironmentInitializers: true,
  19464. });
  19465. return adapter.injector;
  19466. }
  19467. /**
  19468. * A service used by the framework to create instances of standalone injectors. Those injectors are
  19469. * created on demand in case of dynamic component instantiation and contain ambient providers
  19470. * collected from the imports graph rooted at a given standalone component.
  19471. */
  19472. class StandaloneService {
  19473. _injector;
  19474. cachedInjectors = new Map();
  19475. constructor(_injector) {
  19476. this._injector = _injector;
  19477. }
  19478. getOrCreateStandaloneInjector(componentDef) {
  19479. if (!componentDef.standalone) {
  19480. return null;
  19481. }
  19482. if (!this.cachedInjectors.has(componentDef)) {
  19483. const providers = internalImportProvidersFrom(false, componentDef.type);
  19484. const standaloneInjector = providers.length > 0
  19485. ? createEnvironmentInjector([providers], this._injector, `Standalone[${componentDef.type.name}]`)
  19486. : null;
  19487. this.cachedInjectors.set(componentDef, standaloneInjector);
  19488. }
  19489. return this.cachedInjectors.get(componentDef);
  19490. }
  19491. ngOnDestroy() {
  19492. try {
  19493. for (const injector of this.cachedInjectors.values()) {
  19494. if (injector !== null) {
  19495. injector.destroy();
  19496. }
  19497. }
  19498. }
  19499. finally {
  19500. this.cachedInjectors.clear();
  19501. }
  19502. }
  19503. /** @nocollapse */
  19504. static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
  19505. token: StandaloneService,
  19506. providedIn: 'environment',
  19507. factory: () => new StandaloneService(ɵɵinject(EnvironmentInjector)),
  19508. });
  19509. }
  19510. /**
  19511. * Create a component definition object.
  19512. *
  19513. *
  19514. * # Example
  19515. * ```ts
  19516. * class MyComponent {
  19517. * // Generated by Angular Template Compiler
  19518. * // [Symbol] syntax will not be supported by TypeScript until v2.7
  19519. * static ɵcmp = defineComponent({
  19520. * ...
  19521. * });
  19522. * }
  19523. * ```
  19524. * @codeGenApi
  19525. */
  19526. function ɵɵdefineComponent(componentDefinition) {
  19527. return noSideEffects(() => {
  19528. // Initialize ngDevMode. This must be the first statement in ɵɵdefineComponent.
  19529. // See the `initNgDevMode` docstring for more information.
  19530. (typeof ngDevMode === 'undefined' || ngDevMode) && initNgDevMode();
  19531. const baseDef = getNgDirectiveDef(componentDefinition);
  19532. const def = {
  19533. ...baseDef,
  19534. decls: componentDefinition.decls,
  19535. vars: componentDefinition.vars,
  19536. template: componentDefinition.template,
  19537. consts: componentDefinition.consts || null,
  19538. ngContentSelectors: componentDefinition.ngContentSelectors,
  19539. onPush: componentDefinition.changeDetection === ChangeDetectionStrategy.OnPush,
  19540. directiveDefs: null, // assigned in noSideEffects
  19541. pipeDefs: null, // assigned in noSideEffects
  19542. dependencies: (baseDef.standalone && componentDefinition.dependencies) || null,
  19543. getStandaloneInjector: baseDef.standalone
  19544. ? (parentInjector) => {
  19545. return parentInjector.get(StandaloneService).getOrCreateStandaloneInjector(def);
  19546. }
  19547. : null,
  19548. getExternalStyles: null,
  19549. signals: componentDefinition.signals ?? false,
  19550. data: componentDefinition.data || {},
  19551. encapsulation: componentDefinition.encapsulation || ViewEncapsulation.Emulated,
  19552. styles: componentDefinition.styles || EMPTY_ARRAY,
  19553. _: null,
  19554. schemas: componentDefinition.schemas || null,
  19555. tView: null,
  19556. id: '',
  19557. };
  19558. // TODO: Do we still need/want this ?
  19559. if (baseDef.standalone) {
  19560. performanceMarkFeature('NgStandalone');
  19561. }
  19562. initFeatures(def);
  19563. const dependencies = componentDefinition.dependencies;
  19564. def.directiveDefs = extractDefListOrFactory(dependencies, /* pipeDef */ false);
  19565. def.pipeDefs = extractDefListOrFactory(dependencies, /* pipeDef */ true);
  19566. def.id = getComponentId(def);
  19567. return def;
  19568. });
  19569. }
  19570. function extractDirectiveDef(type) {
  19571. return getComponentDef(type) || getDirectiveDef(type);
  19572. }
  19573. function nonNull(value) {
  19574. return value !== null;
  19575. }
  19576. /**
  19577. * @codeGenApi
  19578. */
  19579. function ɵɵdefineNgModule(def) {
  19580. return noSideEffects(() => {
  19581. const res = {
  19582. type: def.type,
  19583. bootstrap: def.bootstrap || EMPTY_ARRAY,
  19584. declarations: def.declarations || EMPTY_ARRAY,
  19585. imports: def.imports || EMPTY_ARRAY,
  19586. exports: def.exports || EMPTY_ARRAY,
  19587. transitiveCompileScopes: null,
  19588. schemas: def.schemas || null,
  19589. id: def.id || null,
  19590. };
  19591. return res;
  19592. });
  19593. }
  19594. /**
  19595. * Converts binding objects from the `DirectiveDefinition` into more efficient
  19596. * lookup dictionaries that are optimized for the framework runtime.
  19597. *
  19598. * This function converts inputs or output directive information into new objects
  19599. * where the public name conveniently maps to the minified internal field name.
  19600. *
  19601. * For inputs, the input flags are additionally persisted into the new data structure,
  19602. * so that those can be quickly retrieved when needed.
  19603. *
  19604. * e.g. for
  19605. *
  19606. * ```ts
  19607. * class Comp {
  19608. * @Input()
  19609. * propName1: string;
  19610. *
  19611. * @Input('publicName2')
  19612. * declaredPropName2: number;
  19613. *
  19614. * inputSignal = input(3);
  19615. * }
  19616. * ```
  19617. *
  19618. * will be serialized as
  19619. *
  19620. * ```ts
  19621. * {
  19622. * propName1: 'propName1',
  19623. * declaredPropName2: ['publicName2', 'declaredPropName2'],
  19624. * inputSignal: [InputFlags.SignalBased, 'inputSignal'],
  19625. * }
  19626. * ```
  19627. *
  19628. * which is than translated by the minifier as:
  19629. *
  19630. * ```ts
  19631. * {
  19632. * minifiedPropName1: 'propName1',
  19633. * minifiedPropName2: ['publicName2', 'declaredPropName2'],
  19634. * minifiedInputSignal: [InputFlags.SignalBased, 'inputSignal'],
  19635. * }
  19636. * ```
  19637. *
  19638. * becomes: (public name => minifiedName + isSignal if needed)
  19639. *
  19640. * ```ts
  19641. * {
  19642. * 'propName1': 'minifiedPropName1',
  19643. * 'publicName2': 'minifiedPropName2',
  19644. * 'inputSignal': ['minifiedInputSignal', InputFlags.SignalBased],
  19645. * }
  19646. * ```
  19647. *
  19648. * Optionally the function can take `declaredInputs` which will result
  19649. * in: (public name => declared name)
  19650. *
  19651. * ```ts
  19652. * {
  19653. * 'propName1': 'propName1',
  19654. * 'publicName2': 'declaredPropName2',
  19655. * 'inputSignal': 'inputSignal',
  19656. * }
  19657. * ```
  19658. *
  19659. */
  19660. function parseAndConvertInputsForDefinition(obj, declaredInputs) {
  19661. if (obj == null)
  19662. return EMPTY_OBJ;
  19663. const newLookup = {};
  19664. for (const minifiedKey in obj) {
  19665. if (obj.hasOwnProperty(minifiedKey)) {
  19666. const value = obj[minifiedKey];
  19667. let publicName;
  19668. let declaredName;
  19669. let inputFlags;
  19670. let transform;
  19671. if (Array.isArray(value)) {
  19672. inputFlags = value[0];
  19673. publicName = value[1];
  19674. declaredName = value[2] ?? publicName; // declared name might not be set to save bytes.
  19675. transform = value[3] || null;
  19676. }
  19677. else {
  19678. publicName = value;
  19679. declaredName = value;
  19680. inputFlags = InputFlags.None;
  19681. transform = null;
  19682. }
  19683. newLookup[publicName] = [minifiedKey, inputFlags, transform];
  19684. declaredInputs[publicName] = declaredName;
  19685. }
  19686. }
  19687. return newLookup;
  19688. }
  19689. function parseAndConvertOutputsForDefinition(obj) {
  19690. if (obj == null)
  19691. return EMPTY_OBJ;
  19692. const newLookup = {};
  19693. for (const minifiedKey in obj) {
  19694. if (obj.hasOwnProperty(minifiedKey)) {
  19695. newLookup[obj[minifiedKey]] = minifiedKey;
  19696. }
  19697. }
  19698. return newLookup;
  19699. }
  19700. /**
  19701. * Create a directive definition object.
  19702. *
  19703. * # Example
  19704. * ```ts
  19705. * class MyDirective {
  19706. * // Generated by Angular Template Compiler
  19707. * // [Symbol] syntax will not be supported by TypeScript until v2.7
  19708. * static ɵdir = ɵɵdefineDirective({
  19709. * ...
  19710. * });
  19711. * }
  19712. * ```
  19713. *
  19714. * @codeGenApi
  19715. */
  19716. function ɵɵdefineDirective(directiveDefinition) {
  19717. return noSideEffects(() => {
  19718. const def = getNgDirectiveDef(directiveDefinition);
  19719. initFeatures(def);
  19720. return def;
  19721. });
  19722. }
  19723. /**
  19724. * Create a pipe definition object.
  19725. *
  19726. * # Example
  19727. * ```ts
  19728. * class MyPipe implements PipeTransform {
  19729. * // Generated by Angular Template Compiler
  19730. * static ɵpipe = definePipe({
  19731. * ...
  19732. * });
  19733. * }
  19734. * ```
  19735. * @param pipeDef Pipe definition generated by the compiler
  19736. *
  19737. * @codeGenApi
  19738. */
  19739. function ɵɵdefinePipe(pipeDef) {
  19740. return {
  19741. type: pipeDef.type,
  19742. name: pipeDef.name,
  19743. factory: null,
  19744. pure: pipeDef.pure !== false,
  19745. standalone: pipeDef.standalone ?? true,
  19746. onDestroy: pipeDef.type.prototype.ngOnDestroy || null,
  19747. };
  19748. }
  19749. function getNgDirectiveDef(directiveDefinition) {
  19750. const declaredInputs = {};
  19751. return {
  19752. type: directiveDefinition.type,
  19753. providersResolver: null,
  19754. factory: null,
  19755. hostBindings: directiveDefinition.hostBindings || null,
  19756. hostVars: directiveDefinition.hostVars || 0,
  19757. hostAttrs: directiveDefinition.hostAttrs || null,
  19758. contentQueries: directiveDefinition.contentQueries || null,
  19759. declaredInputs: declaredInputs,
  19760. inputConfig: directiveDefinition.inputs || EMPTY_OBJ,
  19761. exportAs: directiveDefinition.exportAs || null,
  19762. standalone: directiveDefinition.standalone ?? true,
  19763. signals: directiveDefinition.signals === true,
  19764. selectors: directiveDefinition.selectors || EMPTY_ARRAY,
  19765. viewQuery: directiveDefinition.viewQuery || null,
  19766. features: directiveDefinition.features || null,
  19767. setInput: null,
  19768. findHostDirectiveDefs: null,
  19769. hostDirectives: null,
  19770. inputs: parseAndConvertInputsForDefinition(directiveDefinition.inputs, declaredInputs),
  19771. outputs: parseAndConvertOutputsForDefinition(directiveDefinition.outputs),
  19772. debugInfo: null,
  19773. };
  19774. }
  19775. function initFeatures(definition) {
  19776. definition.features?.forEach((fn) => fn(definition));
  19777. }
  19778. function extractDefListOrFactory(dependencies, pipeDef) {
  19779. if (!dependencies) {
  19780. return null;
  19781. }
  19782. const defExtractor = pipeDef ? getPipeDef$1 : extractDirectiveDef;
  19783. return () => (typeof dependencies === 'function' ? dependencies() : dependencies)
  19784. .map((dep) => defExtractor(dep))
  19785. .filter(nonNull);
  19786. }
  19787. /**
  19788. * A map that contains the generated component IDs and type.
  19789. */
  19790. const GENERATED_COMP_IDS = new Map();
  19791. /**
  19792. * A method can returns a component ID from the component definition using a variant of DJB2 hash
  19793. * algorithm.
  19794. */
  19795. function getComponentId(componentDef) {
  19796. let hash = 0;
  19797. // For components with i18n in templates, the `consts` array is generated by the compiler
  19798. // as a function. If client and server bundles were produced with different minification
  19799. // configurations, the serializable contents of the function body would be different on
  19800. // the client and on the server. This might result in different ids generated. To avoid this
  19801. // issue, we do not take the `consts` contents into account if it's a function.
  19802. // See https://github.com/angular/angular/issues/58713.
  19803. const componentDefConsts = typeof componentDef.consts === 'function' ? '' : componentDef.consts;
  19804. // We cannot rely solely on the component selector as the same selector can be used in different
  19805. // modules.
  19806. //
  19807. // `componentDef.style` is not used, due to it causing inconsistencies. Ex: when server
  19808. // component styles has no sourcemaps and browsers do.
  19809. //
  19810. // Example:
  19811. // https://github.com/angular/components/blob/d9f82c8f95309e77a6d82fd574c65871e91354c2/src/material/core/option/option.ts#L248
  19812. // https://github.com/angular/components/blob/285f46dc2b4c5b127d356cb7c4714b221f03ce50/src/material/legacy-core/option/option.ts#L32
  19813. const hashSelectors = [
  19814. componentDef.selectors,
  19815. componentDef.ngContentSelectors,
  19816. componentDef.hostVars,
  19817. componentDef.hostAttrs,
  19818. componentDefConsts,
  19819. componentDef.vars,
  19820. componentDef.decls,
  19821. componentDef.encapsulation,
  19822. componentDef.standalone,
  19823. componentDef.signals,
  19824. componentDef.exportAs,
  19825. JSON.stringify(componentDef.inputs),
  19826. JSON.stringify(componentDef.outputs),
  19827. // We cannot use 'componentDef.type.name' as the name of the symbol will change and will not
  19828. // match in the server and browser bundles.
  19829. Object.getOwnPropertyNames(componentDef.type.prototype),
  19830. !!componentDef.contentQueries,
  19831. !!componentDef.viewQuery,
  19832. ];
  19833. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  19834. // If client and server bundles were produced with different minification configurations,
  19835. // the serializable contents of the function body would be different on the client and on
  19836. // the server. Ensure that we do not accidentally use functions in component id computation.
  19837. for (const item of hashSelectors) {
  19838. assertNotEqual(typeof item, 'function', 'Internal error: attempting to use a function in component id computation logic.');
  19839. }
  19840. }
  19841. for (const char of hashSelectors.join('|')) {
  19842. hash = (Math.imul(31, hash) + char.charCodeAt(0)) << 0;
  19843. }
  19844. // Force positive number hash.
  19845. // 2147483647 = equivalent of Integer.MAX_VALUE.
  19846. hash += 2147483647 + 1;
  19847. const compId = 'c' + hash;
  19848. if ((typeof ngDevMode === 'undefined' || ngDevMode) &&
  19849. // Skip the check on the server since we can't guarantee the same component instance between
  19850. // requests. Note that we can't use DI to check if we're on the server, because the component
  19851. // hasn't been instantiated yet.
  19852. (typeof ngServerMode === 'undefined' || !ngServerMode)) {
  19853. if (GENERATED_COMP_IDS.has(compId)) {
  19854. const previousCompDefType = GENERATED_COMP_IDS.get(compId);
  19855. if (previousCompDefType !== componentDef.type) {
  19856. console.warn(formatRuntimeError(-912 /* RuntimeErrorCode.COMPONENT_ID_COLLISION */, `Component ID generation collision detected. Components '${previousCompDefType.name}' and '${componentDef.type.name}' with selector '${stringifyCSSSelectorList(componentDef.selectors)}' generated the same component ID. To fix this, you can change the selector of one of those components or add an extra host attribute to force a different ID.`));
  19857. }
  19858. }
  19859. else {
  19860. GENERATED_COMP_IDS.set(compId, componentDef.type);
  19861. }
  19862. }
  19863. return compId;
  19864. }
  19865. function getSuperType(type) {
  19866. return Object.getPrototypeOf(type.prototype).constructor;
  19867. }
  19868. /**
  19869. * Merges the definition from a super class to a sub class.
  19870. * @param definition The definition that is a SubClass of another directive of component
  19871. *
  19872. * @codeGenApi
  19873. */
  19874. function ɵɵInheritDefinitionFeature(definition) {
  19875. let superType = getSuperType(definition.type);
  19876. let shouldInheritFields = true;
  19877. const inheritanceChain = [definition];
  19878. while (superType) {
  19879. let superDef = undefined;
  19880. if (isComponentDef(definition)) {
  19881. // Don't use getComponentDef/getDirectiveDef. This logic relies on inheritance.
  19882. superDef = superType.ɵcmp || superType.ɵdir;
  19883. }
  19884. else {
  19885. if (superType.ɵcmp) {
  19886. throw new RuntimeError(903 /* RuntimeErrorCode.INVALID_INHERITANCE */, ngDevMode &&
  19887. `Directives cannot inherit Components. Directive ${stringifyForError(definition.type)} is attempting to extend component ${stringifyForError(superType)}`);
  19888. }
  19889. // Don't use getComponentDef/getDirectiveDef. This logic relies on inheritance.
  19890. superDef = superType.ɵdir;
  19891. }
  19892. if (superDef) {
  19893. if (shouldInheritFields) {
  19894. inheritanceChain.push(superDef);
  19895. // Some fields in the definition may be empty, if there were no values to put in them that
  19896. // would've justified object creation. Unwrap them if necessary.
  19897. const writeableDef = definition;
  19898. writeableDef.inputs = maybeUnwrapEmpty(definition.inputs);
  19899. writeableDef.declaredInputs = maybeUnwrapEmpty(definition.declaredInputs);
  19900. writeableDef.outputs = maybeUnwrapEmpty(definition.outputs);
  19901. // Merge hostBindings
  19902. const superHostBindings = superDef.hostBindings;
  19903. superHostBindings && inheritHostBindings(definition, superHostBindings);
  19904. // Merge queries
  19905. const superViewQuery = superDef.viewQuery;
  19906. const superContentQueries = superDef.contentQueries;
  19907. superViewQuery && inheritViewQuery(definition, superViewQuery);
  19908. superContentQueries && inheritContentQueries(definition, superContentQueries);
  19909. // Merge inputs and outputs
  19910. mergeInputsWithTransforms(definition, superDef);
  19911. fillProperties(definition.outputs, superDef.outputs);
  19912. // Merge animations metadata.
  19913. // If `superDef` is a Component, the `data` field is present (defaults to an empty object).
  19914. if (isComponentDef(superDef) && superDef.data.animation) {
  19915. // If super def is a Component, the `definition` is also a Component, since Directives can
  19916. // not inherit Components (we throw an error above and cannot reach this code).
  19917. const defData = definition.data;
  19918. defData.animation = (defData.animation || []).concat(superDef.data.animation);
  19919. }
  19920. }
  19921. // Run parent features
  19922. const features = superDef.features;
  19923. if (features) {
  19924. for (let i = 0; i < features.length; i++) {
  19925. const feature = features[i];
  19926. if (feature && feature.ngInherit) {
  19927. feature(definition);
  19928. }
  19929. // If `InheritDefinitionFeature` is a part of the current `superDef`, it means that this
  19930. // def already has all the necessary information inherited from its super class(es), so we
  19931. // can stop merging fields from super classes. However we need to iterate through the
  19932. // prototype chain to look for classes that might contain other "features" (like
  19933. // NgOnChanges), which we should invoke for the original `definition`. We set the
  19934. // `shouldInheritFields` flag to indicate that, essentially skipping fields inheritance
  19935. // logic and only invoking functions from the "features" list.
  19936. if (feature === ɵɵInheritDefinitionFeature) {
  19937. shouldInheritFields = false;
  19938. }
  19939. }
  19940. }
  19941. }
  19942. superType = Object.getPrototypeOf(superType);
  19943. }
  19944. mergeHostAttrsAcrossInheritance(inheritanceChain);
  19945. }
  19946. function mergeInputsWithTransforms(target, source) {
  19947. for (const key in source.inputs) {
  19948. if (!source.inputs.hasOwnProperty(key)) {
  19949. continue;
  19950. }
  19951. if (target.inputs.hasOwnProperty(key)) {
  19952. continue;
  19953. }
  19954. const value = source.inputs[key];
  19955. if (value !== undefined) {
  19956. target.inputs[key] = value;
  19957. target.declaredInputs[key] = source.declaredInputs[key];
  19958. }
  19959. }
  19960. }
  19961. /**
  19962. * Merge the `hostAttrs` and `hostVars` from the inherited parent to the base class.
  19963. *
  19964. * @param inheritanceChain A list of `WritableDefs` starting at the top most type and listing
  19965. * sub-types in order. For each type take the `hostAttrs` and `hostVars` and merge it with the child
  19966. * type.
  19967. */
  19968. function mergeHostAttrsAcrossInheritance(inheritanceChain) {
  19969. let hostVars = 0;
  19970. let hostAttrs = null;
  19971. // We process the inheritance order from the base to the leaves here.
  19972. for (let i = inheritanceChain.length - 1; i >= 0; i--) {
  19973. const def = inheritanceChain[i];
  19974. // For each `hostVars`, we need to add the superclass amount.
  19975. def.hostVars = hostVars += def.hostVars;
  19976. // for each `hostAttrs` we need to merge it with superclass.
  19977. def.hostAttrs = mergeHostAttrs(def.hostAttrs, (hostAttrs = mergeHostAttrs(hostAttrs, def.hostAttrs)));
  19978. }
  19979. }
  19980. function maybeUnwrapEmpty(value) {
  19981. if (value === EMPTY_OBJ) {
  19982. return {};
  19983. }
  19984. else if (value === EMPTY_ARRAY) {
  19985. return [];
  19986. }
  19987. else {
  19988. return value;
  19989. }
  19990. }
  19991. function inheritViewQuery(definition, superViewQuery) {
  19992. const prevViewQuery = definition.viewQuery;
  19993. if (prevViewQuery) {
  19994. definition.viewQuery = (rf, ctx) => {
  19995. superViewQuery(rf, ctx);
  19996. prevViewQuery(rf, ctx);
  19997. };
  19998. }
  19999. else {
  20000. definition.viewQuery = superViewQuery;
  20001. }
  20002. }
  20003. function inheritContentQueries(definition, superContentQueries) {
  20004. const prevContentQueries = definition.contentQueries;
  20005. if (prevContentQueries) {
  20006. definition.contentQueries = (rf, ctx, directiveIndex) => {
  20007. superContentQueries(rf, ctx, directiveIndex);
  20008. prevContentQueries(rf, ctx, directiveIndex);
  20009. };
  20010. }
  20011. else {
  20012. definition.contentQueries = superContentQueries;
  20013. }
  20014. }
  20015. function inheritHostBindings(definition, superHostBindings) {
  20016. const prevHostBindings = definition.hostBindings;
  20017. if (prevHostBindings) {
  20018. definition.hostBindings = (rf, ctx) => {
  20019. superHostBindings(rf, ctx);
  20020. prevHostBindings(rf, ctx);
  20021. };
  20022. }
  20023. else {
  20024. definition.hostBindings = superHostBindings;
  20025. }
  20026. }
  20027. /**
  20028. * Fields which exist on either directive or component definitions, and need to be copied from
  20029. * parent to child classes by the `ɵɵCopyDefinitionFeature`.
  20030. */
  20031. const COPY_DIRECTIVE_FIELDS = [
  20032. // The child class should use the providers of its parent.
  20033. 'providersResolver',
  20034. // Not listed here are any fields which are handled by the `ɵɵInheritDefinitionFeature`, such
  20035. // as inputs, outputs, and host binding functions.
  20036. ];
  20037. /**
  20038. * Fields which exist only on component definitions, and need to be copied from parent to child
  20039. * classes by the `ɵɵCopyDefinitionFeature`.
  20040. *
  20041. * The type here allows any field of `ComponentDef` which is not also a property of `DirectiveDef`,
  20042. * since those should go in `COPY_DIRECTIVE_FIELDS` above.
  20043. */
  20044. const COPY_COMPONENT_FIELDS = [
  20045. // The child class should use the template function of its parent, including all template
  20046. // semantics.
  20047. 'template',
  20048. 'decls',
  20049. 'consts',
  20050. 'vars',
  20051. 'onPush',
  20052. 'ngContentSelectors',
  20053. // The child class should use the CSS styles of its parent, including all styling semantics.
  20054. 'styles',
  20055. 'encapsulation',
  20056. // The child class should be checked by the runtime in the same way as its parent.
  20057. 'schemas',
  20058. ];
  20059. /**
  20060. * Copies the fields not handled by the `ɵɵInheritDefinitionFeature` from the supertype of a
  20061. * definition.
  20062. *
  20063. * This exists primarily to support ngcc migration of an existing View Engine pattern, where an
  20064. * entire decorator is inherited from a parent to a child class. When ngcc detects this case, it
  20065. * generates a skeleton definition on the child class, and applies this feature.
  20066. *
  20067. * The `ɵɵCopyDefinitionFeature` then copies any needed fields from the parent class' definition,
  20068. * including things like the component template function.
  20069. *
  20070. * @param definition The definition of a child class which inherits from a parent class with its
  20071. * own definition.
  20072. *
  20073. * @codeGenApi
  20074. */
  20075. function ɵɵCopyDefinitionFeature(definition) {
  20076. let superType = getSuperType(definition.type);
  20077. let superDef = undefined;
  20078. if (isComponentDef(definition)) {
  20079. // Don't use getComponentDef/getDirectiveDef. This logic relies on inheritance.
  20080. superDef = superType.ɵcmp;
  20081. }
  20082. else {
  20083. // Don't use getComponentDef/getDirectiveDef. This logic relies on inheritance.
  20084. superDef = superType.ɵdir;
  20085. }
  20086. // Needed because `definition` fields are readonly.
  20087. const defAny = definition;
  20088. // Copy over any fields that apply to either directives or components.
  20089. for (const field of COPY_DIRECTIVE_FIELDS) {
  20090. defAny[field] = superDef[field];
  20091. }
  20092. if (isComponentDef(superDef)) {
  20093. // Copy over any component-specific fields.
  20094. for (const field of COPY_COMPONENT_FIELDS) {
  20095. defAny[field] = superDef[field];
  20096. }
  20097. }
  20098. }
  20099. /**
  20100. * This feature adds the host directives behavior to a directive definition by patching a
  20101. * function onto it. The expectation is that the runtime will invoke the function during
  20102. * directive matching.
  20103. *
  20104. * For example:
  20105. * ```ts
  20106. * class ComponentWithHostDirective {
  20107. * static ɵcmp = defineComponent({
  20108. * type: ComponentWithHostDirective,
  20109. * features: [ɵɵHostDirectivesFeature([
  20110. * SimpleHostDirective,
  20111. * {directive: AdvancedHostDirective, inputs: ['foo: alias'], outputs: ['bar']},
  20112. * ])]
  20113. * });
  20114. * }
  20115. * ```
  20116. *
  20117. * @codeGenApi
  20118. */
  20119. function ɵɵHostDirectivesFeature(rawHostDirectives) {
  20120. const feature = (definition) => {
  20121. const isEager = Array.isArray(rawHostDirectives);
  20122. if (definition.hostDirectives === null) {
  20123. definition.findHostDirectiveDefs = findHostDirectiveDefs;
  20124. definition.hostDirectives = isEager
  20125. ? rawHostDirectives.map(createHostDirectiveDef)
  20126. : [rawHostDirectives];
  20127. }
  20128. else if (isEager) {
  20129. definition.hostDirectives.unshift(...rawHostDirectives.map(createHostDirectiveDef));
  20130. }
  20131. else {
  20132. definition.hostDirectives.unshift(rawHostDirectives);
  20133. }
  20134. };
  20135. feature.ngInherit = true;
  20136. return feature;
  20137. }
  20138. function findHostDirectiveDefs(currentDef, matchedDefs, hostDirectiveDefs) {
  20139. if (currentDef.hostDirectives !== null) {
  20140. for (const configOrFn of currentDef.hostDirectives) {
  20141. if (typeof configOrFn === 'function') {
  20142. const resolved = configOrFn();
  20143. for (const config of resolved) {
  20144. trackHostDirectiveDef(createHostDirectiveDef(config), matchedDefs, hostDirectiveDefs);
  20145. }
  20146. }
  20147. else {
  20148. trackHostDirectiveDef(configOrFn, matchedDefs, hostDirectiveDefs);
  20149. }
  20150. }
  20151. }
  20152. }
  20153. /** Tracks a single host directive during directive matching. */
  20154. function trackHostDirectiveDef(def, matchedDefs, hostDirectiveDefs) {
  20155. const hostDirectiveDef = getDirectiveDef(def.directive);
  20156. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  20157. validateHostDirective(def, hostDirectiveDef);
  20158. }
  20159. // We need to patch the `declaredInputs` so that
  20160. // `ngOnChanges` can map the properties correctly.
  20161. patchDeclaredInputs(hostDirectiveDef.declaredInputs, def.inputs);
  20162. // Host directives execute before the host so that its host bindings can be overwritten.
  20163. findHostDirectiveDefs(hostDirectiveDef, matchedDefs, hostDirectiveDefs);
  20164. hostDirectiveDefs.set(hostDirectiveDef, def);
  20165. matchedDefs.push(hostDirectiveDef);
  20166. }
  20167. /** Creates a `HostDirectiveDef` from a used-defined host directive configuration. */
  20168. function createHostDirectiveDef(config) {
  20169. return typeof config === 'function'
  20170. ? { directive: resolveForwardRef(config), inputs: EMPTY_OBJ, outputs: EMPTY_OBJ }
  20171. : {
  20172. directive: resolveForwardRef(config.directive),
  20173. inputs: bindingArrayToMap(config.inputs),
  20174. outputs: bindingArrayToMap(config.outputs),
  20175. };
  20176. }
  20177. /**
  20178. * Converts an array in the form of `['publicName', 'alias', 'otherPublicName', 'otherAlias']` into
  20179. * a map in the form of `{publicName: 'alias', otherPublicName: 'otherAlias'}`.
  20180. */
  20181. function bindingArrayToMap(bindings) {
  20182. if (bindings === undefined || bindings.length === 0) {
  20183. return EMPTY_OBJ;
  20184. }
  20185. const result = {};
  20186. for (let i = 0; i < bindings.length; i += 2) {
  20187. result[bindings[i]] = bindings[i + 1];
  20188. }
  20189. return result;
  20190. }
  20191. /**
  20192. * `ngOnChanges` has some leftover legacy ViewEngine behavior where the keys inside the
  20193. * `SimpleChanges` event refer to the *declared* name of the input, not its public name or its
  20194. * minified name. E.g. in `@Input('alias') foo: string`, the name in the `SimpleChanges` object
  20195. * will always be `foo`, and not `alias` or the minified name of `foo` in apps using property
  20196. * minification.
  20197. *
  20198. * This is achieved through the `DirectiveDef.declaredInputs` map that is constructed when the
  20199. * definition is declared. When a property is written to the directive instance, the
  20200. * `NgOnChangesFeature` will try to remap the property name being written to using the
  20201. * `declaredInputs`.
  20202. *
  20203. * Since the host directive input remapping happens during directive matching, `declaredInputs`
  20204. * won't contain the new alias that the input is available under. This function addresses the
  20205. * issue by patching the host directive aliases to the `declaredInputs`. There is *not* a risk of
  20206. * this patching accidentally introducing new inputs to the host directive, because `declaredInputs`
  20207. * is used *only* by the `NgOnChangesFeature` when determining what name is used in the
  20208. * `SimpleChanges` object which won't be reached if an input doesn't exist.
  20209. */
  20210. function patchDeclaredInputs(declaredInputs, exposedInputs) {
  20211. for (const publicName in exposedInputs) {
  20212. if (exposedInputs.hasOwnProperty(publicName)) {
  20213. const remappedPublicName = exposedInputs[publicName];
  20214. const privateName = declaredInputs[publicName];
  20215. // We *technically* shouldn't be able to hit this case because we can't have multiple
  20216. // inputs on the same property and we have validations against conflicting aliases in
  20217. // `validateMappings`. If we somehow did, it would lead to `ngOnChanges` being invoked
  20218. // with the wrong name so we have a non-user-friendly assertion here just in case.
  20219. if ((typeof ngDevMode === 'undefined' || ngDevMode) &&
  20220. declaredInputs.hasOwnProperty(remappedPublicName)) {
  20221. assertEqual(declaredInputs[remappedPublicName], declaredInputs[publicName], `Conflicting host directive input alias ${publicName}.`);
  20222. }
  20223. declaredInputs[remappedPublicName] = privateName;
  20224. }
  20225. }
  20226. }
  20227. /**
  20228. * Verifies that the host directive has been configured correctly.
  20229. * @param hostDirectiveConfig Host directive configuration object.
  20230. * @param directiveDef Directive definition of the host directive.
  20231. */
  20232. function validateHostDirective(hostDirectiveConfig, directiveDef) {
  20233. const type = hostDirectiveConfig.directive;
  20234. if (directiveDef === null) {
  20235. if (getComponentDef(type) !== null) {
  20236. throw new RuntimeError(310 /* RuntimeErrorCode.HOST_DIRECTIVE_COMPONENT */, `Host directive ${type.name} cannot be a component.`);
  20237. }
  20238. throw new RuntimeError(307 /* RuntimeErrorCode.HOST_DIRECTIVE_UNRESOLVABLE */, `Could not resolve metadata for host directive ${type.name}. ` +
  20239. `Make sure that the ${type.name} class is annotated with an @Directive decorator.`);
  20240. }
  20241. if (!directiveDef.standalone) {
  20242. throw new RuntimeError(308 /* RuntimeErrorCode.HOST_DIRECTIVE_NOT_STANDALONE */, `Host directive ${directiveDef.type.name} must be standalone.`);
  20243. }
  20244. validateMappings('input', directiveDef, hostDirectiveConfig.inputs);
  20245. validateMappings('output', directiveDef, hostDirectiveConfig.outputs);
  20246. }
  20247. /**
  20248. * Checks that the host directive inputs/outputs configuration is valid.
  20249. * @param bindingType Kind of binding that is being validated. Used in the error message.
  20250. * @param def Definition of the host directive that is being validated against.
  20251. * @param hostDirectiveBindings Host directive mapping object that shold be validated.
  20252. */
  20253. function validateMappings(bindingType, def, hostDirectiveBindings) {
  20254. const className = def.type.name;
  20255. const bindings = bindingType === 'input' ? def.inputs : def.outputs;
  20256. for (const publicName in hostDirectiveBindings) {
  20257. if (hostDirectiveBindings.hasOwnProperty(publicName)) {
  20258. if (!bindings.hasOwnProperty(publicName)) {
  20259. throw new RuntimeError(311 /* RuntimeErrorCode.HOST_DIRECTIVE_UNDEFINED_BINDING */, `Directive ${className} does not have an ${bindingType} with a public name of ${publicName}.`);
  20260. }
  20261. const remappedPublicName = hostDirectiveBindings[publicName];
  20262. if (bindings.hasOwnProperty(remappedPublicName) && remappedPublicName !== publicName) {
  20263. throw new RuntimeError(312 /* RuntimeErrorCode.HOST_DIRECTIVE_CONFLICTING_ALIAS */, `Cannot alias ${bindingType} ${publicName} of host directive ${className} to ${remappedPublicName}, because it already has a different ${bindingType} with the same public name.`);
  20264. }
  20265. }
  20266. }
  20267. }
  20268. function isListLikeIterable(obj) {
  20269. if (!isJsObject(obj))
  20270. return false;
  20271. return (Array.isArray(obj) ||
  20272. (!(obj instanceof Map) && // JS Map are iterables but return entries as [k, v]
  20273. Symbol.iterator in obj)); // JS Iterable have a Symbol.iterator prop
  20274. }
  20275. function areIterablesEqual(a, b, comparator) {
  20276. const iterator1 = a[Symbol.iterator]();
  20277. const iterator2 = b[Symbol.iterator]();
  20278. while (true) {
  20279. const item1 = iterator1.next();
  20280. const item2 = iterator2.next();
  20281. if (item1.done && item2.done)
  20282. return true;
  20283. if (item1.done || item2.done)
  20284. return false;
  20285. if (!comparator(item1.value, item2.value))
  20286. return false;
  20287. }
  20288. }
  20289. function iterateListLike(obj, fn) {
  20290. if (Array.isArray(obj)) {
  20291. for (let i = 0; i < obj.length; i++) {
  20292. fn(obj[i]);
  20293. }
  20294. }
  20295. else {
  20296. const iterator = obj[Symbol.iterator]();
  20297. let item;
  20298. while (!(item = iterator.next()).done) {
  20299. fn(item.value);
  20300. }
  20301. }
  20302. }
  20303. function isJsObject(o) {
  20304. return o !== null && (typeof o === 'function' || typeof o === 'object');
  20305. }
  20306. function devModeEqual(a, b) {
  20307. const isListLikeIterableA = isListLikeIterable(a);
  20308. const isListLikeIterableB = isListLikeIterable(b);
  20309. if (isListLikeIterableA && isListLikeIterableB) {
  20310. return areIterablesEqual(a, b, devModeEqual);
  20311. }
  20312. else {
  20313. const isAObject = a && (typeof a === 'object' || typeof a === 'function');
  20314. const isBObject = b && (typeof b === 'object' || typeof b === 'function');
  20315. if (!isListLikeIterableA && isAObject && !isListLikeIterableB && isBObject) {
  20316. return true;
  20317. }
  20318. else {
  20319. return Object.is(a, b);
  20320. }
  20321. }
  20322. }
  20323. // TODO(misko): consider inlining
  20324. /** Updates binding and returns the value. */
  20325. function updateBinding(lView, bindingIndex, value) {
  20326. return (lView[bindingIndex] = value);
  20327. }
  20328. /** Gets the current binding value. */
  20329. function getBinding(lView, bindingIndex) {
  20330. ngDevMode && assertIndexInRange(lView, bindingIndex);
  20331. ngDevMode &&
  20332. assertNotSame(lView[bindingIndex], NO_CHANGE, 'Stored value should never be NO_CHANGE.');
  20333. return lView[bindingIndex];
  20334. }
  20335. /**
  20336. * Updates binding if changed, then returns whether it was updated.
  20337. *
  20338. * This function also checks the `CheckNoChangesMode` and throws if changes are made.
  20339. * Some changes (Objects/iterables) during `CheckNoChangesMode` are exempt to comply with VE
  20340. * behavior.
  20341. *
  20342. * @param lView current `LView`
  20343. * @param bindingIndex The binding in the `LView` to check
  20344. * @param value New value to check against `lView[bindingIndex]`
  20345. * @returns `true` if the bindings has changed. (Throws if binding has changed during
  20346. * `CheckNoChangesMode`)
  20347. */
  20348. function bindingUpdated(lView, bindingIndex, value) {
  20349. ngDevMode && assertNotSame(value, NO_CHANGE, 'Incoming value should never be NO_CHANGE.');
  20350. ngDevMode &&
  20351. assertLessThan(bindingIndex, lView.length, `Slot should have been initialized to NO_CHANGE`);
  20352. const oldValue = lView[bindingIndex];
  20353. if (Object.is(oldValue, value)) {
  20354. return false;
  20355. }
  20356. else {
  20357. if (ngDevMode && isInCheckNoChangesMode()) {
  20358. // View engine didn't report undefined values as changed on the first checkNoChanges pass
  20359. // (before the change detection was run).
  20360. const oldValueToCompare = oldValue !== NO_CHANGE ? oldValue : undefined;
  20361. if (!devModeEqual(oldValueToCompare, value)) {
  20362. const details = getExpressionChangedErrorDetails(lView, bindingIndex, oldValueToCompare, value);
  20363. throwErrorIfNoChangesMode(oldValue === NO_CHANGE, details.oldValue, details.newValue, details.propName, lView);
  20364. }
  20365. // There was a change, but the `devModeEqual` decided that the change is exempt from an error.
  20366. // For this reason we exit as if no change. The early exit is needed to prevent the changed
  20367. // value to be written into `LView` (If we would write the new value that we would not see it
  20368. // as change on next CD.)
  20369. return false;
  20370. }
  20371. lView[bindingIndex] = value;
  20372. return true;
  20373. }
  20374. }
  20375. /** Updates 2 bindings if changed, then returns whether either was updated. */
  20376. function bindingUpdated2(lView, bindingIndex, exp1, exp2) {
  20377. const different = bindingUpdated(lView, bindingIndex, exp1);
  20378. return bindingUpdated(lView, bindingIndex + 1, exp2) || different;
  20379. }
  20380. /** Updates 3 bindings if changed, then returns whether any was updated. */
  20381. function bindingUpdated3(lView, bindingIndex, exp1, exp2, exp3) {
  20382. const different = bindingUpdated2(lView, bindingIndex, exp1, exp2);
  20383. return bindingUpdated(lView, bindingIndex + 2, exp3) || different;
  20384. }
  20385. /** Updates 4 bindings if changed, then returns whether any was updated. */
  20386. function bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4) {
  20387. const different = bindingUpdated2(lView, bindingIndex, exp1, exp2);
  20388. return bindingUpdated2(lView, bindingIndex + 2, exp3, exp4) || different;
  20389. }
  20390. function templateFirstCreatePass(index, tView, lView, templateFn, decls, vars, tagName, attrs, localRefsIndex) {
  20391. ngDevMode && assertFirstCreatePass(tView);
  20392. ngDevMode && ngDevMode.firstCreatePass++;
  20393. const tViewConsts = tView.consts;
  20394. // TODO(pk): refactor getOrCreateTNode to have the "create" only version
  20395. const tNode = getOrCreateTNode(tView, index, 4 /* TNodeType.Container */, tagName || null, attrs || null);
  20396. if (getBindingsEnabled()) {
  20397. resolveDirectives(tView, lView, tNode, getConstant(tViewConsts, localRefsIndex), findDirectiveDefMatches);
  20398. }
  20399. // Merge the template attrs last so that they have the highest priority.
  20400. tNode.mergedAttrs = mergeHostAttrs(tNode.mergedAttrs, tNode.attrs);
  20401. registerPostOrderHooks(tView, tNode);
  20402. const embeddedTView = (tNode.tView = createTView(2 /* TViewType.Embedded */, tNode, templateFn, decls, vars, tView.directiveRegistry, tView.pipeRegistry, null, tView.schemas, tViewConsts, null /* ssrId */));
  20403. if (tView.queries !== null) {
  20404. tView.queries.template(tView, tNode);
  20405. embeddedTView.queries = tView.queries.embeddedTView(tNode);
  20406. }
  20407. return tNode;
  20408. }
  20409. /**
  20410. * Creates an LContainer for an embedded view.
  20411. *
  20412. * @param declarationLView LView in which the template was declared.
  20413. * @param declarationTView TView in which the template wa declared.
  20414. * @param index The index of the container in the data array
  20415. * @param templateFn Inline template
  20416. * @param decls The number of nodes, local refs, and pipes for this template
  20417. * @param vars The number of bindings for this template
  20418. * @param tagName The name of the container element, if applicable
  20419. * @param attrsIndex Index of template attributes in the `consts` array.
  20420. * @param localRefs Index of the local references in the `consts` array.
  20421. * @param localRefExtractor A function which extracts local-refs values from the template.
  20422. * Defaults to the current element associated with the local-ref.
  20423. */
  20424. function declareTemplate(declarationLView, declarationTView, index, templateFn, decls, vars, tagName, attrs, localRefsIndex, localRefExtractor) {
  20425. const adjustedIndex = index + HEADER_OFFSET;
  20426. const tNode = declarationTView.firstCreatePass
  20427. ? templateFirstCreatePass(adjustedIndex, declarationTView, declarationLView, templateFn, decls, vars, tagName, attrs, localRefsIndex)
  20428. : declarationTView.data[adjustedIndex];
  20429. setCurrentTNode(tNode, false);
  20430. const comment = _locateOrCreateContainerAnchor(declarationTView, declarationLView, tNode, index);
  20431. if (wasLastNodeCreated()) {
  20432. appendChild(declarationTView, declarationLView, comment, tNode);
  20433. }
  20434. attachPatchData(comment, declarationLView);
  20435. const lContainer = createLContainer(comment, declarationLView, comment, tNode);
  20436. declarationLView[adjustedIndex] = lContainer;
  20437. addToEndOfViewTree(declarationLView, lContainer);
  20438. // If hydration is enabled, looks up dehydrated views in the DOM
  20439. // using hydration annotation info and stores those views on LContainer.
  20440. // In client-only mode, this function is a noop.
  20441. populateDehydratedViewsInLContainer(lContainer, tNode, declarationLView);
  20442. if (isDirectiveHost(tNode)) {
  20443. createDirectivesInstances(declarationTView, declarationLView, tNode);
  20444. }
  20445. if (localRefsIndex != null) {
  20446. saveResolvedLocalsInData(declarationLView, tNode, localRefExtractor);
  20447. }
  20448. return tNode;
  20449. }
  20450. /**
  20451. * Creates an LContainer for an ng-template (dynamically-inserted view), e.g.
  20452. *
  20453. * <ng-template #foo>
  20454. * <div></div>
  20455. * </ng-template>
  20456. *
  20457. * @param index The index of the container in the data array
  20458. * @param templateFn Inline template
  20459. * @param decls The number of nodes, local refs, and pipes for this template
  20460. * @param vars The number of bindings for this template
  20461. * @param tagName The name of the container element, if applicable
  20462. * @param attrsIndex Index of template attributes in the `consts` array.
  20463. * @param localRefs Index of the local references in the `consts` array.
  20464. * @param localRefExtractor A function which extracts local-refs values from the template.
  20465. * Defaults to the current element associated with the local-ref.
  20466. *
  20467. * @codeGenApi
  20468. */
  20469. function ɵɵtemplate(index, templateFn, decls, vars, tagName, attrsIndex, localRefsIndex, localRefExtractor) {
  20470. const lView = getLView();
  20471. const tView = getTView();
  20472. const attrs = getConstant(tView.consts, attrsIndex);
  20473. declareTemplate(lView, tView, index, templateFn, decls, vars, tagName, attrs, localRefsIndex, localRefExtractor);
  20474. return ɵɵtemplate;
  20475. }
  20476. let _locateOrCreateContainerAnchor = createContainerAnchorImpl;
  20477. /**
  20478. * Regular creation mode for LContainers and their anchor (comment) nodes.
  20479. */
  20480. function createContainerAnchorImpl(tView, lView, tNode, index) {
  20481. lastNodeWasCreated(true);
  20482. return lView[RENDERER].createComment(ngDevMode ? 'container' : '');
  20483. }
  20484. /**
  20485. * Enables hydration code path (to lookup existing elements in DOM)
  20486. * in addition to the regular creation mode for LContainers and their
  20487. * anchor (comment) nodes.
  20488. */
  20489. function locateOrCreateContainerAnchorImpl(tView, lView, tNode, index) {
  20490. const hydrationInfo = lView[HYDRATION];
  20491. const isNodeCreationMode = !hydrationInfo ||
  20492. isInSkipHydrationBlock$1() ||
  20493. isDetachedByI18n(tNode) ||
  20494. isDisconnectedNode$1(hydrationInfo, index);
  20495. lastNodeWasCreated(isNodeCreationMode);
  20496. // Regular creation mode.
  20497. if (isNodeCreationMode) {
  20498. return createContainerAnchorImpl(tView, lView);
  20499. }
  20500. const ssrId = hydrationInfo.data[TEMPLATES]?.[index] ?? null;
  20501. // Apply `ssrId` value to the underlying TView if it was not previously set.
  20502. //
  20503. // There might be situations when the same component is present in a template
  20504. // multiple times and some instances are opted-out of using hydration via
  20505. // `ngSkipHydration` attribute. In this scenario, at the time a TView is created,
  20506. // the `ssrId` might be `null` (if the first component is opted-out of hydration).
  20507. // The code below makes sure that the `ssrId` is applied to the TView if it's still
  20508. // `null` and verifies we never try to override it with a different value.
  20509. if (ssrId !== null && tNode.tView !== null) {
  20510. if (tNode.tView.ssrId === null) {
  20511. tNode.tView.ssrId = ssrId;
  20512. }
  20513. else {
  20514. ngDevMode &&
  20515. assertEqual(tNode.tView.ssrId, ssrId, 'Unexpected value of the `ssrId` for this TView');
  20516. }
  20517. }
  20518. // Hydration mode, looking up existing elements in DOM.
  20519. const currentRNode = locateNextRNode(hydrationInfo, tView, lView, tNode);
  20520. ngDevMode && validateNodeExists(currentRNode, lView, tNode);
  20521. setSegmentHead(hydrationInfo, index, currentRNode);
  20522. const viewContainerSize = calcSerializedContainerSize(hydrationInfo, index);
  20523. const comment = siblingAfter(viewContainerSize, currentRNode);
  20524. if (ngDevMode) {
  20525. validateMatchingNode(comment, Node.COMMENT_NODE, null, lView, tNode);
  20526. markRNodeAsClaimedByHydration(comment);
  20527. }
  20528. return comment;
  20529. }
  20530. function enableLocateOrCreateContainerAnchorImpl() {
  20531. _locateOrCreateContainerAnchor = locateOrCreateContainerAnchorImpl;
  20532. }
  20533. /**
  20534. * Helper function to schedule a callback to be invoked when a browser becomes idle.
  20535. *
  20536. * @param callback A function to be invoked when a browser becomes idle.
  20537. * @param injector injector for the app
  20538. */
  20539. function onIdle(callback, injector) {
  20540. const scheduler = injector.get(IdleScheduler);
  20541. const cleanupFn = () => scheduler.remove(callback);
  20542. scheduler.add(callback);
  20543. return cleanupFn;
  20544. }
  20545. /**
  20546. * Use shims for the `requestIdleCallback` and `cancelIdleCallback` functions for
  20547. * environments where those functions are not available (e.g. Node.js and Safari).
  20548. *
  20549. * Note: we wrap the `requestIdleCallback` call into a function, so that it can be
  20550. * overridden/mocked in test environment and picked up by the runtime code.
  20551. */
  20552. const _requestIdleCallback = () => typeof requestIdleCallback !== 'undefined' ? requestIdleCallback : setTimeout;
  20553. const _cancelIdleCallback = () => typeof requestIdleCallback !== 'undefined' ? cancelIdleCallback : clearTimeout;
  20554. /**
  20555. * Helper service to schedule `requestIdleCallback`s for batches of defer blocks,
  20556. * to avoid calling `requestIdleCallback` for each defer block (e.g. if
  20557. * defer blocks are defined inside a for loop).
  20558. */
  20559. class IdleScheduler {
  20560. // Indicates whether current callbacks are being invoked.
  20561. executingCallbacks = false;
  20562. // Currently scheduled idle callback id.
  20563. idleId = null;
  20564. // Set of callbacks to be invoked next.
  20565. current = new Set();
  20566. // Set of callbacks collected while invoking current set of callbacks.
  20567. // Those callbacks are scheduled for the next idle period.
  20568. deferred = new Set();
  20569. ngZone = inject(NgZone);
  20570. requestIdleCallbackFn = _requestIdleCallback().bind(globalThis);
  20571. cancelIdleCallbackFn = _cancelIdleCallback().bind(globalThis);
  20572. add(callback) {
  20573. const target = this.executingCallbacks ? this.deferred : this.current;
  20574. target.add(callback);
  20575. if (this.idleId === null) {
  20576. this.scheduleIdleCallback();
  20577. }
  20578. }
  20579. remove(callback) {
  20580. const { current, deferred } = this;
  20581. current.delete(callback);
  20582. deferred.delete(callback);
  20583. // If the last callback was removed and there is a pending
  20584. // idle callback - cancel it.
  20585. if (current.size === 0 && deferred.size === 0) {
  20586. this.cancelIdleCallback();
  20587. }
  20588. }
  20589. scheduleIdleCallback() {
  20590. const callback = () => {
  20591. this.cancelIdleCallback();
  20592. this.executingCallbacks = true;
  20593. for (const callback of this.current) {
  20594. callback();
  20595. }
  20596. this.current.clear();
  20597. this.executingCallbacks = false;
  20598. // If there are any callbacks added during an invocation
  20599. // of the current ones - make them "current" and schedule
  20600. // a new idle callback.
  20601. if (this.deferred.size > 0) {
  20602. for (const callback of this.deferred) {
  20603. this.current.add(callback);
  20604. }
  20605. this.deferred.clear();
  20606. this.scheduleIdleCallback();
  20607. }
  20608. };
  20609. // Ensure that the callback runs in the NgZone since
  20610. // the `requestIdleCallback` is not currently patched by Zone.js.
  20611. this.idleId = this.requestIdleCallbackFn(() => this.ngZone.run(callback));
  20612. }
  20613. cancelIdleCallback() {
  20614. if (this.idleId !== null) {
  20615. this.cancelIdleCallbackFn(this.idleId);
  20616. this.idleId = null;
  20617. }
  20618. }
  20619. ngOnDestroy() {
  20620. this.cancelIdleCallback();
  20621. this.current.clear();
  20622. this.deferred.clear();
  20623. }
  20624. /** @nocollapse */
  20625. static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
  20626. token: IdleScheduler,
  20627. providedIn: 'root',
  20628. factory: () => new IdleScheduler(),
  20629. });
  20630. }
  20631. /**
  20632. * Returns a function that captures a provided delay.
  20633. * Invoking the returned function schedules a trigger.
  20634. */
  20635. function onTimer(delay) {
  20636. return (callback, injector) => scheduleTimerTrigger(delay, callback, injector);
  20637. }
  20638. /**
  20639. * Schedules a callback to be invoked after a given timeout.
  20640. *
  20641. * @param delay A number of ms to wait until firing a callback.
  20642. * @param callback A function to be invoked after a timeout.
  20643. * @param injector injector for the app.
  20644. */
  20645. function scheduleTimerTrigger(delay, callback, injector) {
  20646. const scheduler = injector.get(TimerScheduler);
  20647. const ngZone = injector.get(NgZone);
  20648. const cleanupFn = () => scheduler.remove(callback);
  20649. scheduler.add(delay, callback, ngZone);
  20650. return cleanupFn;
  20651. }
  20652. /**
  20653. * Helper service to schedule `setTimeout`s for batches of defer blocks,
  20654. * to avoid calling `setTimeout` for each defer block (e.g. if defer blocks
  20655. * are created inside a for loop).
  20656. */
  20657. class TimerScheduler {
  20658. // Indicates whether current callbacks are being invoked.
  20659. executingCallbacks = false;
  20660. // Currently scheduled `setTimeout` id.
  20661. timeoutId = null;
  20662. // When currently scheduled timer would fire.
  20663. invokeTimerAt = null;
  20664. // List of callbacks to be invoked.
  20665. // For each callback we also store a timestamp on when the callback
  20666. // should be invoked. We store timestamps and callback functions
  20667. // in a flat array to avoid creating new objects for each entry.
  20668. // [timestamp1, callback1, timestamp2, callback2, ...]
  20669. current = [];
  20670. // List of callbacks collected while invoking current set of callbacks.
  20671. // Those callbacks are added to the "current" queue at the end of
  20672. // the current callback invocation. The shape of this list is the same
  20673. // as the shape of the `current` list.
  20674. deferred = [];
  20675. add(delay, callback, ngZone) {
  20676. const target = this.executingCallbacks ? this.deferred : this.current;
  20677. this.addToQueue(target, Date.now() + delay, callback);
  20678. this.scheduleTimer(ngZone);
  20679. }
  20680. remove(callback) {
  20681. const { current, deferred } = this;
  20682. const callbackIndex = this.removeFromQueue(current, callback);
  20683. if (callbackIndex === -1) {
  20684. // Try cleaning up deferred queue only in case
  20685. // we didn't find a callback in the "current" queue.
  20686. this.removeFromQueue(deferred, callback);
  20687. }
  20688. // If the last callback was removed and there is a pending timeout - cancel it.
  20689. if (current.length === 0 && deferred.length === 0) {
  20690. this.clearTimeout();
  20691. }
  20692. }
  20693. addToQueue(target, invokeAt, callback) {
  20694. let insertAtIndex = target.length;
  20695. for (let i = 0; i < target.length; i += 2) {
  20696. const invokeQueuedCallbackAt = target[i];
  20697. if (invokeQueuedCallbackAt > invokeAt) {
  20698. // We've reached a first timer that is scheduled
  20699. // for a later time than what we are trying to insert.
  20700. // This is the location at which we need to insert,
  20701. // no need to iterate further.
  20702. insertAtIndex = i;
  20703. break;
  20704. }
  20705. }
  20706. arrayInsert2(target, insertAtIndex, invokeAt, callback);
  20707. }
  20708. removeFromQueue(target, callback) {
  20709. let index = -1;
  20710. for (let i = 0; i < target.length; i += 2) {
  20711. const queuedCallback = target[i + 1];
  20712. if (queuedCallback === callback) {
  20713. index = i;
  20714. break;
  20715. }
  20716. }
  20717. if (index > -1) {
  20718. // Remove 2 elements: a timestamp slot and
  20719. // the following slot with a callback function.
  20720. arraySplice(target, index, 2);
  20721. }
  20722. return index;
  20723. }
  20724. scheduleTimer(ngZone) {
  20725. const callback = () => {
  20726. this.clearTimeout();
  20727. this.executingCallbacks = true;
  20728. // Clone the current state of the queue, since it might be altered
  20729. // as we invoke callbacks.
  20730. const current = [...this.current];
  20731. // Invoke callbacks that were scheduled to run before the current time.
  20732. const now = Date.now();
  20733. for (let i = 0; i < current.length; i += 2) {
  20734. const invokeAt = current[i];
  20735. const callback = current[i + 1];
  20736. if (invokeAt <= now) {
  20737. callback();
  20738. }
  20739. else {
  20740. // We've reached a timer that should not be invoked yet.
  20741. break;
  20742. }
  20743. }
  20744. // The state of the queue might've changed after callbacks invocation,
  20745. // run the cleanup logic based on the *current* state of the queue.
  20746. let lastCallbackIndex = -1;
  20747. for (let i = 0; i < this.current.length; i += 2) {
  20748. const invokeAt = this.current[i];
  20749. if (invokeAt <= now) {
  20750. // Add +1 to account for a callback function that
  20751. // goes after the timestamp in events array.
  20752. lastCallbackIndex = i + 1;
  20753. }
  20754. else {
  20755. // We've reached a timer that should not be invoked yet.
  20756. break;
  20757. }
  20758. }
  20759. if (lastCallbackIndex >= 0) {
  20760. arraySplice(this.current, 0, lastCallbackIndex + 1);
  20761. }
  20762. this.executingCallbacks = false;
  20763. // If there are any callbacks added during an invocation
  20764. // of the current ones - move them over to the "current"
  20765. // queue.
  20766. if (this.deferred.length > 0) {
  20767. for (let i = 0; i < this.deferred.length; i += 2) {
  20768. const invokeAt = this.deferred[i];
  20769. const callback = this.deferred[i + 1];
  20770. this.addToQueue(this.current, invokeAt, callback);
  20771. }
  20772. this.deferred.length = 0;
  20773. }
  20774. this.scheduleTimer(ngZone);
  20775. };
  20776. // Avoid running timer callbacks more than once per
  20777. // average frame duration. This is needed for better
  20778. // batching and to avoid kicking off excessive change
  20779. // detection cycles.
  20780. const FRAME_DURATION_MS = 16; // 1000ms / 60fps
  20781. if (this.current.length > 0) {
  20782. const now = Date.now();
  20783. // First element in the queue points at the timestamp
  20784. // of the first (earliest) event.
  20785. const invokeAt = this.current[0];
  20786. if (this.timeoutId === null ||
  20787. // Reschedule a timer in case a queue contains an item with
  20788. // an earlier timestamp and the delta is more than an average
  20789. // frame duration.
  20790. (this.invokeTimerAt && this.invokeTimerAt - invokeAt > FRAME_DURATION_MS)) {
  20791. // There was a timeout already, but an earlier event was added
  20792. // into the queue. In this case we drop an old timer and setup
  20793. // a new one with an updated (smaller) timeout.
  20794. this.clearTimeout();
  20795. const timeout = Math.max(invokeAt - now, FRAME_DURATION_MS);
  20796. this.invokeTimerAt = invokeAt;
  20797. this.timeoutId = ngZone.runOutsideAngular(() => {
  20798. return setTimeout(() => ngZone.run(callback), timeout);
  20799. });
  20800. }
  20801. }
  20802. }
  20803. clearTimeout() {
  20804. if (this.timeoutId !== null) {
  20805. clearTimeout(this.timeoutId);
  20806. this.timeoutId = null;
  20807. }
  20808. }
  20809. ngOnDestroy() {
  20810. this.clearTimeout();
  20811. this.current.length = 0;
  20812. this.deferred.length = 0;
  20813. }
  20814. /** @nocollapse */
  20815. static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
  20816. token: TimerScheduler,
  20817. providedIn: 'root',
  20818. factory: () => new TimerScheduler(),
  20819. });
  20820. }
  20821. /**
  20822. * A service used by the framework to create and cache injector instances.
  20823. *
  20824. * This service is used to create a single injector instance for each defer
  20825. * block definition, to avoid creating an injector for each defer block instance
  20826. * of a certain type.
  20827. */
  20828. class CachedInjectorService {
  20829. cachedInjectors = new Map();
  20830. getOrCreateInjector(key, parentInjector, providers, debugName) {
  20831. if (!this.cachedInjectors.has(key)) {
  20832. const injector = providers.length > 0
  20833. ? createEnvironmentInjector(providers, parentInjector, debugName)
  20834. : null;
  20835. this.cachedInjectors.set(key, injector);
  20836. }
  20837. return this.cachedInjectors.get(key);
  20838. }
  20839. ngOnDestroy() {
  20840. try {
  20841. for (const injector of this.cachedInjectors.values()) {
  20842. if (injector !== null) {
  20843. injector.destroy();
  20844. }
  20845. }
  20846. }
  20847. finally {
  20848. this.cachedInjectors.clear();
  20849. }
  20850. }
  20851. /** @nocollapse */
  20852. static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
  20853. token: CachedInjectorService,
  20854. providedIn: 'environment',
  20855. factory: () => new CachedInjectorService(),
  20856. });
  20857. }
  20858. /**
  20859. * **INTERNAL**, avoid referencing it in application code.
  20860. * *
  20861. * Injector token that allows to provide `DeferBlockDependencyInterceptor` class
  20862. * implementation.
  20863. *
  20864. * This token is only injected in devMode
  20865. */
  20866. const DEFER_BLOCK_DEPENDENCY_INTERCEPTOR =
  20867. /* @__PURE__ */ new InjectionToken('DEFER_BLOCK_DEPENDENCY_INTERCEPTOR');
  20868. /**
  20869. * **INTERNAL**, token used for configuring defer block behavior.
  20870. */
  20871. const DEFER_BLOCK_CONFIG = new InjectionToken(ngDevMode ? 'DEFER_BLOCK_CONFIG' : '');
  20872. /**
  20873. * Checks whether there is a cached injector associated with a given defer block
  20874. * declaration and returns if it exists. If there is no cached injector present -
  20875. * creates a new injector and stores in the cache.
  20876. */
  20877. function getOrCreateEnvironmentInjector(parentInjector, tDetails, providers) {
  20878. return parentInjector
  20879. .get(CachedInjectorService)
  20880. .getOrCreateInjector(tDetails, parentInjector, providers, ngDevMode ? 'DeferBlock Injector' : '');
  20881. }
  20882. /** Injector Helpers */
  20883. /**
  20884. * Creates a new injector, which contains providers collected from dependencies (NgModules) of
  20885. * defer-loaded components. This function detects different types of parent injectors and creates
  20886. * a new injector based on that.
  20887. */
  20888. function createDeferBlockInjector(parentInjector, tDetails, providers) {
  20889. // Check if the parent injector is an instance of a `ChainedInjector`.
  20890. //
  20891. // In this case, we retain the shape of the injector and use a newly created
  20892. // `EnvironmentInjector` as a parent in the `ChainedInjector`. That is needed to
  20893. // make sure that the primary injector gets consulted first (since it's typically
  20894. // a NodeInjector) and `EnvironmentInjector` tree is consulted after that.
  20895. if (parentInjector instanceof ChainedInjector) {
  20896. const origInjector = parentInjector.injector;
  20897. // Guaranteed to be an environment injector
  20898. const parentEnvInjector = parentInjector.parentInjector;
  20899. const envInjector = getOrCreateEnvironmentInjector(parentEnvInjector, tDetails, providers);
  20900. return new ChainedInjector(origInjector, envInjector);
  20901. }
  20902. const parentEnvInjector = parentInjector.get(EnvironmentInjector);
  20903. // If the `parentInjector` is *not* an `EnvironmentInjector` - we need to create
  20904. // a new `ChainedInjector` with the following setup:
  20905. //
  20906. // - the provided `parentInjector` becomes a primary injector
  20907. // - an existing (real) `EnvironmentInjector` becomes a parent injector for
  20908. // a newly-created one, which contains extra providers
  20909. //
  20910. // So the final order in which injectors would be consulted in this case would look like this:
  20911. //
  20912. // 1. Provided `parentInjector`
  20913. // 2. Newly-created `EnvironmentInjector` with extra providers
  20914. // 3. `EnvironmentInjector` from the `parentInjector`
  20915. if (parentEnvInjector !== parentInjector) {
  20916. const envInjector = getOrCreateEnvironmentInjector(parentEnvInjector, tDetails, providers);
  20917. return new ChainedInjector(parentInjector, envInjector);
  20918. }
  20919. // The `parentInjector` is an instance of an `EnvironmentInjector`.
  20920. // No need for special handling, we can use `parentInjector` as a
  20921. // parent injector directly.
  20922. return getOrCreateEnvironmentInjector(parentInjector, tDetails, providers);
  20923. }
  20924. /** Rendering Helpers */
  20925. /**
  20926. * Transitions a defer block to the new state. Updates the necessary
  20927. * data structures and renders corresponding block.
  20928. *
  20929. * @param newState New state that should be applied to the defer block.
  20930. * @param tNode TNode that represents a defer block.
  20931. * @param lContainer Represents an instance of a defer block.
  20932. * @param skipTimerScheduling Indicates that `@loading` and `@placeholder` block
  20933. * should be rendered immediately, even if they have `after` or `minimum` config
  20934. * options setup. This flag to needed for testing APIs to transition defer block
  20935. * between states via `DeferFixture.render` method.
  20936. */
  20937. function renderDeferBlockState(newState, tNode, lContainer, skipTimerScheduling = false) {
  20938. const hostLView = lContainer[PARENT];
  20939. const hostTView = hostLView[TVIEW];
  20940. // Check if this view is not destroyed. Since the loading process was async,
  20941. // the view might end up being destroyed by the time rendering happens.
  20942. if (isDestroyed(hostLView))
  20943. return;
  20944. // Make sure this TNode belongs to TView that represents host LView.
  20945. ngDevMode && assertTNodeForLView(tNode, hostLView);
  20946. const lDetails = getLDeferBlockDetails(hostLView, tNode);
  20947. ngDevMode && assertDefined(lDetails, 'Expected a defer block state defined');
  20948. const currentState = lDetails[DEFER_BLOCK_STATE];
  20949. const ssrState = lDetails[SSR_BLOCK_STATE];
  20950. if (ssrState !== null && newState < ssrState) {
  20951. return; // trying to render a previous state, exit
  20952. }
  20953. if (isValidStateChange(currentState, newState) &&
  20954. isValidStateChange(lDetails[NEXT_DEFER_BLOCK_STATE] ?? -1, newState)) {
  20955. const tDetails = getTDeferBlockDetails(hostTView, tNode);
  20956. // Skips scheduling on the server since it can delay the server response.
  20957. const needsScheduling = !skipTimerScheduling &&
  20958. (typeof ngServerMode === 'undefined' || !ngServerMode) &&
  20959. (getLoadingBlockAfter(tDetails) !== null ||
  20960. getMinimumDurationForState(tDetails, DeferBlockState.Loading) !== null ||
  20961. getMinimumDurationForState(tDetails, DeferBlockState.Placeholder));
  20962. if (ngDevMode && needsScheduling) {
  20963. assertDefined(applyDeferBlockStateWithSchedulingImpl, 'Expected scheduling function to be defined');
  20964. }
  20965. const applyStateFn = needsScheduling
  20966. ? applyDeferBlockStateWithSchedulingImpl
  20967. : applyDeferBlockState;
  20968. try {
  20969. applyStateFn(newState, lDetails, lContainer, tNode, hostLView);
  20970. }
  20971. catch (error) {
  20972. handleError$1(hostLView, error);
  20973. }
  20974. }
  20975. }
  20976. function findMatchingDehydratedViewForDeferBlock(lContainer, lDetails) {
  20977. const dehydratedViewIx = lContainer[DEHYDRATED_VIEWS]?.findIndex((view) => view.data[DEFER_BLOCK_STATE$1] === lDetails[DEFER_BLOCK_STATE]) ?? -1;
  20978. const dehydratedView = dehydratedViewIx > -1 ? lContainer[DEHYDRATED_VIEWS][dehydratedViewIx] : null;
  20979. return { dehydratedView, dehydratedViewIx };
  20980. }
  20981. /**
  20982. * Applies changes to the DOM to reflect a given state.
  20983. */
  20984. function applyDeferBlockState(newState, lDetails, lContainer, tNode, hostLView) {
  20985. profiler(20 /* ProfilerEvent.DeferBlockStateStart */);
  20986. const stateTmplIndex = getTemplateIndexForState(newState, hostLView, tNode);
  20987. if (stateTmplIndex !== null) {
  20988. lDetails[DEFER_BLOCK_STATE] = newState;
  20989. const hostTView = hostLView[TVIEW];
  20990. const adjustedIndex = stateTmplIndex + HEADER_OFFSET;
  20991. // The TNode that represents a template that will activated in the defer block
  20992. const activeBlockTNode = getTNode(hostTView, adjustedIndex);
  20993. // There is only 1 view that can be present in an LContainer that
  20994. // represents a defer block, so always refer to the first one.
  20995. const viewIndex = 0;
  20996. removeLViewFromLContainer(lContainer, viewIndex);
  20997. let injector;
  20998. if (newState === DeferBlockState.Complete) {
  20999. // When we render a defer block in completed state, there might be
  21000. // newly loaded standalone components used within the block, which may
  21001. // import NgModules with providers. In order to make those providers
  21002. // available for components declared in that NgModule, we create an instance
  21003. // of an environment injector to host those providers and pass this injector
  21004. // to the logic that creates a view.
  21005. const tDetails = getTDeferBlockDetails(hostTView, tNode);
  21006. const providers = tDetails.providers;
  21007. if (providers && providers.length > 0) {
  21008. injector = createDeferBlockInjector(hostLView[INJECTOR], tDetails, providers);
  21009. }
  21010. }
  21011. const { dehydratedView, dehydratedViewIx } = findMatchingDehydratedViewForDeferBlock(lContainer, lDetails);
  21012. const embeddedLView = createAndRenderEmbeddedLView(hostLView, activeBlockTNode, null, {
  21013. injector,
  21014. dehydratedView,
  21015. });
  21016. addLViewToLContainer(lContainer, embeddedLView, viewIndex, shouldAddViewToDom(activeBlockTNode, dehydratedView));
  21017. markViewDirty(embeddedLView, 2 /* NotificationSource.DeferBlockStateUpdate */);
  21018. if (dehydratedViewIx > -1) {
  21019. // Erase dehydrated view info in a given LContainer, so that the view is not
  21020. // removed later by post-hydration cleanup process (which iterates over all
  21021. // dehydrated views in component tree). This clears only the dehydrated view
  21022. // that was found for this render, which in most cases will be the only view.
  21023. // In the case that there was control flow that changed, there may be either
  21024. // more than one or the views would not match up due to the server rendered
  21025. // content being a different branch of the control flow.
  21026. lContainer[DEHYDRATED_VIEWS]?.splice(dehydratedViewIx, 1);
  21027. }
  21028. if ((newState === DeferBlockState.Complete || newState === DeferBlockState.Error) &&
  21029. Array.isArray(lDetails[ON_COMPLETE_FNS])) {
  21030. for (const callback of lDetails[ON_COMPLETE_FNS]) {
  21031. callback();
  21032. }
  21033. lDetails[ON_COMPLETE_FNS] = null;
  21034. }
  21035. }
  21036. profiler(21 /* ProfilerEvent.DeferBlockStateEnd */);
  21037. }
  21038. /**
  21039. * Extends the `applyDeferBlockState` with timer-based scheduling.
  21040. * This function becomes available on a page if there are defer blocks
  21041. * that use `after` or `minimum` parameters in the `@loading` or
  21042. * `@placeholder` blocks.
  21043. */
  21044. function applyDeferBlockStateWithScheduling(newState, lDetails, lContainer, tNode, hostLView) {
  21045. const now = Date.now();
  21046. const hostTView = hostLView[TVIEW];
  21047. const tDetails = getTDeferBlockDetails(hostTView, tNode);
  21048. if (lDetails[STATE_IS_FROZEN_UNTIL] === null || lDetails[STATE_IS_FROZEN_UNTIL] <= now) {
  21049. lDetails[STATE_IS_FROZEN_UNTIL] = null;
  21050. const loadingAfter = getLoadingBlockAfter(tDetails);
  21051. const inLoadingAfterPhase = lDetails[LOADING_AFTER_CLEANUP_FN] !== null;
  21052. if (newState === DeferBlockState.Loading && loadingAfter !== null && !inLoadingAfterPhase) {
  21053. // Trying to render loading, but it has an `after` config,
  21054. // so schedule an update action after a timeout.
  21055. lDetails[NEXT_DEFER_BLOCK_STATE] = newState;
  21056. const cleanupFn = scheduleDeferBlockUpdate(loadingAfter, lDetails, tNode, lContainer, hostLView);
  21057. lDetails[LOADING_AFTER_CLEANUP_FN] = cleanupFn;
  21058. }
  21059. else {
  21060. // If we transition to a complete or an error state and there is a pending
  21061. // operation to render loading after a timeout - invoke a cleanup operation,
  21062. // which stops the timer.
  21063. if (newState > DeferBlockState.Loading && inLoadingAfterPhase) {
  21064. lDetails[LOADING_AFTER_CLEANUP_FN]();
  21065. lDetails[LOADING_AFTER_CLEANUP_FN] = null;
  21066. lDetails[NEXT_DEFER_BLOCK_STATE] = null;
  21067. }
  21068. applyDeferBlockState(newState, lDetails, lContainer, tNode, hostLView);
  21069. const duration = getMinimumDurationForState(tDetails, newState);
  21070. if (duration !== null) {
  21071. lDetails[STATE_IS_FROZEN_UNTIL] = now + duration;
  21072. scheduleDeferBlockUpdate(duration, lDetails, tNode, lContainer, hostLView);
  21073. }
  21074. }
  21075. }
  21076. else {
  21077. // We are still rendering the previous state.
  21078. // Update the `NEXT_DEFER_BLOCK_STATE`, which would be
  21079. // picked up once it's time to transition to the next state.
  21080. lDetails[NEXT_DEFER_BLOCK_STATE] = newState;
  21081. }
  21082. }
  21083. /**
  21084. * Schedules an update operation after a specified timeout.
  21085. */
  21086. function scheduleDeferBlockUpdate(timeout, lDetails, tNode, lContainer, hostLView) {
  21087. const callback = () => {
  21088. const nextState = lDetails[NEXT_DEFER_BLOCK_STATE];
  21089. lDetails[STATE_IS_FROZEN_UNTIL] = null;
  21090. lDetails[NEXT_DEFER_BLOCK_STATE] = null;
  21091. if (nextState !== null) {
  21092. renderDeferBlockState(nextState, tNode, lContainer);
  21093. }
  21094. };
  21095. return scheduleTimerTrigger(timeout, callback, hostLView[INJECTOR]);
  21096. }
  21097. /**
  21098. * Checks whether we can transition to the next state.
  21099. *
  21100. * We transition to the next state if the previous state was represented
  21101. * with a number that is less than the next state. For example, if the current
  21102. * state is "loading" (represented as `1`), we should not show a placeholder
  21103. * (represented as `0`), but we can show a completed state (represented as `2`)
  21104. * or an error state (represented as `3`).
  21105. */
  21106. function isValidStateChange(currentState, newState) {
  21107. return currentState < newState;
  21108. }
  21109. /** Utility function to render placeholder content (if present) */
  21110. function renderPlaceholder(lView, tNode) {
  21111. const lContainer = lView[tNode.index];
  21112. ngDevMode && assertLContainer(lContainer);
  21113. renderDeferBlockState(DeferBlockState.Placeholder, tNode, lContainer);
  21114. }
  21115. /**
  21116. * Subscribes to the "loading" Promise and renders corresponding defer sub-block,
  21117. * based on the loading results.
  21118. *
  21119. * @param lContainer Represents an instance of a defer block.
  21120. * @param tNode Represents defer block info shared across all instances.
  21121. */
  21122. function renderDeferStateAfterResourceLoading(tDetails, tNode, lContainer) {
  21123. ngDevMode &&
  21124. assertDefined(tDetails.loadingPromise, 'Expected loading Promise to exist on this defer block');
  21125. tDetails.loadingPromise.then(() => {
  21126. if (tDetails.loadingState === DeferDependenciesLoadingState.COMPLETE) {
  21127. ngDevMode && assertDeferredDependenciesLoaded(tDetails);
  21128. // Everything is loaded, show the primary block content
  21129. renderDeferBlockState(DeferBlockState.Complete, tNode, lContainer);
  21130. }
  21131. else if (tDetails.loadingState === DeferDependenciesLoadingState.FAILED) {
  21132. renderDeferBlockState(DeferBlockState.Error, tNode, lContainer);
  21133. }
  21134. });
  21135. }
  21136. /**
  21137. * Reference to the timer-based scheduler implementation of defer block state
  21138. * rendering method. It's used to make timer-based scheduling tree-shakable.
  21139. * If `minimum` or `after` parameters are used, compiler generates an extra
  21140. * argument for the `ɵɵdefer` instruction, which references a timer-based
  21141. * implementation.
  21142. */
  21143. let applyDeferBlockStateWithSchedulingImpl = null;
  21144. /**
  21145. * Enables timer-related scheduling if `after` or `minimum` parameters are setup
  21146. * on the `@loading` or `@placeholder` blocks.
  21147. */
  21148. function ɵɵdeferEnableTimerScheduling(tView, tDetails, placeholderConfigIndex, loadingConfigIndex) {
  21149. const tViewConsts = tView.consts;
  21150. if (placeholderConfigIndex != null) {
  21151. tDetails.placeholderBlockConfig = getConstant(tViewConsts, placeholderConfigIndex);
  21152. }
  21153. if (loadingConfigIndex != null) {
  21154. tDetails.loadingBlockConfig = getConstant(tViewConsts, loadingConfigIndex);
  21155. }
  21156. // Enable implementation that supports timer-based scheduling.
  21157. if (applyDeferBlockStateWithSchedulingImpl === null) {
  21158. applyDeferBlockStateWithSchedulingImpl = applyDeferBlockStateWithScheduling;
  21159. }
  21160. }
  21161. /**
  21162. * The name of a field that Angular monkey-patches onto a component
  21163. * class to store a function that loads defer-loadable dependencies
  21164. * and applies metadata to a class.
  21165. */
  21166. const ASYNC_COMPONENT_METADATA_FN = '__ngAsyncComponentMetadataFn__';
  21167. /**
  21168. * If a given component has unresolved async metadata - returns a reference
  21169. * to a function that applies component metadata after resolving defer-loadable
  21170. * dependencies. Otherwise - this function returns `null`.
  21171. */
  21172. function getAsyncClassMetadataFn(type) {
  21173. const componentClass = type; // cast to `any`, so that we can read a monkey-patched field
  21174. return componentClass[ASYNC_COMPONENT_METADATA_FN] ?? null;
  21175. }
  21176. /**
  21177. * Handles the process of applying metadata info to a component class in case
  21178. * component template has defer blocks (thus some dependencies became deferrable).
  21179. *
  21180. * @param type Component class where metadata should be added
  21181. * @param dependencyLoaderFn Function that loads dependencies
  21182. * @param metadataSetterFn Function that forms a scope in which the `setClassMetadata` is invoked
  21183. */
  21184. function setClassMetadataAsync(type, dependencyLoaderFn, metadataSetterFn) {
  21185. const componentClass = type; // cast to `any`, so that we can monkey-patch it
  21186. componentClass[ASYNC_COMPONENT_METADATA_FN] = () => Promise.all(dependencyLoaderFn()).then((dependencies) => {
  21187. metadataSetterFn(...dependencies);
  21188. // Metadata is now set, reset field value to indicate that this component
  21189. // can by used/compiled synchronously.
  21190. componentClass[ASYNC_COMPONENT_METADATA_FN] = null;
  21191. return dependencies;
  21192. });
  21193. return componentClass[ASYNC_COMPONENT_METADATA_FN];
  21194. }
  21195. /**
  21196. * Adds decorator, constructor, and property metadata to a given type via static metadata fields
  21197. * on the type.
  21198. *
  21199. * These metadata fields can later be read with Angular's `ReflectionCapabilities` API.
  21200. *
  21201. * Calls to `setClassMetadata` can be guarded by ngDevMode, resulting in the metadata assignments
  21202. * being tree-shaken away during production builds.
  21203. */
  21204. function setClassMetadata(type, decorators, ctorParameters, propDecorators) {
  21205. return noSideEffects(() => {
  21206. const clazz = type;
  21207. if (decorators !== null) {
  21208. if (clazz.hasOwnProperty('decorators') && clazz.decorators !== undefined) {
  21209. clazz.decorators.push(...decorators);
  21210. }
  21211. else {
  21212. clazz.decorators = decorators;
  21213. }
  21214. }
  21215. if (ctorParameters !== null) {
  21216. // Rather than merging, clobber the existing parameters. If other projects exist which
  21217. // use tsickle-style annotations and reflect over them in the same way, this could
  21218. // cause issues, but that is vanishingly unlikely.
  21219. clazz.ctorParameters = ctorParameters;
  21220. }
  21221. if (propDecorators !== null) {
  21222. // The property decorator objects are merged as it is possible different fields have
  21223. // different decorator types. Decorators on individual fields are not merged, as it's
  21224. // also incredibly unlikely that a field will be decorated both with an Angular
  21225. // decorator and a non-Angular decorator that's also been downleveled.
  21226. if (clazz.hasOwnProperty('propDecorators') && clazz.propDecorators !== undefined) {
  21227. clazz.propDecorators = { ...clazz.propDecorators, ...propDecorators };
  21228. }
  21229. else {
  21230. clazz.propDecorators = propDecorators;
  21231. }
  21232. }
  21233. });
  21234. }
  21235. class Console {
  21236. log(message) {
  21237. // tslint:disable-next-line:no-console
  21238. console.log(message);
  21239. }
  21240. // Note: for reporting errors use `DOM.logError()` as it is platform specific
  21241. warn(message) {
  21242. console.warn(message);
  21243. }
  21244. static ɵfac = function Console_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || Console)(); };
  21245. static ɵprov = /*@__PURE__*/ ɵɵdefineInjectable({ token: Console, factory: Console.ɵfac, providedIn: 'platform' });
  21246. }
  21247. (() => { (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(Console, [{
  21248. type: Injectable,
  21249. args: [{ providedIn: 'platform' }]
  21250. }], null, null); })();
  21251. /**
  21252. * These are the data structures that our framework injector profiler will fill with data in order
  21253. * to support DI debugging APIs.
  21254. *
  21255. * resolverToTokenToDependencies: Maps an injector to a Map of tokens to an Array of
  21256. * dependencies. Injector -> Token -> Dependencies This is used to support the
  21257. * getDependenciesFromInjectable API, which takes in an injector and a token and returns it's
  21258. * dependencies.
  21259. *
  21260. * resolverToProviders: Maps a DI resolver (an Injector or a TNode) to the providers configured
  21261. * within it This is used to support the getInjectorProviders API, which takes in an injector and
  21262. * returns the providers that it was configured with. Note that for the element injector case we
  21263. * use the TNode instead of the LView as the DI resolver. This is because the registration of
  21264. * providers happens only once per type of TNode. If an injector is created with an identical TNode,
  21265. * the providers for that injector will not be reconfigured.
  21266. *
  21267. * standaloneInjectorToComponent: Maps the injector of a standalone component to the standalone
  21268. * component that it is associated with. Used in the getInjectorProviders API, specificially in the
  21269. * discovery of import paths for each provider. This is necessary because the imports array of a
  21270. * standalone component is processed and configured in its standalone injector, but exists within
  21271. * the component's definition. Because getInjectorProviders takes in an injector, if that injector
  21272. * is the injector of a standalone component, we need to be able to discover the place where the
  21273. * imports array is located (the component) in order to flatten the imports array within it to
  21274. * discover all of it's providers.
  21275. *
  21276. *
  21277. * All of these data structures are instantiated with WeakMaps. This will ensure that the presence
  21278. * of any object in the keys of these maps does not prevent the garbage collector from collecting
  21279. * those objects. Because of this property of WeakMaps, these data structures will never be the
  21280. * source of a memory leak.
  21281. *
  21282. * An example of this advantage: When components are destroyed, we don't need to do
  21283. * any additional work to remove that component from our mappings.
  21284. *
  21285. */
  21286. class DIDebugData {
  21287. resolverToTokenToDependencies = new WeakMap();
  21288. resolverToProviders = new WeakMap();
  21289. resolverToEffects = new WeakMap();
  21290. standaloneInjectorToComponent = new WeakMap();
  21291. reset() {
  21292. this.resolverToTokenToDependencies = new WeakMap();
  21293. this.resolverToProviders = new WeakMap();
  21294. this.standaloneInjectorToComponent = new WeakMap();
  21295. }
  21296. }
  21297. let frameworkDIDebugData = new DIDebugData();
  21298. function getFrameworkDIDebugData() {
  21299. return frameworkDIDebugData;
  21300. }
  21301. /**
  21302. * Initalize default handling of injector events. This handling parses events
  21303. * as they are emitted and constructs the data structures necessary to support
  21304. * some of debug APIs.
  21305. *
  21306. * See handleInjectEvent, handleCreateEvent and handleProviderConfiguredEvent
  21307. * for descriptions of each handler
  21308. *
  21309. * Supported APIs:
  21310. * - getDependenciesFromInjectable
  21311. * - getInjectorProviders
  21312. */
  21313. function setupFrameworkInjectorProfiler() {
  21314. frameworkDIDebugData.reset();
  21315. setInjectorProfiler((injectorProfilerEvent) => handleInjectorProfilerEvent(injectorProfilerEvent));
  21316. }
  21317. function handleInjectorProfilerEvent(injectorProfilerEvent) {
  21318. const { context, type } = injectorProfilerEvent;
  21319. if (type === 0 /* InjectorProfilerEventType.Inject */) {
  21320. handleInjectEvent(context, injectorProfilerEvent.service);
  21321. }
  21322. else if (type === 1 /* InjectorProfilerEventType.InstanceCreatedByInjector */) {
  21323. handleInstanceCreatedByInjectorEvent(context, injectorProfilerEvent.instance);
  21324. }
  21325. else if (type === 2 /* InjectorProfilerEventType.ProviderConfigured */) {
  21326. handleProviderConfiguredEvent(context, injectorProfilerEvent.providerRecord);
  21327. }
  21328. else if (type === 3 /* InjectorProfilerEventType.EffectCreated */) {
  21329. handleEffectCreatedEvent(context, injectorProfilerEvent.effect);
  21330. }
  21331. }
  21332. function handleEffectCreatedEvent(context, effect) {
  21333. const diResolver = getDIResolver(context.injector);
  21334. if (diResolver === null) {
  21335. throwError('An EffectCreated event must be run within an injection context.');
  21336. }
  21337. const { resolverToEffects } = frameworkDIDebugData;
  21338. if (!resolverToEffects.has(diResolver)) {
  21339. resolverToEffects.set(diResolver, []);
  21340. }
  21341. resolverToEffects.get(diResolver).push(effect);
  21342. }
  21343. /**
  21344. *
  21345. * Stores the injected service in frameworkDIDebugData.resolverToTokenToDependencies
  21346. * based on it's injector and token.
  21347. *
  21348. * @param context InjectorProfilerContext the injection context that this event occurred in.
  21349. * @param data InjectedService the service associated with this inject event.
  21350. *
  21351. */
  21352. function handleInjectEvent(context, data) {
  21353. const diResolver = getDIResolver(context.injector);
  21354. if (diResolver === null) {
  21355. throwError('An Inject event must be run within an injection context.');
  21356. }
  21357. const diResolverToInstantiatedToken = frameworkDIDebugData.resolverToTokenToDependencies;
  21358. if (!diResolverToInstantiatedToken.has(diResolver)) {
  21359. diResolverToInstantiatedToken.set(diResolver, new WeakMap());
  21360. }
  21361. // if token is a primitive type, ignore this event. We do this because we cannot keep track of
  21362. // non-primitive tokens in WeakMaps since they are not garbage collectable.
  21363. if (!canBeHeldWeakly(context.token)) {
  21364. return;
  21365. }
  21366. const instantiatedTokenToDependencies = diResolverToInstantiatedToken.get(diResolver);
  21367. if (!instantiatedTokenToDependencies.has(context.token)) {
  21368. instantiatedTokenToDependencies.set(context.token, []);
  21369. }
  21370. const { token, value, flags } = data;
  21371. assertDefined(context.token, 'Injector profiler context token is undefined.');
  21372. const dependencies = instantiatedTokenToDependencies.get(context.token);
  21373. assertDefined(dependencies, 'Could not resolve dependencies for token.');
  21374. if (context.injector instanceof NodeInjector) {
  21375. dependencies.push({ token, value, flags, injectedIn: getNodeInjectorContext(context.injector) });
  21376. }
  21377. else {
  21378. dependencies.push({ token, value, flags });
  21379. }
  21380. }
  21381. /**
  21382. *
  21383. * Returns the LView and TNode associated with a NodeInjector. Returns undefined if the injector
  21384. * is not a NodeInjector.
  21385. *
  21386. * @param injector
  21387. * @returns {lView: LView, tNode: TNode}|undefined
  21388. */
  21389. function getNodeInjectorContext(injector) {
  21390. if (!(injector instanceof NodeInjector)) {
  21391. throwError('getNodeInjectorContext must be called with a NodeInjector');
  21392. }
  21393. const lView = getNodeInjectorLView(injector);
  21394. const tNode = getNodeInjectorTNode(injector);
  21395. if (tNode === null) {
  21396. return;
  21397. }
  21398. assertTNodeForLView(tNode, lView);
  21399. return { lView, tNode };
  21400. }
  21401. /**
  21402. *
  21403. * If the created instance is an instance of a standalone component, maps the injector to that
  21404. * standalone component in frameworkDIDebugData.standaloneInjectorToComponent
  21405. *
  21406. * @param context InjectorProfilerContext the injection context that this event occurred in.
  21407. * @param data InjectorCreatedInstance an object containing the instance that was just created
  21408. *
  21409. */
  21410. function handleInstanceCreatedByInjectorEvent(context, data) {
  21411. const { value } = data;
  21412. if (getDIResolver(context.injector) === null) {
  21413. throwError('An InjectorCreatedInstance event must be run within an injection context.');
  21414. }
  21415. // if our value is an instance of a standalone component, map the injector of that standalone
  21416. // component to the component class. Otherwise, this event is a noop.
  21417. let standaloneComponent = undefined;
  21418. if (typeof value === 'object') {
  21419. standaloneComponent = value?.constructor;
  21420. }
  21421. // We want to also cover if `standaloneComponent === null` in addition to `undefined`
  21422. if (standaloneComponent == undefined || !isStandaloneComponent(standaloneComponent)) {
  21423. return;
  21424. }
  21425. const environmentInjector = context.injector.get(EnvironmentInjector, null, { optional: true });
  21426. // Standalone components should have an environment injector. If one cannot be
  21427. // found we may be in a test case for low level functionality that did not explicitly
  21428. // setup this injector. In those cases, we simply ignore this event.
  21429. if (environmentInjector === null) {
  21430. return;
  21431. }
  21432. const { standaloneInjectorToComponent } = frameworkDIDebugData;
  21433. // If our injector has already been mapped, as is the case
  21434. // when a standalone component imports another standalone component,
  21435. // we consider the original component (the component doing the importing)
  21436. // as the component connected to our injector.
  21437. if (standaloneInjectorToComponent.has(environmentInjector)) {
  21438. return;
  21439. }
  21440. // If our injector hasn't been mapped, then we map it to the standalone component
  21441. standaloneInjectorToComponent.set(environmentInjector, standaloneComponent);
  21442. }
  21443. function isStandaloneComponent(value) {
  21444. const def = getComponentDef(value);
  21445. return !!def?.standalone;
  21446. }
  21447. /**
  21448. *
  21449. * Stores the emitted ProviderRecords from the InjectorProfilerEventType.ProviderConfigured
  21450. * event in frameworkDIDebugData.resolverToProviders
  21451. *
  21452. * @param context InjectorProfilerContext the injection context that this event occurred in.
  21453. * @param data ProviderRecord an object containing the instance that was just created
  21454. *
  21455. */
  21456. function handleProviderConfiguredEvent(context, data) {
  21457. const { resolverToProviders } = frameworkDIDebugData;
  21458. let diResolver;
  21459. if (context?.injector instanceof NodeInjector) {
  21460. diResolver = getNodeInjectorTNode(context.injector);
  21461. }
  21462. else {
  21463. diResolver = context.injector;
  21464. }
  21465. if (diResolver === null) {
  21466. throwError('A ProviderConfigured event must be run within an injection context.');
  21467. }
  21468. if (!resolverToProviders.has(diResolver)) {
  21469. resolverToProviders.set(diResolver, []);
  21470. }
  21471. resolverToProviders.get(diResolver).push(data);
  21472. }
  21473. function getDIResolver(injector) {
  21474. let diResolver = null;
  21475. if (injector === undefined) {
  21476. return diResolver;
  21477. }
  21478. // We use the LView as the diResolver for NodeInjectors because they
  21479. // do not persist anywhere in the framework. They are simply wrappers around an LView and a TNode
  21480. // that do persist. Because of this, we rely on the LView of the NodeInjector in order to use
  21481. // as a concrete key to represent this injector. If we get the same LView back later, we know
  21482. // we're looking at the same injector.
  21483. if (injector instanceof NodeInjector) {
  21484. diResolver = getNodeInjectorLView(injector);
  21485. }
  21486. // Other injectors can be used a keys for a map because their instances
  21487. // persist
  21488. else {
  21489. diResolver = injector;
  21490. }
  21491. return diResolver;
  21492. }
  21493. // inspired by
  21494. // https://tc39.es/ecma262/multipage/executable-code-and-execution-contexts.html#sec-canbeheldweakly
  21495. function canBeHeldWeakly(value) {
  21496. // we check for value !== null here because typeof null === 'object
  21497. return (value !== null &&
  21498. (typeof value === 'object' || typeof value === 'function' || typeof value === 'symbol'));
  21499. }
  21500. /**
  21501. * Marks a component for check (in case of OnPush components) and synchronously
  21502. * performs change detection on the application this component belongs to.
  21503. *
  21504. * @param component Component to {@link /api/core/ChangeDetectorRef#markForCheck mark for check}
  21505. *
  21506. * @publicApi
  21507. */
  21508. function applyChanges(component) {
  21509. ngDevMode && assertDefined(component, 'component');
  21510. markViewDirty(getComponentViewByInstance(component), 3 /* NotificationSource.DebugApplyChanges */);
  21511. getRootComponents(component).forEach((rootComponent) => detectChanges(rootComponent));
  21512. }
  21513. /**
  21514. * Synchronously perform change detection on a component (and possibly its sub-components).
  21515. *
  21516. * This function triggers change detection in a synchronous way on a component.
  21517. *
  21518. * @param component The component which the change detection should be performed on.
  21519. */
  21520. function detectChanges(component) {
  21521. const view = getComponentViewByInstance(component);
  21522. view[FLAGS] |= 1024 /* LViewFlags.RefreshView */;
  21523. detectChangesInternal(view);
  21524. }
  21525. /**
  21526. * Retrieves all defer blocks in a given LView.
  21527. *
  21528. * @param lView lView with defer blocks
  21529. * @param deferBlocks defer block aggregator array
  21530. */
  21531. function getDeferBlocks$1(lView, deferBlocks) {
  21532. const tView = lView[TVIEW];
  21533. for (let i = HEADER_OFFSET; i < tView.bindingStartIndex; i++) {
  21534. if (isLContainer(lView[i])) {
  21535. const lContainer = lView[i];
  21536. // An LContainer may represent an instance of a defer block, in which case
  21537. // we store it as a result. Otherwise, keep iterating over LContainer views and
  21538. // look for defer blocks.
  21539. const isLast = i === tView.bindingStartIndex - 1;
  21540. if (!isLast) {
  21541. const tNode = tView.data[i];
  21542. const tDetails = getTDeferBlockDetails(tView, tNode);
  21543. if (isTDeferBlockDetails(tDetails)) {
  21544. deferBlocks.push({ lContainer, lView, tNode, tDetails });
  21545. // This LContainer represents a defer block, so we exit
  21546. // this iteration and don't inspect views in this LContainer.
  21547. continue;
  21548. }
  21549. }
  21550. for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
  21551. getDeferBlocks$1(lContainer[i], deferBlocks);
  21552. }
  21553. }
  21554. else if (isLView(lView[i])) {
  21555. // This is a component, enter the `getDeferBlocks` recursively.
  21556. getDeferBlocks$1(lView[i], deferBlocks);
  21557. }
  21558. }
  21559. }
  21560. /*!
  21561. * @license
  21562. * Copyright Google LLC All Rights Reserved.
  21563. *
  21564. * Use of this source code is governed by an MIT-style license that can be
  21565. * found in the LICENSE file at https://angular.dev/license
  21566. */
  21567. /**
  21568. * Gets all of the `@defer` blocks that are present inside the specified DOM node.
  21569. * @param node Node in which to look for `@defer` blocks.
  21570. *
  21571. * @publicApi
  21572. */
  21573. function getDeferBlocks(node) {
  21574. const results = [];
  21575. const lView = getLContext(node)?.lView;
  21576. if (lView) {
  21577. findDeferBlocks(node, lView, results);
  21578. }
  21579. return results;
  21580. }
  21581. /**
  21582. * Finds all the `@defer` blocks inside a specific node and view.
  21583. * @param node Node in which to search for blocks.
  21584. * @param lView View within the node in which to search for blocks.
  21585. * @param results Array to which to add blocks once they're found.
  21586. */
  21587. function findDeferBlocks(node, lView, results) {
  21588. const registry = lView[INJECTOR].get(DEHYDRATED_BLOCK_REGISTRY, null, { optional: true });
  21589. const blocks = [];
  21590. getDeferBlocks$1(lView, blocks);
  21591. for (const details of blocks) {
  21592. const native = getNativeByTNode(details.tNode, details.lView);
  21593. const lDetails = getLDeferBlockDetails(details.lView, details.tNode);
  21594. // The LView from `getLContext` might be the view the element is placed in.
  21595. // Filter out defer blocks that aren't inside the specified root node.
  21596. if (!node.contains(native)) {
  21597. continue;
  21598. }
  21599. const tDetails = details.tDetails;
  21600. const renderedLView = getRendererLView(details);
  21601. const rootNodes = [];
  21602. if (renderedLView !== null) {
  21603. collectNativeNodes(renderedLView[TVIEW], renderedLView, renderedLView[TVIEW].firstChild, rootNodes);
  21604. }
  21605. const data = {
  21606. state: stringifyState(lDetails[DEFER_BLOCK_STATE]),
  21607. incrementalHydrationState: inferHydrationState(tDetails, lDetails, registry),
  21608. hasErrorBlock: tDetails.errorTmplIndex !== null,
  21609. loadingBlock: {
  21610. exists: tDetails.loadingTmplIndex !== null,
  21611. minimumTime: tDetails.loadingBlockConfig?.[MINIMUM_SLOT] ?? null,
  21612. afterTime: tDetails.loadingBlockConfig?.[LOADING_AFTER_SLOT] ?? null,
  21613. },
  21614. placeholderBlock: {
  21615. exists: tDetails.placeholderTmplIndex !== null,
  21616. minimumTime: tDetails.placeholderBlockConfig?.[MINIMUM_SLOT] ?? null,
  21617. },
  21618. triggers: tDetails.debug?.triggers ? Array.from(tDetails.debug.triggers).sort() : [],
  21619. rootNodes,
  21620. };
  21621. results.push(data);
  21622. // `getDeferBlocks` does not resolve nested defer blocks so we have to recurse manually.
  21623. if (renderedLView !== null) {
  21624. findDeferBlocks(node, renderedLView, results);
  21625. }
  21626. }
  21627. }
  21628. /**
  21629. * Turns the `DeferBlockState` into a string which is more readable than the enum form.
  21630. *
  21631. * @param lDetails Information about the
  21632. * @returns
  21633. */
  21634. function stringifyState(state) {
  21635. switch (state) {
  21636. case DeferBlockState.Complete:
  21637. return 'complete';
  21638. case DeferBlockState.Loading:
  21639. return 'loading';
  21640. case DeferBlockState.Placeholder:
  21641. return 'placeholder';
  21642. case DeferBlockState.Error:
  21643. return 'error';
  21644. case DeferBlockInternalState.Initial:
  21645. return 'initial';
  21646. default:
  21647. throw new Error(`Unrecognized state ${state}`);
  21648. }
  21649. }
  21650. /**
  21651. * Infers the hydration state of a specific defer block.
  21652. * @param tDetails Static defer block information.
  21653. * @param lDetails Instance defer block information.
  21654. * @param registry Registry coordinating the hydration of defer blocks.
  21655. */
  21656. function inferHydrationState(tDetails, lDetails, registry) {
  21657. if (registry === null ||
  21658. lDetails[SSR_UNIQUE_ID] === null ||
  21659. tDetails.hydrateTriggers === null ||
  21660. tDetails.hydrateTriggers.has(7 /* DeferBlockTrigger.Never */)) {
  21661. return 'not-configured';
  21662. }
  21663. return registry.has(lDetails[SSR_UNIQUE_ID]) ? 'dehydrated' : 'hydrated';
  21664. }
  21665. /**
  21666. * Gets the current LView that is rendered out in a defer block.
  21667. * @param details Instance information about the block.
  21668. */
  21669. function getRendererLView(details) {
  21670. // Defer block containers can only ever contain one view.
  21671. // If they're empty, it means that nothing is rendered.
  21672. if (details.lContainer.length <= CONTAINER_HEADER_OFFSET) {
  21673. return null;
  21674. }
  21675. const lView = details.lContainer[CONTAINER_HEADER_OFFSET];
  21676. ngDevMode && assertLView(lView);
  21677. return lView;
  21678. }
  21679. /**
  21680. * Discovers the dependencies of an injectable instance. Provides DI information about each
  21681. * dependency that the injectable was instantiated with, including where they were provided from.
  21682. *
  21683. * @param injector An injector instance
  21684. * @param token a DI token that was constructed by the given injector instance
  21685. * @returns an object that contains the created instance of token as well as all of the dependencies
  21686. * that it was instantiated with OR undefined if the token was not created within the given
  21687. * injector.
  21688. */
  21689. function getDependenciesFromInjectable(injector, token) {
  21690. // First we check to see if the token given maps to an actual instance in the injector given.
  21691. // We use `self: true` because we only want to look at the injector we were given.
  21692. // We use `optional: true` because it's possible that the token we were given was never
  21693. // constructed by the injector we were given.
  21694. const instance = injector.get(token, null, { self: true, optional: true });
  21695. if (instance === null) {
  21696. throw new Error(`Unable to determine instance of ${token} in given injector`);
  21697. }
  21698. const unformattedDependencies = getDependenciesForTokenInInjector(token, injector);
  21699. const resolutionPath = getInjectorResolutionPath(injector);
  21700. const dependencies = unformattedDependencies.map((dep) => {
  21701. // injectedIn contains private fields, so we omit it from the response
  21702. const formattedDependency = {
  21703. value: dep.value,
  21704. };
  21705. // convert injection flags to booleans
  21706. const flags = dep.flags;
  21707. formattedDependency.flags = {
  21708. optional: (8 /* InternalInjectFlags.Optional */ & flags) === 8 /* InternalInjectFlags.Optional */,
  21709. host: (1 /* InternalInjectFlags.Host */ & flags) === 1 /* InternalInjectFlags.Host */,
  21710. self: (2 /* InternalInjectFlags.Self */ & flags) === 2 /* InternalInjectFlags.Self */,
  21711. skipSelf: (4 /* InternalInjectFlags.SkipSelf */ & flags) === 4 /* InternalInjectFlags.SkipSelf */,
  21712. };
  21713. // find the injector that provided the dependency
  21714. for (let i = 0; i < resolutionPath.length; i++) {
  21715. const injectorToCheck = resolutionPath[i];
  21716. // if skipSelf is true we skip the first injector
  21717. if (i === 0 && formattedDependency.flags.skipSelf) {
  21718. continue;
  21719. }
  21720. // host only applies to NodeInjectors
  21721. if (formattedDependency.flags.host && injectorToCheck instanceof EnvironmentInjector) {
  21722. break;
  21723. }
  21724. const instance = injectorToCheck.get(dep.token, null, {
  21725. self: true,
  21726. optional: true,
  21727. });
  21728. if (instance !== null) {
  21729. // if host flag is true we double check that we can get the service from the first element
  21730. // in the resolution path by using the host flag. This is done to make sure that we've found
  21731. // the correct providing injector, and not a node injector that is connected to our path via
  21732. // a router outlet.
  21733. if (formattedDependency.flags.host) {
  21734. const firstInjector = resolutionPath[0];
  21735. const lookupFromFirstInjector = firstInjector.get(dep.token, null, {
  21736. ...formattedDependency.flags,
  21737. optional: true,
  21738. });
  21739. if (lookupFromFirstInjector !== null) {
  21740. formattedDependency.providedIn = injectorToCheck;
  21741. }
  21742. break;
  21743. }
  21744. formattedDependency.providedIn = injectorToCheck;
  21745. break;
  21746. }
  21747. // if self is true we stop after the first injector
  21748. if (i === 0 && formattedDependency.flags.self) {
  21749. break;
  21750. }
  21751. }
  21752. if (dep.token)
  21753. formattedDependency.token = dep.token;
  21754. return formattedDependency;
  21755. });
  21756. return { instance, dependencies };
  21757. }
  21758. function getDependenciesForTokenInInjector(token, injector) {
  21759. const { resolverToTokenToDependencies } = getFrameworkDIDebugData();
  21760. if (!(injector instanceof NodeInjector)) {
  21761. return resolverToTokenToDependencies.get(injector)?.get?.(token) ?? [];
  21762. }
  21763. const lView = getNodeInjectorLView(injector);
  21764. const tokenDependencyMap = resolverToTokenToDependencies.get(lView);
  21765. const dependencies = tokenDependencyMap?.get(token) ?? [];
  21766. // In the NodeInjector case, all injections for every node are stored in the same lView.
  21767. // We use the injectedIn field of the dependency to filter out the dependencies that
  21768. // do not come from the same node as the instance we're looking at.
  21769. return dependencies.filter((dependency) => {
  21770. const dependencyNode = dependency.injectedIn?.tNode;
  21771. if (dependencyNode === undefined) {
  21772. return false;
  21773. }
  21774. const instanceNode = getNodeInjectorTNode(injector);
  21775. assertTNode(dependencyNode);
  21776. assertTNode(instanceNode);
  21777. return dependencyNode === instanceNode;
  21778. });
  21779. }
  21780. /**
  21781. * Gets the class associated with an injector that contains a provider `imports` array in it's
  21782. * definition
  21783. *
  21784. * For Module Injectors this returns the NgModule constructor.
  21785. *
  21786. * For Standalone injectors this returns the standalone component constructor.
  21787. *
  21788. * @param injector Injector an injector instance
  21789. * @returns the constructor where the `imports` array that configures this injector is located
  21790. */
  21791. function getProviderImportsContainer(injector) {
  21792. const { standaloneInjectorToComponent } = getFrameworkDIDebugData();
  21793. // standalone components configure providers through a component def, so we have to
  21794. // use the standalone component associated with this injector if Injector represents
  21795. // a standalone components EnvironmentInjector
  21796. if (standaloneInjectorToComponent.has(injector)) {
  21797. return standaloneInjectorToComponent.get(injector);
  21798. }
  21799. // Module injectors configure providers through their NgModule def, so we use the
  21800. // injector to lookup its NgModuleRef and through that grab its instance
  21801. const defTypeRef = injector.get(NgModuleRef$1, null, { self: true, optional: true });
  21802. // If we can't find an associated imports container, return null.
  21803. // This could be the case if this function is called with an R3Injector that does not represent
  21804. // a standalone component or NgModule.
  21805. if (defTypeRef === null) {
  21806. return null;
  21807. }
  21808. // In standalone applications, the root environment injector created by bootstrapApplication
  21809. // may have no associated "instance".
  21810. if (defTypeRef.instance === null) {
  21811. return null;
  21812. }
  21813. return defTypeRef.instance.constructor;
  21814. }
  21815. /**
  21816. * Gets the providers configured on a NodeInjector
  21817. *
  21818. * @param injector A NodeInjector instance
  21819. * @returns ProviderRecord[] an array of objects representing the providers configured on this
  21820. * injector
  21821. */
  21822. function getNodeInjectorProviders(injector) {
  21823. const diResolver = getNodeInjectorTNode(injector);
  21824. const { resolverToProviders } = getFrameworkDIDebugData();
  21825. return resolverToProviders.get(diResolver) ?? [];
  21826. }
  21827. /**
  21828. * Gets a mapping of providers configured on an injector to their import paths
  21829. *
  21830. * ModuleA -> imports ModuleB
  21831. * ModuleB -> imports ModuleC
  21832. * ModuleB -> provides MyServiceA
  21833. * ModuleC -> provides MyServiceB
  21834. *
  21835. * getProviderImportPaths(ModuleA)
  21836. * > Map(2) {
  21837. * MyServiceA => [ModuleA, ModuleB]
  21838. * MyServiceB => [ModuleA, ModuleB, ModuleC]
  21839. * }
  21840. *
  21841. * @param providerImportsContainer constructor of class that contains an `imports` array in it's
  21842. * definition
  21843. * @returns A Map object that maps providers to an array of constructors representing it's import
  21844. * path
  21845. *
  21846. */
  21847. function getProviderImportPaths(providerImportsContainer) {
  21848. const providerToPath = new Map();
  21849. const visitedContainers = new Set();
  21850. const visitor = walkProviderTreeToDiscoverImportPaths(providerToPath, visitedContainers);
  21851. walkProviderTree(providerImportsContainer, visitor, [], new Set());
  21852. return providerToPath;
  21853. }
  21854. /**
  21855. *
  21856. * Higher order function that returns a visitor for WalkProviderTree
  21857. *
  21858. * Takes in a Map and Set to keep track of the providers and containers
  21859. * visited, so that we can discover the import paths of these providers
  21860. * during the traversal.
  21861. *
  21862. * This visitor takes advantage of the fact that walkProviderTree performs a
  21863. * postorder traversal of the provider tree for the passed in container. Because postorder
  21864. * traversal recursively processes subtrees from leaf nodes until the traversal reaches the root,
  21865. * we write a visitor that constructs provider import paths in reverse.
  21866. *
  21867. *
  21868. * We use the visitedContainers set defined outside this visitor
  21869. * because we want to run some logic only once for
  21870. * each container in the tree. That logic can be described as:
  21871. *
  21872. *
  21873. * 1. for each discovered_provider and discovered_path in the incomplete provider paths we've
  21874. * already discovered
  21875. * 2. get the first container in discovered_path
  21876. * 3. if that first container is in the imports array of the container we're visiting
  21877. * Then the container we're visiting is also in the import path of discovered_provider, so we
  21878. * unshift discovered_path with the container we're currently visiting
  21879. *
  21880. *
  21881. * Example Run:
  21882. * ```
  21883. * ┌──────────┐
  21884. * │containerA│
  21885. * ┌─imports-─┤ ├──imports─┐
  21886. * │ │ provA │ │
  21887. * │ │ provB │ │
  21888. * │ └──────────┘ │
  21889. * │ │
  21890. * ┌▼─────────┐ ┌────────▼─┐
  21891. * │containerB│ │containerC│
  21892. * │ │ │ │
  21893. * │ provD │ │ provF │
  21894. * │ provE │ │ provG │
  21895. * └──────────┘ └──────────┘
  21896. * ```
  21897. *
  21898. * Each step of the traversal,
  21899. *
  21900. * ```
  21901. * visitor(provD, containerB)
  21902. * providerToPath === Map { provD => [containerB] }
  21903. * visitedContainers === Set { containerB }
  21904. *
  21905. * visitor(provE, containerB)
  21906. * providerToPath === Map { provD => [containerB], provE => [containerB] }
  21907. * visitedContainers === Set { containerB }
  21908. *
  21909. * visitor(provF, containerC)
  21910. * providerToPath === Map { provD => [containerB], provE => [containerB], provF => [containerC] }
  21911. * visitedContainers === Set { containerB, containerC }
  21912. *
  21913. * visitor(provG, containerC)
  21914. * providerToPath === Map {
  21915. * provD => [containerB], provE => [containerB], provF => [containerC], provG => [containerC]
  21916. * }
  21917. * visitedContainers === Set { containerB, containerC }
  21918. *
  21919. * visitor(provA, containerA)
  21920. * providerToPath === Map {
  21921. * provD => [containerA, containerB],
  21922. * provE => [containerA, containerB],
  21923. * provF => [containerA, containerC],
  21924. * provG => [containerA, containerC],
  21925. * provA => [containerA]
  21926. * }
  21927. * visitedContainers === Set { containerB, containerC, containerA }
  21928. *
  21929. * visitor(provB, containerA)
  21930. * providerToPath === Map {
  21931. * provD => [containerA, containerB],
  21932. * provE => [containerA, containerB],
  21933. * provF => [containerA, containerC],
  21934. * provG => [containerA, containerC],
  21935. * provA => [containerA]
  21936. * provB => [containerA]
  21937. * }
  21938. * visitedContainers === Set { containerB, containerC, containerA }
  21939. * ```
  21940. *
  21941. * @param providerToPath Map map of providers to paths that this function fills
  21942. * @param visitedContainers Set a set to keep track of the containers we've already visited
  21943. * @return function(provider SingleProvider, container: Type<unknown> | InjectorType<unknown>) =>
  21944. * void
  21945. */
  21946. function walkProviderTreeToDiscoverImportPaths(providerToPath, visitedContainers) {
  21947. return (provider, container) => {
  21948. // If the provider is not already in the providerToPath map,
  21949. // add an entry with the provider as the key and an array containing the current container as
  21950. // the value
  21951. if (!providerToPath.has(provider)) {
  21952. providerToPath.set(provider, [container]);
  21953. }
  21954. // This block will run exactly once for each container in the import tree.
  21955. // This is where we run the logic to check the imports array of the current
  21956. // container to see if it's the next container in the path for our currently
  21957. // discovered providers.
  21958. if (!visitedContainers.has(container)) {
  21959. // Iterate through the providers we've already seen
  21960. for (const prov of providerToPath.keys()) {
  21961. const existingImportPath = providerToPath.get(prov);
  21962. let containerDef = getInjectorDef(container);
  21963. if (!containerDef) {
  21964. const ngModule = container.ngModule;
  21965. containerDef = getInjectorDef(ngModule);
  21966. }
  21967. if (!containerDef) {
  21968. return;
  21969. }
  21970. const lastContainerAddedToPath = existingImportPath[0];
  21971. let isNextStepInPath = false;
  21972. deepForEach(containerDef.imports, (moduleImport) => {
  21973. if (isNextStepInPath) {
  21974. return;
  21975. }
  21976. isNextStepInPath =
  21977. moduleImport.ngModule === lastContainerAddedToPath ||
  21978. moduleImport === lastContainerAddedToPath;
  21979. if (isNextStepInPath) {
  21980. providerToPath.get(prov)?.unshift(container);
  21981. }
  21982. });
  21983. }
  21984. }
  21985. visitedContainers.add(container);
  21986. };
  21987. }
  21988. /**
  21989. * Gets the providers configured on an EnvironmentInjector
  21990. *
  21991. * @param injector EnvironmentInjector
  21992. * @returns an array of objects representing the providers of the given injector
  21993. */
  21994. function getEnvironmentInjectorProviders(injector) {
  21995. const providerRecordsWithoutImportPaths = getFrameworkDIDebugData().resolverToProviders.get(injector) ?? [];
  21996. // platform injector has no provider imports container so can we skip trying to
  21997. // find import paths
  21998. if (isPlatformInjector(injector)) {
  21999. return providerRecordsWithoutImportPaths;
  22000. }
  22001. const providerImportsContainer = getProviderImportsContainer(injector);
  22002. if (providerImportsContainer === null) {
  22003. // We assume that if an environment injector exists without an associated provider imports
  22004. // container, it was created without such a container. Some examples cases where this could
  22005. // happen:
  22006. // - The root injector of a standalone application
  22007. // - A router injector created by using the providers array in a lazy loaded route
  22008. // - A manually created injector that is attached to the injector tree
  22009. // Since each of these cases has no provider container, there is no concept of import paths,
  22010. // so we can simply return the provider records.
  22011. return providerRecordsWithoutImportPaths;
  22012. }
  22013. const providerToPath = getProviderImportPaths(providerImportsContainer);
  22014. const providerRecords = [];
  22015. for (const providerRecord of providerRecordsWithoutImportPaths) {
  22016. const provider = providerRecord.provider;
  22017. // Ignore these special providers for now until we have a cleaner way of
  22018. // determing when they are provided by the framework vs provided by the user.
  22019. const token = provider.provide;
  22020. if (token === ENVIRONMENT_INITIALIZER || token === INJECTOR_DEF_TYPES) {
  22021. continue;
  22022. }
  22023. let importPath = providerToPath.get(provider) ?? [];
  22024. const def = getComponentDef(providerImportsContainer);
  22025. const isStandaloneComponent = !!def?.standalone;
  22026. // We prepend the component constructor in the standalone case
  22027. // because walkProviderTree does not visit this constructor during it's traversal
  22028. if (isStandaloneComponent) {
  22029. importPath = [providerImportsContainer, ...importPath];
  22030. }
  22031. providerRecords.push({ ...providerRecord, importPath });
  22032. }
  22033. return providerRecords;
  22034. }
  22035. function isPlatformInjector(injector) {
  22036. return injector instanceof R3Injector && injector.scopes.has('platform');
  22037. }
  22038. /**
  22039. * Gets the providers configured on an injector.
  22040. *
  22041. * @param injector the injector to lookup the providers of
  22042. * @returns ProviderRecord[] an array of objects representing the providers of the given injector
  22043. */
  22044. function getInjectorProviders(injector) {
  22045. if (injector instanceof NodeInjector) {
  22046. return getNodeInjectorProviders(injector);
  22047. }
  22048. else if (injector instanceof EnvironmentInjector) {
  22049. return getEnvironmentInjectorProviders(injector);
  22050. }
  22051. throwError('getInjectorProviders only supports NodeInjector and EnvironmentInjector');
  22052. }
  22053. /**
  22054. *
  22055. * Given an injector, this function will return
  22056. * an object containing the type and source of the injector.
  22057. *
  22058. * | | type | source |
  22059. * |--------------|-------------|-------------------------------------------------------------|
  22060. * | NodeInjector | element | DOM element that created this injector |
  22061. * | R3Injector | environment | `injector.source` |
  22062. * | NullInjector | null | null |
  22063. *
  22064. * @param injector the Injector to get metadata for
  22065. * @returns an object containing the type and source of the given injector. If the injector metadata
  22066. * cannot be determined, returns null.
  22067. */
  22068. function getInjectorMetadata(injector) {
  22069. if (injector instanceof NodeInjector) {
  22070. const lView = getNodeInjectorLView(injector);
  22071. const tNode = getNodeInjectorTNode(injector);
  22072. assertTNodeForLView(tNode, lView);
  22073. return { type: 'element', source: getNativeByTNode(tNode, lView) };
  22074. }
  22075. if (injector instanceof R3Injector) {
  22076. return { type: 'environment', source: injector.source ?? null };
  22077. }
  22078. if (injector instanceof NullInjector) {
  22079. return { type: 'null', source: null };
  22080. }
  22081. return null;
  22082. }
  22083. function getInjectorResolutionPath(injector) {
  22084. const resolutionPath = [injector];
  22085. getInjectorResolutionPathHelper(injector, resolutionPath);
  22086. return resolutionPath;
  22087. }
  22088. function getInjectorResolutionPathHelper(injector, resolutionPath) {
  22089. const parent = getInjectorParent(injector);
  22090. // if getInjectorParent can't find a parent, then we've either reached the end
  22091. // of the path, or we need to move from the Element Injector tree to the
  22092. // module injector tree using the first injector in our path as the connection point.
  22093. if (parent === null) {
  22094. if (injector instanceof NodeInjector) {
  22095. const firstInjector = resolutionPath[0];
  22096. if (firstInjector instanceof NodeInjector) {
  22097. const moduleInjector = getModuleInjectorOfNodeInjector(firstInjector);
  22098. if (moduleInjector === null) {
  22099. throwError('NodeInjector must have some connection to the module injector tree');
  22100. }
  22101. resolutionPath.push(moduleInjector);
  22102. getInjectorResolutionPathHelper(moduleInjector, resolutionPath);
  22103. }
  22104. return resolutionPath;
  22105. }
  22106. }
  22107. else {
  22108. resolutionPath.push(parent);
  22109. getInjectorResolutionPathHelper(parent, resolutionPath);
  22110. }
  22111. return resolutionPath;
  22112. }
  22113. /**
  22114. * Gets the parent of an injector.
  22115. *
  22116. * This function is not able to make the jump from the Element Injector Tree to the Module
  22117. * injector tree. This is because the "parent" (the next step in the reoslution path)
  22118. * of a root NodeInjector is dependent on which NodeInjector ancestor initiated
  22119. * the DI lookup. See getInjectorResolutionPath for a function that can make this jump.
  22120. *
  22121. * In the below diagram:
  22122. * ```ts
  22123. * getInjectorParent(NodeInjectorB)
  22124. * > NodeInjectorA
  22125. * getInjectorParent(NodeInjectorA) // or getInjectorParent(getInjectorParent(NodeInjectorB))
  22126. * > null // cannot jump to ModuleInjector tree
  22127. * ```
  22128. *
  22129. * ```
  22130. * ┌───────┐ ┌───────────────────┐
  22131. * ┌───────────┤ModuleA├───Injector────►│EnvironmentInjector│
  22132. * │ └───┬───┘ └───────────────────┘
  22133. * │ │
  22134. * │ bootstraps
  22135. * │ │
  22136. * │ │
  22137. * │ ┌────▼─────┐ ┌─────────────┐
  22138. * declares │ComponentA├────Injector────►│NodeInjectorA│
  22139. * │ └────┬─────┘ └─────▲───────┘
  22140. * │ │ │
  22141. * │ renders parent
  22142. * │ │ │
  22143. * │ ┌────▼─────┐ ┌─────┴───────┐
  22144. * └─────────►│ComponentB├────Injector────►│NodeInjectorB│
  22145. * └──────────┘ └─────────────┘
  22146. *```
  22147. *
  22148. * @param injector an Injector to get the parent of
  22149. * @returns Injector the parent of the given injector
  22150. */
  22151. function getInjectorParent(injector) {
  22152. if (injector instanceof R3Injector) {
  22153. const parent = injector.parent;
  22154. if (isRouterOutletInjector(parent)) {
  22155. // This is a special case for a `ChainedInjector` instance, which represents
  22156. // a combination of a Router's `OutletInjector` and an EnvironmentInjector,
  22157. // which represents a `@defer` block. Since the `OutletInjector` doesn't store
  22158. // any tokens itself, we point to the parent injector instead. See the
  22159. // `OutletInjector.__ngOutletInjector` field for additional information.
  22160. return parent.parentInjector;
  22161. }
  22162. return parent;
  22163. }
  22164. let tNode;
  22165. let lView;
  22166. if (injector instanceof NodeInjector) {
  22167. tNode = getNodeInjectorTNode(injector);
  22168. lView = getNodeInjectorLView(injector);
  22169. }
  22170. else if (injector instanceof NullInjector) {
  22171. return null;
  22172. }
  22173. else if (injector instanceof ChainedInjector) {
  22174. return injector.parentInjector;
  22175. }
  22176. else {
  22177. throwError('getInjectorParent only support injectors of type R3Injector, NodeInjector, NullInjector');
  22178. }
  22179. const parentLocation = getParentInjectorLocation(tNode, lView);
  22180. if (hasParentInjector(parentLocation)) {
  22181. const parentInjectorIndex = getParentInjectorIndex(parentLocation);
  22182. const parentLView = getParentInjectorView(parentLocation, lView);
  22183. const parentTView = parentLView[TVIEW];
  22184. const parentTNode = parentTView.data[parentInjectorIndex + 8 /* NodeInjectorOffset.TNODE */];
  22185. return new NodeInjector(parentTNode, parentLView);
  22186. }
  22187. else {
  22188. const chainedInjector = lView[INJECTOR];
  22189. // Case where chainedInjector.injector is an OutletInjector and chainedInjector.injector.parent
  22190. // is a NodeInjector.
  22191. // todo(aleksanderbodurri): ideally nothing in packages/core should deal
  22192. // directly with router concerns. Refactor this so that we can make the jump from
  22193. // NodeInjector -> OutletInjector -> NodeInjector
  22194. // without explicitly relying on types contracts from packages/router
  22195. const injectorParent = chainedInjector.injector?.parent;
  22196. if (injectorParent instanceof NodeInjector) {
  22197. return injectorParent;
  22198. }
  22199. }
  22200. return null;
  22201. }
  22202. /**
  22203. * Gets the module injector of a NodeInjector.
  22204. *
  22205. * @param injector NodeInjector to get module injector of
  22206. * @returns Injector representing module injector of the given NodeInjector
  22207. */
  22208. function getModuleInjectorOfNodeInjector(injector) {
  22209. let lView;
  22210. if (injector instanceof NodeInjector) {
  22211. lView = getNodeInjectorLView(injector);
  22212. }
  22213. else {
  22214. throwError('getModuleInjectorOfNodeInjector must be called with a NodeInjector');
  22215. }
  22216. const inj = lView[INJECTOR];
  22217. const moduleInjector = inj instanceof ChainedInjector ? inj.parentInjector : inj.parent;
  22218. if (!moduleInjector) {
  22219. throwError('NodeInjector must have some connection to the module injector tree');
  22220. }
  22221. return moduleInjector;
  22222. }
  22223. function isComputedNode(node) {
  22224. return node.kind === 'computed';
  22225. }
  22226. function isTemplateEffectNode(node) {
  22227. return node.kind === 'template';
  22228. }
  22229. function isEffectNode(node) {
  22230. return node.kind === 'effect';
  22231. }
  22232. function isSignalNode(node) {
  22233. return node.kind === 'signal';
  22234. }
  22235. /**
  22236. *
  22237. * @param injector
  22238. * @returns Template consumer of given NodeInjector
  22239. */
  22240. function getTemplateConsumer(injector) {
  22241. const tNode = getNodeInjectorTNode(injector);
  22242. assertTNode(tNode);
  22243. const lView = getNodeInjectorLView(injector);
  22244. assertLView(lView);
  22245. const templateLView = lView[tNode.index];
  22246. assertLView(templateLView);
  22247. return templateLView[REACTIVE_TEMPLATE_CONSUMER];
  22248. }
  22249. function getNodesAndEdgesFromSignalMap(signalMap) {
  22250. const nodes = Array.from(signalMap.keys());
  22251. const debugSignalGraphNodes = [];
  22252. const edges = [];
  22253. for (const [consumer, producers] of signalMap.entries()) {
  22254. const consumerIndex = nodes.indexOf(consumer);
  22255. // collect node
  22256. if (isComputedNode(consumer) || isSignalNode(consumer)) {
  22257. debugSignalGraphNodes.push({
  22258. label: consumer.debugName,
  22259. value: consumer.value,
  22260. kind: consumer.kind,
  22261. });
  22262. }
  22263. else if (isTemplateEffectNode(consumer)) {
  22264. debugSignalGraphNodes.push({
  22265. label: consumer.debugName ?? consumer.lView?.[HOST]?.tagName?.toLowerCase?.(),
  22266. kind: consumer.kind,
  22267. });
  22268. }
  22269. else if (isEffectNode(consumer)) {
  22270. debugSignalGraphNodes.push({
  22271. label: consumer.debugName,
  22272. kind: consumer.kind,
  22273. });
  22274. }
  22275. else {
  22276. debugSignalGraphNodes.push({
  22277. label: consumer.debugName,
  22278. kind: consumer.kind,
  22279. });
  22280. }
  22281. // collect edges for node
  22282. for (const producer of producers) {
  22283. edges.push({ consumer: consumerIndex, producer: nodes.indexOf(producer) });
  22284. }
  22285. }
  22286. return { nodes: debugSignalGraphNodes, edges };
  22287. }
  22288. function extractEffectsFromInjector(injector) {
  22289. let diResolver = injector;
  22290. if (injector instanceof NodeInjector) {
  22291. const lView = getNodeInjectorLView(injector);
  22292. diResolver = lView;
  22293. }
  22294. const resolverToEffects = getFrameworkDIDebugData().resolverToEffects;
  22295. const effects = resolverToEffects.get(diResolver) ?? [];
  22296. return effects.map((effect) => effect[SIGNAL]);
  22297. }
  22298. function extractSignalNodesAndEdgesFromRoots(nodes, signalDependenciesMap = new Map()) {
  22299. for (const node of nodes) {
  22300. if (signalDependenciesMap.has(node)) {
  22301. continue;
  22302. }
  22303. const producerNodes = (node.producerNode ?? []);
  22304. signalDependenciesMap.set(node, producerNodes);
  22305. extractSignalNodesAndEdgesFromRoots(producerNodes, signalDependenciesMap);
  22306. }
  22307. return signalDependenciesMap;
  22308. }
  22309. /**
  22310. * Returns a debug representation of the signal graph for the given injector.
  22311. *
  22312. * Currently only supports element injectors. Starts by discovering the consumer nodes
  22313. * and then traverses their producer nodes to build the signal graph.
  22314. *
  22315. * @param injector The injector to get the signal graph for.
  22316. * @returns A debug representation of the signal graph.
  22317. * @throws If the injector is an environment injector.
  22318. */
  22319. function getSignalGraph(injector) {
  22320. let templateConsumer = null;
  22321. if (!(injector instanceof NodeInjector) && !(injector instanceof R3Injector)) {
  22322. return throwError('getSignalGraph must be called with a NodeInjector or R3Injector');
  22323. }
  22324. if (injector instanceof NodeInjector) {
  22325. templateConsumer = getTemplateConsumer(injector);
  22326. }
  22327. const nonTemplateEffectNodes = extractEffectsFromInjector(injector);
  22328. const signalNodes = templateConsumer
  22329. ? [templateConsumer, ...nonTemplateEffectNodes]
  22330. : nonTemplateEffectNodes;
  22331. const signalDependenciesMap = extractSignalNodesAndEdgesFromRoots(signalNodes);
  22332. return getNodesAndEdgesFromSignalMap(signalDependenciesMap);
  22333. }
  22334. /**
  22335. * This file introduces series of globally accessible debug tools
  22336. * to allow for the Angular debugging story to function.
  22337. *
  22338. * To see this in action run the following command:
  22339. *
  22340. * bazel run //packages/core/test/bundling/todo:devserver
  22341. *
  22342. * Then load `localhost:5432` and start using the console tools.
  22343. */
  22344. /**
  22345. * This value reflects the property on the window where the dev
  22346. * tools are patched (window.ng).
  22347. * */
  22348. const GLOBAL_PUBLISH_EXPANDO_KEY = 'ng';
  22349. const globalUtilsFunctions = {
  22350. /**
  22351. * Warning: functions that start with `ɵ` are considered *INTERNAL* and should not be relied upon
  22352. * in application's code. The contract of those functions might be changed in any release and/or a
  22353. * function can be removed completely.
  22354. */
  22355. 'ɵgetDependenciesFromInjectable': getDependenciesFromInjectable,
  22356. 'ɵgetInjectorProviders': getInjectorProviders,
  22357. 'ɵgetInjectorResolutionPath': getInjectorResolutionPath,
  22358. 'ɵgetInjectorMetadata': getInjectorMetadata,
  22359. 'ɵsetProfiler': setProfiler,
  22360. 'ɵgetSignalGraph': getSignalGraph,
  22361. 'ɵgetDeferBlocks': getDeferBlocks,
  22362. 'getDirectiveMetadata': getDirectiveMetadata$1,
  22363. 'getComponent': getComponent,
  22364. 'getContext': getContext,
  22365. 'getListeners': getListeners,
  22366. 'getOwningComponent': getOwningComponent,
  22367. 'getHostElement': getHostElement,
  22368. 'getInjector': getInjector,
  22369. 'getRootComponents': getRootComponents,
  22370. 'getDirectives': getDirectives,
  22371. 'applyChanges': applyChanges,
  22372. 'isSignal': isSignal,
  22373. };
  22374. let _published = false;
  22375. /**
  22376. * Publishes a collection of default debug tools onto`window.ng`.
  22377. *
  22378. * These functions are available globally when Angular is in development
  22379. * mode and are automatically stripped away from prod mode is on.
  22380. */
  22381. function publishDefaultGlobalUtils$1() {
  22382. if (!_published) {
  22383. _published = true;
  22384. if (typeof window !== 'undefined') {
  22385. // Only configure the injector profiler when running in the browser.
  22386. setupFrameworkInjectorProfiler();
  22387. }
  22388. for (const [methodName, method] of Object.entries(globalUtilsFunctions)) {
  22389. publishGlobalUtil(methodName, method);
  22390. }
  22391. }
  22392. }
  22393. /**
  22394. * Publishes the given function to `window.ng` so that it can be
  22395. * used from the browser console when an application is not in production.
  22396. */
  22397. function publishGlobalUtil(name, fn) {
  22398. publishUtil(name, fn);
  22399. }
  22400. /**
  22401. * Publishes the given function to `window.ng` from package other than @angular/core
  22402. * So that it can be used from the browser console when an application is not in production.
  22403. */
  22404. function publishExternalGlobalUtil(name, fn) {
  22405. publishUtil(name, fn);
  22406. }
  22407. function publishUtil(name, fn) {
  22408. if (typeof COMPILED === 'undefined' || !COMPILED) {
  22409. // Note: we can't export `ng` when using closure enhanced optimization as:
  22410. // - closure declares globals itself for minified names, which sometimes clobber our `ng` global
  22411. // - we can't declare a closure extern as the namespace `ng` is already used within Google
  22412. // for typings for AngularJS (via `goog.provide('ng....')`).
  22413. const w = _global;
  22414. ngDevMode && assertDefined(fn, 'function not defined');
  22415. w[GLOBAL_PUBLISH_EXPANDO_KEY] ??= {};
  22416. w[GLOBAL_PUBLISH_EXPANDO_KEY][name] = fn;
  22417. }
  22418. }
  22419. /**
  22420. * Internal injection token that can used to access an instance of a Testability class.
  22421. *
  22422. * This token acts as a bridge between the core bootstrap code and the `Testability` class. This is
  22423. * needed to ensure that there are no direct references to the `Testability` class, so it can be
  22424. * tree-shaken away (if not referenced). For the environments/setups when the `Testability` class
  22425. * should be available, this token is used to add a provider that references the `Testability`
  22426. * class. Otherwise, only this token is retained in a bundle, but the `Testability` class is not.
  22427. */
  22428. const TESTABILITY = new InjectionToken('');
  22429. /**
  22430. * Internal injection token to retrieve Testability getter class instance.
  22431. */
  22432. const TESTABILITY_GETTER = new InjectionToken('');
  22433. /**
  22434. * The Testability service provides testing hooks that can be accessed from
  22435. * the browser.
  22436. *
  22437. * Angular applications bootstrapped using an NgModule (via `@NgModule.bootstrap` field) will also
  22438. * instantiate Testability by default (in both development and production modes).
  22439. *
  22440. * For applications bootstrapped using the `bootstrapApplication` function, Testability is not
  22441. * included by default. You can include it into your applications by getting the list of necessary
  22442. * providers using the `provideProtractorTestingSupport()` function and adding them into the
  22443. * `options.providers` array. Example:
  22444. *
  22445. * ```ts
  22446. * import {provideProtractorTestingSupport} from '@angular/platform-browser';
  22447. *
  22448. * await bootstrapApplication(RootComponent, providers: [provideProtractorTestingSupport()]);
  22449. * ```
  22450. *
  22451. * @publicApi
  22452. */
  22453. class Testability {
  22454. _ngZone;
  22455. registry;
  22456. _isZoneStable = true;
  22457. _callbacks = [];
  22458. taskTrackingZone = null;
  22459. constructor(_ngZone, registry, testabilityGetter) {
  22460. this._ngZone = _ngZone;
  22461. this.registry = registry;
  22462. // If there was no Testability logic registered in the global scope
  22463. // before, register the current testability getter as a global one.
  22464. if (!_testabilityGetter) {
  22465. setTestabilityGetter(testabilityGetter);
  22466. testabilityGetter.addToWindow(registry);
  22467. }
  22468. this._watchAngularEvents();
  22469. _ngZone.run(() => {
  22470. this.taskTrackingZone =
  22471. typeof Zone == 'undefined' ? null : Zone.current.get('TaskTrackingZone');
  22472. });
  22473. }
  22474. _watchAngularEvents() {
  22475. this._ngZone.onUnstable.subscribe({
  22476. next: () => {
  22477. this._isZoneStable = false;
  22478. },
  22479. });
  22480. this._ngZone.runOutsideAngular(() => {
  22481. this._ngZone.onStable.subscribe({
  22482. next: () => {
  22483. NgZone.assertNotInAngularZone();
  22484. queueMicrotask(() => {
  22485. this._isZoneStable = true;
  22486. this._runCallbacksIfReady();
  22487. });
  22488. },
  22489. });
  22490. });
  22491. }
  22492. /**
  22493. * Whether an associated application is stable
  22494. */
  22495. isStable() {
  22496. return this._isZoneStable && !this._ngZone.hasPendingMacrotasks;
  22497. }
  22498. _runCallbacksIfReady() {
  22499. if (this.isStable()) {
  22500. // Schedules the call backs in a new frame so that it is always async.
  22501. queueMicrotask(() => {
  22502. while (this._callbacks.length !== 0) {
  22503. let cb = this._callbacks.pop();
  22504. clearTimeout(cb.timeoutId);
  22505. cb.doneCb();
  22506. }
  22507. });
  22508. }
  22509. else {
  22510. // Still not stable, send updates.
  22511. let pending = this.getPendingTasks();
  22512. this._callbacks = this._callbacks.filter((cb) => {
  22513. if (cb.updateCb && cb.updateCb(pending)) {
  22514. clearTimeout(cb.timeoutId);
  22515. return false;
  22516. }
  22517. return true;
  22518. });
  22519. }
  22520. }
  22521. getPendingTasks() {
  22522. if (!this.taskTrackingZone) {
  22523. return [];
  22524. }
  22525. // Copy the tasks data so that we don't leak tasks.
  22526. return this.taskTrackingZone.macroTasks.map((t) => {
  22527. return {
  22528. source: t.source,
  22529. // From TaskTrackingZone:
  22530. // https://github.com/angular/zone.js/blob/master/lib/zone-spec/task-tracking.ts#L40
  22531. creationLocation: t.creationLocation,
  22532. data: t.data,
  22533. };
  22534. });
  22535. }
  22536. addCallback(cb, timeout, updateCb) {
  22537. let timeoutId = -1;
  22538. if (timeout && timeout > 0) {
  22539. timeoutId = setTimeout(() => {
  22540. this._callbacks = this._callbacks.filter((cb) => cb.timeoutId !== timeoutId);
  22541. cb();
  22542. }, timeout);
  22543. }
  22544. this._callbacks.push({ doneCb: cb, timeoutId: timeoutId, updateCb: updateCb });
  22545. }
  22546. /**
  22547. * Wait for the application to be stable with a timeout. If the timeout is reached before that
  22548. * happens, the callback receives a list of the macro tasks that were pending, otherwise null.
  22549. *
  22550. * @param doneCb The callback to invoke when Angular is stable or the timeout expires
  22551. * whichever comes first.
  22552. * @param timeout Optional. The maximum time to wait for Angular to become stable. If not
  22553. * specified, whenStable() will wait forever.
  22554. * @param updateCb Optional. If specified, this callback will be invoked whenever the set of
  22555. * pending macrotasks changes. If this callback returns true doneCb will not be invoked
  22556. * and no further updates will be issued.
  22557. */
  22558. whenStable(doneCb, timeout, updateCb) {
  22559. if (updateCb && !this.taskTrackingZone) {
  22560. throw new Error('Task tracking zone is required when passing an update callback to ' +
  22561. 'whenStable(). Is "zone.js/plugins/task-tracking" loaded?');
  22562. }
  22563. this.addCallback(doneCb, timeout, updateCb);
  22564. this._runCallbacksIfReady();
  22565. }
  22566. /**
  22567. * Registers an application with a testability hook so that it can be tracked.
  22568. * @param token token of application, root element
  22569. *
  22570. * @internal
  22571. */
  22572. registerApplication(token) {
  22573. this.registry.registerApplication(token, this);
  22574. }
  22575. /**
  22576. * Unregisters an application.
  22577. * @param token token of application, root element
  22578. *
  22579. * @internal
  22580. */
  22581. unregisterApplication(token) {
  22582. this.registry.unregisterApplication(token);
  22583. }
  22584. /**
  22585. * Find providers by name
  22586. * @param using The root element to search from
  22587. * @param provider The name of binding variable
  22588. * @param exactMatch Whether using exactMatch
  22589. */
  22590. findProviders(using, provider, exactMatch) {
  22591. // TODO(juliemr): implement.
  22592. return [];
  22593. }
  22594. static ɵfac = function Testability_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || Testability)(ɵɵinject(NgZone), ɵɵinject(TestabilityRegistry), ɵɵinject(TESTABILITY_GETTER)); };
  22595. static ɵprov = /*@__PURE__*/ ɵɵdefineInjectable({ token: Testability, factory: Testability.ɵfac });
  22596. }
  22597. (() => { (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(Testability, [{
  22598. type: Injectable
  22599. }], () => [{ type: NgZone }, { type: TestabilityRegistry }, { type: undefined, decorators: [{
  22600. type: Inject,
  22601. args: [TESTABILITY_GETTER]
  22602. }] }], null); })();
  22603. /**
  22604. * A global registry of {@link Testability} instances for specific elements.
  22605. * @publicApi
  22606. */
  22607. class TestabilityRegistry {
  22608. /** @internal */
  22609. _applications = new Map();
  22610. /**
  22611. * Registers an application with a testability hook so that it can be tracked
  22612. * @param token token of application, root element
  22613. * @param testability Testability hook
  22614. */
  22615. registerApplication(token, testability) {
  22616. this._applications.set(token, testability);
  22617. }
  22618. /**
  22619. * Unregisters an application.
  22620. * @param token token of application, root element
  22621. */
  22622. unregisterApplication(token) {
  22623. this._applications.delete(token);
  22624. }
  22625. /**
  22626. * Unregisters all applications
  22627. */
  22628. unregisterAllApplications() {
  22629. this._applications.clear();
  22630. }
  22631. /**
  22632. * Get a testability hook associated with the application
  22633. * @param elem root element
  22634. */
  22635. getTestability(elem) {
  22636. return this._applications.get(elem) || null;
  22637. }
  22638. /**
  22639. * Get all registered testabilities
  22640. */
  22641. getAllTestabilities() {
  22642. return Array.from(this._applications.values());
  22643. }
  22644. /**
  22645. * Get all registered applications(root elements)
  22646. */
  22647. getAllRootElements() {
  22648. return Array.from(this._applications.keys());
  22649. }
  22650. /**
  22651. * Find testability of a node in the Tree
  22652. * @param elem node
  22653. * @param findInAncestors whether finding testability in ancestors if testability was not found in
  22654. * current node
  22655. */
  22656. findTestabilityInTree(elem, findInAncestors = true) {
  22657. return _testabilityGetter?.findTestabilityInTree(this, elem, findInAncestors) ?? null;
  22658. }
  22659. static ɵfac = function TestabilityRegistry_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || TestabilityRegistry)(); };
  22660. static ɵprov = /*@__PURE__*/ ɵɵdefineInjectable({ token: TestabilityRegistry, factory: TestabilityRegistry.ɵfac, providedIn: 'platform' });
  22661. }
  22662. (() => { (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(TestabilityRegistry, [{
  22663. type: Injectable,
  22664. args: [{ providedIn: 'platform' }]
  22665. }], null, null); })();
  22666. /**
  22667. * Set the {@link GetTestability} implementation used by the Angular testing framework.
  22668. * @publicApi
  22669. */
  22670. function setTestabilityGetter(getter) {
  22671. _testabilityGetter = getter;
  22672. }
  22673. let _testabilityGetter;
  22674. /**
  22675. * A scheduler which manages the execution of effects.
  22676. */
  22677. class EffectScheduler {
  22678. /** @nocollapse */
  22679. static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
  22680. token: EffectScheduler,
  22681. providedIn: 'root',
  22682. factory: () => new ZoneAwareEffectScheduler(),
  22683. });
  22684. }
  22685. /**
  22686. * A wrapper around `ZoneAwareQueueingScheduler` that schedules flushing via the microtask queue
  22687. * when.
  22688. */
  22689. class ZoneAwareEffectScheduler {
  22690. queuedEffectCount = 0;
  22691. queues = new Map();
  22692. schedule(handle) {
  22693. this.enqueue(handle);
  22694. }
  22695. remove(handle) {
  22696. const zone = handle.zone;
  22697. const queue = this.queues.get(zone);
  22698. if (!queue.has(handle)) {
  22699. return;
  22700. }
  22701. queue.delete(handle);
  22702. this.queuedEffectCount--;
  22703. }
  22704. enqueue(handle) {
  22705. const zone = handle.zone;
  22706. if (!this.queues.has(zone)) {
  22707. this.queues.set(zone, new Set());
  22708. }
  22709. const queue = this.queues.get(zone);
  22710. if (queue.has(handle)) {
  22711. return;
  22712. }
  22713. this.queuedEffectCount++;
  22714. queue.add(handle);
  22715. }
  22716. /**
  22717. * Run all scheduled effects.
  22718. *
  22719. * Execution order of effects within the same zone is guaranteed to be FIFO, but there is no
  22720. * ordering guarantee between effects scheduled in different zones.
  22721. */
  22722. flush() {
  22723. while (this.queuedEffectCount > 0) {
  22724. for (const [zone, queue] of this.queues) {
  22725. // `zone` here must be defined.
  22726. if (zone === null) {
  22727. this.flushQueue(queue);
  22728. }
  22729. else {
  22730. zone.run(() => this.flushQueue(queue));
  22731. }
  22732. }
  22733. }
  22734. }
  22735. flushQueue(queue) {
  22736. for (const handle of queue) {
  22737. queue.delete(handle);
  22738. this.queuedEffectCount--;
  22739. // TODO: what happens if this throws an error?
  22740. handle.run();
  22741. }
  22742. }
  22743. }
  22744. /**
  22745. * Determine if the argument is shaped like a Promise
  22746. */
  22747. function isPromise(obj) {
  22748. // allow any Promise/A+ compliant thenable.
  22749. // It's up to the caller to ensure that obj.then conforms to the spec
  22750. return !!obj && typeof obj.then === 'function';
  22751. }
  22752. /**
  22753. * Determine if the argument is a Subscribable
  22754. */
  22755. function isSubscribable(obj) {
  22756. return !!obj && typeof obj.subscribe === 'function';
  22757. }
  22758. /**
  22759. * A DI token that you can use to provide
  22760. * one or more initialization functions.
  22761. *
  22762. * The provided functions are injected at application startup and executed during
  22763. * app initialization. If any of these functions returns a Promise or an Observable, initialization
  22764. * does not complete until the Promise is resolved or the Observable is completed.
  22765. *
  22766. * You can, for example, create a factory function that loads language data
  22767. * or an external configuration, and provide that function to the `APP_INITIALIZER` token.
  22768. * The function is executed during the application bootstrap process,
  22769. * and the needed data is available on startup.
  22770. *
  22771. * Note that the provided initializer is run in the injection context.
  22772. *
  22773. * @deprecated from v19.0.0, use provideAppInitializer instead
  22774. *
  22775. * @see {@link ApplicationInitStatus}
  22776. * @see {@link provideAppInitializer}
  22777. *
  22778. * @usageNotes
  22779. *
  22780. * The following example illustrates how to configure a multi-provider using `APP_INITIALIZER` token
  22781. * and a function returning a promise.
  22782. * ### Example with NgModule-based application
  22783. * ```ts
  22784. * function initializeApp(): Promise<any> {
  22785. * const http = inject(HttpClient);
  22786. * return firstValueFrom(
  22787. * http
  22788. * .get("https://someUrl.com/api/user")
  22789. * .pipe(tap(user => { ... }))
  22790. * );
  22791. * }
  22792. *
  22793. * @NgModule({
  22794. * imports: [BrowserModule],
  22795. * declarations: [AppComponent],
  22796. * bootstrap: [AppComponent],
  22797. * providers: [{
  22798. * provide: APP_INITIALIZER,
  22799. * useValue: initializeApp,
  22800. * multi: true,
  22801. * }]
  22802. * })
  22803. * export class AppModule {}
  22804. * ```
  22805. *
  22806. * ### Example with standalone application
  22807. * ```ts
  22808. * function initializeApp() {
  22809. * const http = inject(HttpClient);
  22810. * return firstValueFrom(
  22811. * http
  22812. * .get("https://someUrl.com/api/user")
  22813. * .pipe(tap(user => { ... }))
  22814. * );
  22815. * }
  22816. *
  22817. * bootstrapApplication(App, {
  22818. * providers: [
  22819. * provideHttpClient(),
  22820. * {
  22821. * provide: APP_INITIALIZER,
  22822. * useValue: initializeApp,
  22823. * multi: true,
  22824. * },
  22825. * ],
  22826. * });
  22827. * ```
  22828. *
  22829. *
  22830. * It's also possible to configure a multi-provider using `APP_INITIALIZER` token and a function
  22831. * returning an observable, see an example below. Note: the `HttpClient` in this example is used for
  22832. * demo purposes to illustrate how the factory function can work with other providers available
  22833. * through DI.
  22834. *
  22835. * ### Example with NgModule-based application
  22836. * ```ts
  22837. * function initializeApp() {
  22838. * const http = inject(HttpClient);
  22839. * return firstValueFrom(
  22840. * http
  22841. * .get("https://someUrl.com/api/user")
  22842. * .pipe(tap(user => { ... }))
  22843. * );
  22844. * }
  22845. *
  22846. * @NgModule({
  22847. * imports: [BrowserModule, HttpClientModule],
  22848. * declarations: [AppComponent],
  22849. * bootstrap: [AppComponent],
  22850. * providers: [{
  22851. * provide: APP_INITIALIZER,
  22852. * useValue: initializeApp,
  22853. * multi: true,
  22854. * }]
  22855. * })
  22856. * export class AppModule {}
  22857. * ```
  22858. *
  22859. * ### Example with standalone application
  22860. * ```ts
  22861. * function initializeApp() {
  22862. * const http = inject(HttpClient);
  22863. * return firstValueFrom(
  22864. * http
  22865. * .get("https://someUrl.com/api/user")
  22866. * .pipe(tap(user => { ... }))
  22867. * );
  22868. * }
  22869. *
  22870. * bootstrapApplication(App, {
  22871. * providers: [
  22872. * provideHttpClient(),
  22873. * {
  22874. * provide: APP_INITIALIZER,
  22875. * useValue: initializeApp,
  22876. * multi: true,
  22877. * },
  22878. * ],
  22879. * });
  22880. * ```
  22881. *
  22882. * @publicApi
  22883. */
  22884. const APP_INITIALIZER = new InjectionToken(ngDevMode ? 'Application Initializer' : '');
  22885. /**
  22886. * @description
  22887. * The provided function is injected at application startup and executed during
  22888. * app initialization. If the function returns a Promise or an Observable, initialization
  22889. * does not complete until the Promise is resolved or the Observable is completed.
  22890. *
  22891. * You can, for example, create a function that loads language data
  22892. * or an external configuration, and provide that function using `provideAppInitializer()`.
  22893. * The function is executed during the application bootstrap process,
  22894. * and the needed data is available on startup.
  22895. *
  22896. * Note that the provided initializer is run in the injection context.
  22897. *
  22898. * Previously, this was achieved using the `APP_INITIALIZER` token which is now deprecated.
  22899. *
  22900. * @see {@link APP_INITIALIZER}
  22901. *
  22902. * @usageNotes
  22903. * The following example illustrates how to configure an initialization function using
  22904. * `provideAppInitializer()`
  22905. * ```ts
  22906. * bootstrapApplication(App, {
  22907. * providers: [
  22908. * provideAppInitializer(() => {
  22909. * const http = inject(HttpClient);
  22910. * return firstValueFrom(
  22911. * http
  22912. * .get("https://someUrl.com/api/user")
  22913. * .pipe(tap(user => { ... }))
  22914. * );
  22915. * }),
  22916. * provideHttpClient(),
  22917. * ],
  22918. * });
  22919. * ```
  22920. *
  22921. * @publicApi
  22922. */
  22923. function provideAppInitializer(initializerFn) {
  22924. return makeEnvironmentProviders([
  22925. {
  22926. provide: APP_INITIALIZER,
  22927. multi: true,
  22928. useValue: initializerFn,
  22929. },
  22930. ]);
  22931. }
  22932. /**
  22933. * A class that reflects the state of running {@link APP_INITIALIZER} functions.
  22934. *
  22935. * @publicApi
  22936. */
  22937. class ApplicationInitStatus {
  22938. // Using non null assertion, these fields are defined below
  22939. // within the `new Promise` callback (synchronously).
  22940. resolve;
  22941. reject;
  22942. initialized = false;
  22943. done = false;
  22944. donePromise = new Promise((res, rej) => {
  22945. this.resolve = res;
  22946. this.reject = rej;
  22947. });
  22948. appInits = inject(APP_INITIALIZER, { optional: true }) ?? [];
  22949. injector = inject(Injector);
  22950. constructor() {
  22951. if ((typeof ngDevMode === 'undefined' || ngDevMode) && !Array.isArray(this.appInits)) {
  22952. throw new RuntimeError(-209 /* RuntimeErrorCode.INVALID_MULTI_PROVIDER */, 'Unexpected type of the `APP_INITIALIZER` token value ' +
  22953. `(expected an array, but got ${typeof this.appInits}). ` +
  22954. 'Please check that the `APP_INITIALIZER` token is configured as a ' +
  22955. '`multi: true` provider.');
  22956. }
  22957. }
  22958. /** @internal */
  22959. runInitializers() {
  22960. if (this.initialized) {
  22961. return;
  22962. }
  22963. const asyncInitPromises = [];
  22964. for (const appInits of this.appInits) {
  22965. const initResult = runInInjectionContext(this.injector, appInits);
  22966. if (isPromise(initResult)) {
  22967. asyncInitPromises.push(initResult);
  22968. }
  22969. else if (isSubscribable(initResult)) {
  22970. const observableAsPromise = new Promise((resolve, reject) => {
  22971. initResult.subscribe({ complete: resolve, error: reject });
  22972. });
  22973. asyncInitPromises.push(observableAsPromise);
  22974. }
  22975. }
  22976. const complete = () => {
  22977. // @ts-expect-error overwriting a readonly
  22978. this.done = true;
  22979. this.resolve();
  22980. };
  22981. Promise.all(asyncInitPromises)
  22982. .then(() => {
  22983. complete();
  22984. })
  22985. .catch((e) => {
  22986. this.reject(e);
  22987. });
  22988. if (asyncInitPromises.length === 0) {
  22989. complete();
  22990. }
  22991. this.initialized = true;
  22992. }
  22993. static ɵfac = function ApplicationInitStatus_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || ApplicationInitStatus)(); };
  22994. static ɵprov = /*@__PURE__*/ ɵɵdefineInjectable({ token: ApplicationInitStatus, factory: ApplicationInitStatus.ɵfac, providedIn: 'root' });
  22995. }
  22996. (() => { (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(ApplicationInitStatus, [{
  22997. type: Injectable,
  22998. args: [{ providedIn: 'root' }]
  22999. }], () => [], null); })();
  23000. /**
  23001. * A DI token that provides a set of callbacks to
  23002. * be called for every component that is bootstrapped.
  23003. *
  23004. * Each callback must take a `ComponentRef` instance and return nothing.
  23005. *
  23006. * `(componentRef: ComponentRef) => void`
  23007. *
  23008. * @publicApi
  23009. */
  23010. const APP_BOOTSTRAP_LISTENER = new InjectionToken(ngDevMode ? 'appBootstrapListener' : '');
  23011. function publishDefaultGlobalUtils() {
  23012. ngDevMode && publishDefaultGlobalUtils$1();
  23013. }
  23014. /**
  23015. * Sets the error for an invalid write to a signal to be an Angular `RuntimeError`.
  23016. */
  23017. function publishSignalConfiguration() {
  23018. setThrowInvalidWriteToSignalError(() => {
  23019. throw new RuntimeError(600 /* RuntimeErrorCode.SIGNAL_WRITE_FROM_ILLEGAL_CONTEXT */, ngDevMode && 'Writing to signals is not allowed in a `computed`.');
  23020. });
  23021. }
  23022. function isBoundToModule(cf) {
  23023. return cf.isBoundToModule;
  23024. }
  23025. /**
  23026. * A token for third-party components that can register themselves with NgProbe.
  23027. *
  23028. * @deprecated
  23029. * @publicApi
  23030. */
  23031. class NgProbeToken {
  23032. name;
  23033. token;
  23034. constructor(name, token) {
  23035. this.name = name;
  23036. this.token = token;
  23037. }
  23038. }
  23039. /** Maximum number of times ApplicationRef will refresh all attached views in a single tick. */
  23040. const MAXIMUM_REFRESH_RERUNS = 10;
  23041. function optionsReducer(dst, objs) {
  23042. if (Array.isArray(objs)) {
  23043. return objs.reduce(optionsReducer, dst);
  23044. }
  23045. return { ...dst, ...objs };
  23046. }
  23047. /**
  23048. * A reference to an Angular application running on a page.
  23049. *
  23050. * @usageNotes
  23051. * ### isStable examples and caveats
  23052. *
  23053. * Note two important points about `isStable`, demonstrated in the examples below:
  23054. * - the application will never be stable if you start any kind
  23055. * of recurrent asynchronous task when the application starts
  23056. * (for example for a polling process, started with a `setInterval`, a `setTimeout`
  23057. * or using RxJS operators like `interval`);
  23058. * - the `isStable` Observable runs outside of the Angular zone.
  23059. *
  23060. * Let's imagine that you start a recurrent task
  23061. * (here incrementing a counter, using RxJS `interval`),
  23062. * and at the same time subscribe to `isStable`.
  23063. *
  23064. * ```ts
  23065. * constructor(appRef: ApplicationRef) {
  23066. * appRef.isStable.pipe(
  23067. * filter(stable => stable)
  23068. * ).subscribe(() => console.log('App is stable now');
  23069. * interval(1000).subscribe(counter => console.log(counter));
  23070. * }
  23071. * ```
  23072. * In this example, `isStable` will never emit `true`,
  23073. * and the trace "App is stable now" will never get logged.
  23074. *
  23075. * If you want to execute something when the app is stable,
  23076. * you have to wait for the application to be stable
  23077. * before starting your polling process.
  23078. *
  23079. * ```ts
  23080. * constructor(appRef: ApplicationRef) {
  23081. * appRef.isStable.pipe(
  23082. * first(stable => stable),
  23083. * tap(stable => console.log('App is stable now')),
  23084. * switchMap(() => interval(1000))
  23085. * ).subscribe(counter => console.log(counter));
  23086. * }
  23087. * ```
  23088. * In this example, the trace "App is stable now" will be logged
  23089. * and then the counter starts incrementing every second.
  23090. *
  23091. * Note also that this Observable runs outside of the Angular zone,
  23092. * which means that the code in the subscription
  23093. * to this Observable will not trigger the change detection.
  23094. *
  23095. * Let's imagine that instead of logging the counter value,
  23096. * you update a field of your component
  23097. * and display it in its template.
  23098. *
  23099. * ```ts
  23100. * constructor(appRef: ApplicationRef) {
  23101. * appRef.isStable.pipe(
  23102. * first(stable => stable),
  23103. * switchMap(() => interval(1000))
  23104. * ).subscribe(counter => this.value = counter);
  23105. * }
  23106. * ```
  23107. * As the `isStable` Observable runs outside the zone,
  23108. * the `value` field will be updated properly,
  23109. * but the template will not be refreshed!
  23110. *
  23111. * You'll have to manually trigger the change detection to update the template.
  23112. *
  23113. * ```ts
  23114. * constructor(appRef: ApplicationRef, cd: ChangeDetectorRef) {
  23115. * appRef.isStable.pipe(
  23116. * first(stable => stable),
  23117. * switchMap(() => interval(1000))
  23118. * ).subscribe(counter => {
  23119. * this.value = counter;
  23120. * cd.detectChanges();
  23121. * });
  23122. * }
  23123. * ```
  23124. *
  23125. * Or make the subscription callback run inside the zone.
  23126. *
  23127. * ```ts
  23128. * constructor(appRef: ApplicationRef, zone: NgZone) {
  23129. * appRef.isStable.pipe(
  23130. * first(stable => stable),
  23131. * switchMap(() => interval(1000))
  23132. * ).subscribe(counter => zone.run(() => this.value = counter));
  23133. * }
  23134. * ```
  23135. *
  23136. * @publicApi
  23137. */
  23138. class ApplicationRef {
  23139. /** @internal */
  23140. _runningTick = false;
  23141. _destroyed = false;
  23142. _destroyListeners = [];
  23143. /** @internal */
  23144. _views = [];
  23145. internalErrorHandler = inject(INTERNAL_APPLICATION_ERROR_HANDLER);
  23146. afterRenderManager = inject(AfterRenderManager);
  23147. zonelessEnabled = inject(ZONELESS_ENABLED);
  23148. rootEffectScheduler = inject(EffectScheduler);
  23149. /**
  23150. * Current dirty state of the application across a number of dimensions (views, afterRender hooks,
  23151. * etc).
  23152. *
  23153. * A flag set here means that `tick()` will attempt to resolve the dirtiness when executed.
  23154. *
  23155. * @internal
  23156. */
  23157. dirtyFlags = 0 /* ApplicationRefDirtyFlags.None */;
  23158. /**
  23159. * Most recent snapshot from the `TracingService`, if any.
  23160. *
  23161. * This snapshot attempts to capture the context when `tick()` was first
  23162. * scheduled. It then runs wrapped in this context.
  23163. *
  23164. * @internal
  23165. */
  23166. tracingSnapshot = null;
  23167. // Needed for ComponentFixture temporarily during migration of autoDetect behavior
  23168. // Eventually the hostView of the fixture should just attach to ApplicationRef.
  23169. externalTestViews = new Set();
  23170. /** @internal */
  23171. afterTick = new Subject();
  23172. /** @internal */
  23173. get allViews() {
  23174. return [...this.externalTestViews.keys(), ...this._views];
  23175. }
  23176. /**
  23177. * Indicates whether this instance was destroyed.
  23178. */
  23179. get destroyed() {
  23180. return this._destroyed;
  23181. }
  23182. /**
  23183. * Get a list of component types registered to this application.
  23184. * This list is populated even before the component is created.
  23185. */
  23186. componentTypes = [];
  23187. /**
  23188. * Get a list of components registered to this application.
  23189. */
  23190. components = [];
  23191. /**
  23192. * Returns an Observable that indicates when the application is stable or unstable.
  23193. */
  23194. isStable = inject(PendingTasksInternal).hasPendingTasks.pipe(map((pending) => !pending));
  23195. constructor() {
  23196. // Inject the tracing service to initialize it.
  23197. inject(TracingService, { optional: true });
  23198. }
  23199. /**
  23200. * @returns A promise that resolves when the application becomes stable
  23201. */
  23202. whenStable() {
  23203. let subscription;
  23204. return new Promise((resolve) => {
  23205. subscription = this.isStable.subscribe({
  23206. next: (stable) => {
  23207. if (stable) {
  23208. resolve();
  23209. }
  23210. },
  23211. });
  23212. }).finally(() => {
  23213. subscription.unsubscribe();
  23214. });
  23215. }
  23216. _injector = inject(EnvironmentInjector);
  23217. _rendererFactory = null;
  23218. /**
  23219. * The `EnvironmentInjector` used to create this application.
  23220. */
  23221. get injector() {
  23222. return this._injector;
  23223. }
  23224. /**
  23225. * Bootstrap a component onto the element identified by its selector or, optionally, to a
  23226. * specified element.
  23227. *
  23228. * @usageNotes
  23229. * ### Bootstrap process
  23230. *
  23231. * When bootstrapping a component, Angular mounts it onto a target DOM element
  23232. * and kicks off automatic change detection. The target DOM element can be
  23233. * provided using the `rootSelectorOrNode` argument.
  23234. *
  23235. * If the target DOM element is not provided, Angular tries to find one on a page
  23236. * using the `selector` of the component that is being bootstrapped
  23237. * (first matched element is used).
  23238. *
  23239. * ### Example
  23240. *
  23241. * Generally, we define the component to bootstrap in the `bootstrap` array of `NgModule`,
  23242. * but it requires us to know the component while writing the application code.
  23243. *
  23244. * Imagine a situation where we have to wait for an API call to decide about the component to
  23245. * bootstrap. We can use the `ngDoBootstrap` hook of the `NgModule` and call this method to
  23246. * dynamically bootstrap a component.
  23247. *
  23248. * {@example core/ts/platform/platform.ts region='componentSelector'}
  23249. *
  23250. * Optionally, a component can be mounted onto a DOM element that does not match the
  23251. * selector of the bootstrapped component.
  23252. *
  23253. * In the following example, we are providing a CSS selector to match the target element.
  23254. *
  23255. * {@example core/ts/platform/platform.ts region='cssSelector'}
  23256. *
  23257. * While in this example, we are providing reference to a DOM node.
  23258. *
  23259. * {@example core/ts/platform/platform.ts region='domNode'}
  23260. */
  23261. bootstrap(componentOrFactory, rootSelectorOrNode) {
  23262. profiler(10 /* ProfilerEvent.BootstrapComponentStart */);
  23263. (typeof ngDevMode === 'undefined' || ngDevMode) && warnIfDestroyed(this._destroyed);
  23264. const isComponentFactory = componentOrFactory instanceof ComponentFactory$1;
  23265. const initStatus = this._injector.get(ApplicationInitStatus);
  23266. if (!initStatus.done) {
  23267. let errorMessage = '';
  23268. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  23269. const standalone = !isComponentFactory && isStandalone(componentOrFactory);
  23270. errorMessage =
  23271. 'Cannot bootstrap as there are still asynchronous initializers running.' +
  23272. (standalone
  23273. ? ''
  23274. : ' Bootstrap components in the `ngDoBootstrap` method of the root module.');
  23275. }
  23276. throw new RuntimeError(405 /* RuntimeErrorCode.ASYNC_INITIALIZERS_STILL_RUNNING */, errorMessage);
  23277. }
  23278. let componentFactory;
  23279. if (isComponentFactory) {
  23280. componentFactory = componentOrFactory;
  23281. }
  23282. else {
  23283. const resolver = this._injector.get(ComponentFactoryResolver$1);
  23284. componentFactory = resolver.resolveComponentFactory(componentOrFactory);
  23285. }
  23286. this.componentTypes.push(componentFactory.componentType);
  23287. // Create a factory associated with the current module if it's not bound to some other
  23288. const ngModule = isBoundToModule(componentFactory)
  23289. ? undefined
  23290. : this._injector.get(NgModuleRef$1);
  23291. const selectorOrNode = rootSelectorOrNode || componentFactory.selector;
  23292. const compRef = componentFactory.create(Injector.NULL, [], selectorOrNode, ngModule);
  23293. const nativeElement = compRef.location.nativeElement;
  23294. const testability = compRef.injector.get(TESTABILITY, null);
  23295. testability?.registerApplication(nativeElement);
  23296. compRef.onDestroy(() => {
  23297. this.detachView(compRef.hostView);
  23298. remove(this.components, compRef);
  23299. testability?.unregisterApplication(nativeElement);
  23300. });
  23301. this._loadComponent(compRef);
  23302. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  23303. const _console = this._injector.get(Console);
  23304. _console.log(`Angular is running in development mode.`);
  23305. }
  23306. profiler(11 /* ProfilerEvent.BootstrapComponentEnd */, compRef);
  23307. return compRef;
  23308. }
  23309. /**
  23310. * Invoke this method to explicitly process change detection and its side-effects.
  23311. *
  23312. * In development mode, `tick()` also performs a second change detection cycle to ensure that no
  23313. * further changes are detected. If additional changes are picked up during this second cycle,
  23314. * bindings in the app have side-effects that cannot be resolved in a single change detection
  23315. * pass.
  23316. * In this case, Angular throws an error, since an Angular application can only have one change
  23317. * detection pass during which all change detection must complete.
  23318. */
  23319. tick() {
  23320. if (!this.zonelessEnabled) {
  23321. this.dirtyFlags |= 1 /* ApplicationRefDirtyFlags.ViewTreeGlobal */;
  23322. }
  23323. this._tick();
  23324. }
  23325. /** @internal */
  23326. _tick() {
  23327. profiler(12 /* ProfilerEvent.ChangeDetectionStart */);
  23328. if (this.tracingSnapshot !== null) {
  23329. // Ensure we always run `tickImpl()` in the context of the most recent snapshot,
  23330. // if one exists. Snapshots may be reference counted by the implementation so
  23331. // we want to ensure that if we request a snapshot that we use it.
  23332. this.tracingSnapshot.run(TracingAction.CHANGE_DETECTION, this.tickImpl);
  23333. }
  23334. else {
  23335. this.tickImpl();
  23336. }
  23337. }
  23338. tickImpl = () => {
  23339. (typeof ngDevMode === 'undefined' || ngDevMode) && warnIfDestroyed(this._destroyed);
  23340. if (this._runningTick) {
  23341. throw new RuntimeError(101 /* RuntimeErrorCode.RECURSIVE_APPLICATION_REF_TICK */, ngDevMode && 'ApplicationRef.tick is called recursively');
  23342. }
  23343. const prevConsumer = setActiveConsumer$1(null);
  23344. try {
  23345. this._runningTick = true;
  23346. this.synchronize();
  23347. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  23348. for (let view of this.allViews) {
  23349. view.checkNoChanges();
  23350. }
  23351. }
  23352. }
  23353. catch (e) {
  23354. // Attention: Don't rethrow as it could cancel subscriptions to Observables!
  23355. this.internalErrorHandler(e);
  23356. }
  23357. finally {
  23358. this._runningTick = false;
  23359. this.tracingSnapshot?.dispose();
  23360. this.tracingSnapshot = null;
  23361. setActiveConsumer$1(prevConsumer);
  23362. this.afterTick.next();
  23363. profiler(13 /* ProfilerEvent.ChangeDetectionEnd */);
  23364. }
  23365. };
  23366. /**
  23367. * Performs the core work of synchronizing the application state with the UI, resolving any
  23368. * pending dirtiness (potentially in a loop).
  23369. */
  23370. synchronize() {
  23371. if (this._rendererFactory === null && !this._injector.destroyed) {
  23372. this._rendererFactory = this._injector.get(RendererFactory2, null, { optional: true });
  23373. }
  23374. let runs = 0;
  23375. while (this.dirtyFlags !== 0 /* ApplicationRefDirtyFlags.None */ && runs++ < MAXIMUM_REFRESH_RERUNS) {
  23376. profiler(14 /* ProfilerEvent.ChangeDetectionSyncStart */);
  23377. this.synchronizeOnce();
  23378. profiler(15 /* ProfilerEvent.ChangeDetectionSyncEnd */);
  23379. }
  23380. if ((typeof ngDevMode === 'undefined' || ngDevMode) && runs >= MAXIMUM_REFRESH_RERUNS) {
  23381. throw new RuntimeError(103 /* RuntimeErrorCode.INFINITE_CHANGE_DETECTION */, ngDevMode &&
  23382. 'Infinite change detection while refreshing application views. ' +
  23383. 'Ensure views are not calling `markForCheck` on every template execution or ' +
  23384. 'that afterRender hooks always mark views for check.');
  23385. }
  23386. }
  23387. /**
  23388. * Perform a single synchronization pass.
  23389. */
  23390. synchronizeOnce() {
  23391. // First, process any dirty root effects.
  23392. if (this.dirtyFlags & 16 /* ApplicationRefDirtyFlags.RootEffects */) {
  23393. this.dirtyFlags &= -17 /* ApplicationRefDirtyFlags.RootEffects */;
  23394. this.rootEffectScheduler.flush();
  23395. }
  23396. // First check dirty views, if there are any.
  23397. if (this.dirtyFlags & 7 /* ApplicationRefDirtyFlags.ViewTreeAny */) {
  23398. // Change detection on views starts in targeted mode (only check components if they're
  23399. // marked as dirty) unless global checking is specifically requested via APIs like
  23400. // `ApplicationRef.tick()` and the `NgZone` integration.
  23401. const useGlobalCheck = Boolean(this.dirtyFlags & 1 /* ApplicationRefDirtyFlags.ViewTreeGlobal */);
  23402. // Clear the view-related dirty flags.
  23403. this.dirtyFlags &= -8 /* ApplicationRefDirtyFlags.ViewTreeAny */;
  23404. // Set the AfterRender bit, as we're checking views and will need to run afterRender hooks.
  23405. this.dirtyFlags |= 8 /* ApplicationRefDirtyFlags.AfterRender */;
  23406. // Check all potentially dirty views.
  23407. for (let { _lView, notifyErrorHandler } of this.allViews) {
  23408. detectChangesInViewIfRequired(_lView, notifyErrorHandler, useGlobalCheck, this.zonelessEnabled);
  23409. }
  23410. // If `markForCheck()` was called during view checking, it will have set the `ViewTreeCheck`
  23411. // flag. We clear the flag here because, for backwards compatibility, `markForCheck()`
  23412. // during view checking doesn't cause the view to be re-checked.
  23413. this.dirtyFlags &= -5 /* ApplicationRefDirtyFlags.ViewTreeCheck */;
  23414. // Check if any views are still dirty after checking and we need to loop back.
  23415. this.syncDirtyFlagsWithViews();
  23416. if (this.dirtyFlags &
  23417. (7 /* ApplicationRefDirtyFlags.ViewTreeAny */ | 16 /* ApplicationRefDirtyFlags.RootEffects */)) {
  23418. // If any views or effects are still dirty after checking, loop back before running render
  23419. // hooks.
  23420. return;
  23421. }
  23422. }
  23423. else {
  23424. // If we skipped refreshing views above, there might still be unflushed animations
  23425. // because we never called `detectChangesInternal` on the views.
  23426. this._rendererFactory?.begin?.();
  23427. this._rendererFactory?.end?.();
  23428. }
  23429. // Even if there were no dirty views, afterRender hooks might still be dirty.
  23430. if (this.dirtyFlags & 8 /* ApplicationRefDirtyFlags.AfterRender */) {
  23431. this.dirtyFlags &= -9 /* ApplicationRefDirtyFlags.AfterRender */;
  23432. this.afterRenderManager.execute();
  23433. // afterRender hooks might influence dirty flags.
  23434. }
  23435. this.syncDirtyFlagsWithViews();
  23436. }
  23437. /**
  23438. * Checks `allViews` for views which require refresh/traversal, and updates `dirtyFlags`
  23439. * accordingly, with two potential behaviors:
  23440. *
  23441. * 1. If any of our views require updating, then this adds the `ViewTreeTraversal` dirty flag.
  23442. * This _should_ be a no-op, since the scheduler should've added the flag at the same time the
  23443. * view was marked as needing updating.
  23444. *
  23445. * TODO(alxhub): figure out if this behavior is still needed for edge cases.
  23446. *
  23447. * 2. If none of our views require updating, then clear the view-related `dirtyFlag`s. This
  23448. * happens when the scheduler is notified of a view becoming dirty, but the view itself isn't
  23449. * reachable through traversal from our roots (e.g. it's detached from the CD tree).
  23450. */
  23451. syncDirtyFlagsWithViews() {
  23452. if (this.allViews.some(({ _lView }) => requiresRefreshOrTraversal(_lView))) {
  23453. // If after running all afterRender callbacks new views are dirty, ensure we loop back.
  23454. this.dirtyFlags |= 2 /* ApplicationRefDirtyFlags.ViewTreeTraversal */;
  23455. return;
  23456. }
  23457. else {
  23458. // Even though this flag may be set, none of _our_ views require traversal, and so the
  23459. // `ApplicationRef` doesn't require any repeated checking.
  23460. this.dirtyFlags &= -8 /* ApplicationRefDirtyFlags.ViewTreeAny */;
  23461. }
  23462. }
  23463. /**
  23464. * Attaches a view so that it will be dirty checked.
  23465. * The view will be automatically detached when it is destroyed.
  23466. * This will throw if the view is already attached to a ViewContainer.
  23467. */
  23468. attachView(viewRef) {
  23469. (typeof ngDevMode === 'undefined' || ngDevMode) && warnIfDestroyed(this._destroyed);
  23470. const view = viewRef;
  23471. this._views.push(view);
  23472. view.attachToAppRef(this);
  23473. }
  23474. /**
  23475. * Detaches a view from dirty checking again.
  23476. */
  23477. detachView(viewRef) {
  23478. (typeof ngDevMode === 'undefined' || ngDevMode) && warnIfDestroyed(this._destroyed);
  23479. const view = viewRef;
  23480. remove(this._views, view);
  23481. view.detachFromAppRef();
  23482. }
  23483. _loadComponent(componentRef) {
  23484. this.attachView(componentRef.hostView);
  23485. this.tick();
  23486. this.components.push(componentRef);
  23487. // Get the listeners lazily to prevent DI cycles.
  23488. const listeners = this._injector.get(APP_BOOTSTRAP_LISTENER, []);
  23489. if (ngDevMode && !Array.isArray(listeners)) {
  23490. throw new RuntimeError(-209 /* RuntimeErrorCode.INVALID_MULTI_PROVIDER */, 'Unexpected type of the `APP_BOOTSTRAP_LISTENER` token value ' +
  23491. `(expected an array, but got ${typeof listeners}). ` +
  23492. 'Please check that the `APP_BOOTSTRAP_LISTENER` token is configured as a ' +
  23493. '`multi: true` provider.');
  23494. }
  23495. listeners.forEach((listener) => listener(componentRef));
  23496. }
  23497. /** @internal */
  23498. ngOnDestroy() {
  23499. if (this._destroyed)
  23500. return;
  23501. try {
  23502. // Call all the lifecycle hooks.
  23503. this._destroyListeners.forEach((listener) => listener());
  23504. // Destroy all registered views.
  23505. this._views.slice().forEach((view) => view.destroy());
  23506. }
  23507. finally {
  23508. // Indicate that this instance is destroyed.
  23509. this._destroyed = true;
  23510. // Release all references.
  23511. this._views = [];
  23512. this._destroyListeners = [];
  23513. }
  23514. }
  23515. /**
  23516. * Registers a listener to be called when an instance is destroyed.
  23517. *
  23518. * @param callback A callback function to add as a listener.
  23519. * @returns A function which unregisters a listener.
  23520. */
  23521. onDestroy(callback) {
  23522. (typeof ngDevMode === 'undefined' || ngDevMode) && warnIfDestroyed(this._destroyed);
  23523. this._destroyListeners.push(callback);
  23524. return () => remove(this._destroyListeners, callback);
  23525. }
  23526. /**
  23527. * Destroys an Angular application represented by this `ApplicationRef`. Calling this function
  23528. * will destroy the associated environment injectors as well as all the bootstrapped components
  23529. * with their views.
  23530. */
  23531. destroy() {
  23532. if (this._destroyed) {
  23533. throw new RuntimeError(406 /* RuntimeErrorCode.APPLICATION_REF_ALREADY_DESTROYED */, ngDevMode && 'This instance of the `ApplicationRef` has already been destroyed.');
  23534. }
  23535. const injector = this._injector;
  23536. // Check that this injector instance supports destroy operation.
  23537. if (injector.destroy && !injector.destroyed) {
  23538. // Destroying an underlying injector will trigger the `ngOnDestroy` lifecycle
  23539. // hook, which invokes the remaining cleanup actions.
  23540. injector.destroy();
  23541. }
  23542. }
  23543. /**
  23544. * Returns the number of attached views.
  23545. */
  23546. get viewCount() {
  23547. return this._views.length;
  23548. }
  23549. static ɵfac = function ApplicationRef_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || ApplicationRef)(); };
  23550. static ɵprov = /*@__PURE__*/ ɵɵdefineInjectable({ token: ApplicationRef, factory: ApplicationRef.ɵfac, providedIn: 'root' });
  23551. }
  23552. (() => { (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(ApplicationRef, [{
  23553. type: Injectable,
  23554. args: [{ providedIn: 'root' }]
  23555. }], () => [], null); })();
  23556. function warnIfDestroyed(destroyed) {
  23557. if (destroyed) {
  23558. console.warn(formatRuntimeError(406 /* RuntimeErrorCode.APPLICATION_REF_ALREADY_DESTROYED */, 'This instance of the `ApplicationRef` has already been destroyed.'));
  23559. }
  23560. }
  23561. function remove(list, el) {
  23562. const index = list.indexOf(el);
  23563. if (index > -1) {
  23564. list.splice(index, 1);
  23565. }
  23566. }
  23567. function detectChangesInViewIfRequired(lView, notifyErrorHandler, isFirstPass, zonelessEnabled) {
  23568. // When re-checking, only check views which actually need it.
  23569. if (!isFirstPass && !requiresRefreshOrTraversal(lView)) {
  23570. return;
  23571. }
  23572. const mode = isFirstPass && !zonelessEnabled
  23573. ? // The first pass is always in Global mode, which includes `CheckAlways` views.
  23574. 0 /* ChangeDetectionMode.Global */
  23575. : // Only refresh views with the `RefreshView` flag or views is a changed signal
  23576. 1 /* ChangeDetectionMode.Targeted */;
  23577. detectChangesInternal(lView, notifyErrorHandler, mode);
  23578. }
  23579. /**
  23580. * Schedules triggering of a defer block for `on idle` and `on timer` conditions.
  23581. */
  23582. function scheduleDelayedTrigger(scheduleFn) {
  23583. const lView = getLView();
  23584. const tNode = getCurrentTNode();
  23585. renderPlaceholder(lView, tNode);
  23586. // Exit early to avoid invoking `scheduleFn`, which would
  23587. // add `setTimeout` call and potentially delay serialization
  23588. // on the server unnecessarily.
  23589. if (!shouldTriggerDeferBlock(0 /* TriggerType.Regular */, lView))
  23590. return;
  23591. const injector = lView[INJECTOR];
  23592. const lDetails = getLDeferBlockDetails(lView, tNode);
  23593. const cleanupFn = scheduleFn(() => triggerDeferBlock(0 /* TriggerType.Regular */, lView, tNode), injector);
  23594. storeTriggerCleanupFn(0 /* TriggerType.Regular */, lDetails, cleanupFn);
  23595. }
  23596. /**
  23597. * Schedules prefetching for `on idle` and `on timer` triggers.
  23598. *
  23599. * @param scheduleFn A function that does the scheduling.
  23600. */
  23601. function scheduleDelayedPrefetching(scheduleFn, trigger) {
  23602. if (typeof ngServerMode !== 'undefined' && ngServerMode)
  23603. return;
  23604. const lView = getLView();
  23605. const injector = lView[INJECTOR];
  23606. // Only trigger the scheduled trigger on the browser
  23607. // since we don't want to delay the server response.
  23608. const tNode = getCurrentTNode();
  23609. const tView = lView[TVIEW];
  23610. const tDetails = getTDeferBlockDetails(tView, tNode);
  23611. if (tDetails.loadingState === DeferDependenciesLoadingState.NOT_STARTED) {
  23612. const lDetails = getLDeferBlockDetails(lView, tNode);
  23613. const prefetch = () => triggerPrefetching(tDetails, lView, tNode);
  23614. const cleanupFn = scheduleFn(prefetch, injector);
  23615. storeTriggerCleanupFn(1 /* TriggerType.Prefetch */, lDetails, cleanupFn);
  23616. }
  23617. }
  23618. /**
  23619. * Schedules hydration triggering of a defer block for `on idle` and `on timer` conditions.
  23620. */
  23621. function scheduleDelayedHydrating(scheduleFn, lView, tNode) {
  23622. if (typeof ngServerMode !== 'undefined' && ngServerMode)
  23623. return;
  23624. // Only trigger the scheduled trigger on the browser
  23625. // since we don't want to delay the server response.
  23626. const injector = lView[INJECTOR];
  23627. const lDetails = getLDeferBlockDetails(lView, tNode);
  23628. const ssrUniqueId = lDetails[SSR_UNIQUE_ID];
  23629. ngDevMode && assertSsrIdDefined(ssrUniqueId);
  23630. const cleanupFn = scheduleFn(() => triggerHydrationFromBlockName(injector, ssrUniqueId), injector);
  23631. storeTriggerCleanupFn(2 /* TriggerType.Hydrate */, lDetails, cleanupFn);
  23632. }
  23633. /**
  23634. * Trigger prefetching of dependencies for a defer block.
  23635. *
  23636. * @param tDetails Static information about this defer block.
  23637. * @param lView LView of a host view.
  23638. * @param tNode TNode that represents a defer block.
  23639. */
  23640. function triggerPrefetching(tDetails, lView, tNode) {
  23641. triggerResourceLoading(tDetails, lView, tNode);
  23642. }
  23643. /**
  23644. * Trigger loading of defer block dependencies if the process hasn't started yet.
  23645. *
  23646. * @param tDetails Static information about this defer block.
  23647. * @param lView LView of a host view.
  23648. */
  23649. function triggerResourceLoading(tDetails, lView, tNode) {
  23650. const injector = lView[INJECTOR];
  23651. const tView = lView[TVIEW];
  23652. if (tDetails.loadingState !== DeferDependenciesLoadingState.NOT_STARTED) {
  23653. // If the loading status is different from initial one, it means that
  23654. // the loading of dependencies is in progress and there is nothing to do
  23655. // in this function. All details can be obtained from the `tDetails` object.
  23656. return tDetails.loadingPromise ?? Promise.resolve();
  23657. }
  23658. const lDetails = getLDeferBlockDetails(lView, tNode);
  23659. const primaryBlockTNode = getPrimaryBlockTNode(tView, tDetails);
  23660. // Switch from NOT_STARTED -> IN_PROGRESS state.
  23661. tDetails.loadingState = DeferDependenciesLoadingState.IN_PROGRESS;
  23662. // Prefetching is triggered, cleanup all registered prefetch triggers.
  23663. invokeTriggerCleanupFns(1 /* TriggerType.Prefetch */, lDetails);
  23664. let dependenciesFn = tDetails.dependencyResolverFn;
  23665. if (ngDevMode) {
  23666. // Check if dependency function interceptor is configured.
  23667. const deferDependencyInterceptor = injector.get(DEFER_BLOCK_DEPENDENCY_INTERCEPTOR, null, {
  23668. optional: true,
  23669. });
  23670. if (deferDependencyInterceptor) {
  23671. dependenciesFn = deferDependencyInterceptor.intercept(dependenciesFn);
  23672. }
  23673. }
  23674. // Indicate that an application is not stable and has a pending task.
  23675. const pendingTasks = injector.get(PendingTasksInternal);
  23676. const taskId = pendingTasks.add();
  23677. // The `dependenciesFn` might be `null` when all dependencies within
  23678. // a given defer block were eagerly referenced elsewhere in a file,
  23679. // thus no dynamic `import()`s were produced.
  23680. if (!dependenciesFn) {
  23681. tDetails.loadingPromise = Promise.resolve().then(() => {
  23682. tDetails.loadingPromise = null;
  23683. tDetails.loadingState = DeferDependenciesLoadingState.COMPLETE;
  23684. pendingTasks.remove(taskId);
  23685. });
  23686. return tDetails.loadingPromise;
  23687. }
  23688. // Start downloading of defer block dependencies.
  23689. tDetails.loadingPromise = Promise.allSettled(dependenciesFn()).then((results) => {
  23690. let failed = false;
  23691. const directiveDefs = [];
  23692. const pipeDefs = [];
  23693. for (const result of results) {
  23694. if (result.status === 'fulfilled') {
  23695. const dependency = result.value;
  23696. const directiveDef = getComponentDef(dependency) || getDirectiveDef(dependency);
  23697. if (directiveDef) {
  23698. directiveDefs.push(directiveDef);
  23699. }
  23700. else {
  23701. const pipeDef = getPipeDef$1(dependency);
  23702. if (pipeDef) {
  23703. pipeDefs.push(pipeDef);
  23704. }
  23705. }
  23706. }
  23707. else {
  23708. failed = true;
  23709. break;
  23710. }
  23711. }
  23712. // Loading is completed, we no longer need the loading Promise
  23713. // and a pending task should also be removed.
  23714. tDetails.loadingPromise = null;
  23715. pendingTasks.remove(taskId);
  23716. if (failed) {
  23717. tDetails.loadingState = DeferDependenciesLoadingState.FAILED;
  23718. if (tDetails.errorTmplIndex === null) {
  23719. const templateLocation = ngDevMode ? getTemplateLocationDetails(lView) : '';
  23720. const error = new RuntimeError(-750 /* RuntimeErrorCode.DEFER_LOADING_FAILED */, ngDevMode &&
  23721. 'Loading dependencies for `@defer` block failed, ' +
  23722. `but no \`@error\` block was configured${templateLocation}. ` +
  23723. 'Consider using the `@error` block to render an error state.');
  23724. handleError$1(lView, error);
  23725. }
  23726. }
  23727. else {
  23728. tDetails.loadingState = DeferDependenciesLoadingState.COMPLETE;
  23729. // Update directive and pipe registries to add newly downloaded dependencies.
  23730. const primaryBlockTView = primaryBlockTNode.tView;
  23731. if (directiveDefs.length > 0) {
  23732. primaryBlockTView.directiveRegistry = addDepsToRegistry(primaryBlockTView.directiveRegistry, directiveDefs);
  23733. // Extract providers from all NgModules imported by standalone components
  23734. // used within this defer block.
  23735. const directiveTypes = directiveDefs.map((def) => def.type);
  23736. const providers = internalImportProvidersFrom(false, ...directiveTypes);
  23737. tDetails.providers = providers;
  23738. }
  23739. if (pipeDefs.length > 0) {
  23740. primaryBlockTView.pipeRegistry = addDepsToRegistry(primaryBlockTView.pipeRegistry, pipeDefs);
  23741. }
  23742. }
  23743. });
  23744. return tDetails.loadingPromise;
  23745. }
  23746. /**
  23747. * Defines whether we should proceed with triggering a given defer block.
  23748. */
  23749. function shouldTriggerDeferBlock(triggerType, lView) {
  23750. // prevents triggering regular triggers when on the server.
  23751. if (triggerType === 0 /* TriggerType.Regular */ && typeof ngServerMode !== 'undefined' && ngServerMode) {
  23752. return false;
  23753. }
  23754. // prevents triggering in the case of a test run with manual defer block configuration.
  23755. const injector = lView[INJECTOR];
  23756. const config = injector.get(DEFER_BLOCK_CONFIG, null, { optional: true });
  23757. if (config?.behavior === DeferBlockBehavior.Manual) {
  23758. return false;
  23759. }
  23760. return true;
  23761. }
  23762. /**
  23763. * Attempts to trigger loading of defer block dependencies.
  23764. * If the block is already in a loading, completed or an error state -
  23765. * no additional actions are taken.
  23766. */
  23767. function triggerDeferBlock(triggerType, lView, tNode) {
  23768. const tView = lView[TVIEW];
  23769. const lContainer = lView[tNode.index];
  23770. ngDevMode && assertLContainer(lContainer);
  23771. if (!shouldTriggerDeferBlock(triggerType, lView))
  23772. return;
  23773. const lDetails = getLDeferBlockDetails(lView, tNode);
  23774. const tDetails = getTDeferBlockDetails(tView, tNode);
  23775. // Defer block is triggered, cleanup all registered trigger functions.
  23776. invokeAllTriggerCleanupFns(lDetails);
  23777. switch (tDetails.loadingState) {
  23778. case DeferDependenciesLoadingState.NOT_STARTED:
  23779. renderDeferBlockState(DeferBlockState.Loading, tNode, lContainer);
  23780. triggerResourceLoading(tDetails, lView, tNode);
  23781. // The `loadingState` might have changed to "loading".
  23782. if (tDetails.loadingState ===
  23783. DeferDependenciesLoadingState.IN_PROGRESS) {
  23784. renderDeferStateAfterResourceLoading(tDetails, tNode, lContainer);
  23785. }
  23786. break;
  23787. case DeferDependenciesLoadingState.IN_PROGRESS:
  23788. renderDeferBlockState(DeferBlockState.Loading, tNode, lContainer);
  23789. renderDeferStateAfterResourceLoading(tDetails, tNode, lContainer);
  23790. break;
  23791. case DeferDependenciesLoadingState.COMPLETE:
  23792. ngDevMode && assertDeferredDependenciesLoaded(tDetails);
  23793. renderDeferBlockState(DeferBlockState.Complete, tNode, lContainer);
  23794. break;
  23795. case DeferDependenciesLoadingState.FAILED:
  23796. renderDeferBlockState(DeferBlockState.Error, tNode, lContainer);
  23797. break;
  23798. default:
  23799. if (ngDevMode) {
  23800. throwError('Unknown defer block state');
  23801. }
  23802. }
  23803. }
  23804. /**
  23805. * The core mechanism for incremental hydration. This triggers or
  23806. * queues hydration for all the blocks in the tree that need to be hydrated
  23807. * and keeps track of all those blocks that were hydrated along the way.
  23808. *
  23809. * Note: the `replayQueuedEventsFn` is only provided when hydration is invoked
  23810. * as a result of an event replay (via JsAction). When hydration is invoked from
  23811. * an instruction set (e.g. `deferOnImmediate`) - there is no need to replay any
  23812. * events.
  23813. */
  23814. async function triggerHydrationFromBlockName(injector, blockName, replayQueuedEventsFn) {
  23815. const dehydratedBlockRegistry = injector.get(DEHYDRATED_BLOCK_REGISTRY);
  23816. const blocksBeingHydrated = dehydratedBlockRegistry.hydrating;
  23817. // Make sure we don't hydrate/trigger the same thing multiple times
  23818. if (blocksBeingHydrated.has(blockName)) {
  23819. return;
  23820. }
  23821. // Trigger resource loading and hydration for the blocks in the queue in the order of highest block
  23822. // to lowest block. Once a block has finished resource loading, after next render fires after hydration
  23823. // finishes. The new block will have its defer instruction called and will be in the registry.
  23824. // Due to timing related to potential nested control flow, this has to be scheduled after the next render.
  23825. const { parentBlockPromise, hydrationQueue } = getParentBlockHydrationQueue(blockName, injector);
  23826. if (hydrationQueue.length === 0)
  23827. return;
  23828. // It's possible that the hydrationQueue topmost item is actually in the process of hydrating and has
  23829. // a promise already. In that case, we don't want to destroy that promise and queue it again.
  23830. if (parentBlockPromise !== null) {
  23831. hydrationQueue.shift();
  23832. }
  23833. // The hydrating map in the registry prevents re-triggering hydration for a block that's already in
  23834. // the hydration queue. Here we generate promises for each of the blocks about to be hydrated
  23835. populateHydratingStateForQueue(dehydratedBlockRegistry, hydrationQueue);
  23836. // We await this after populating the hydration state so we can prevent re-triggering hydration for
  23837. // the same blocks while this promise is being awaited.
  23838. if (parentBlockPromise !== null) {
  23839. await parentBlockPromise;
  23840. }
  23841. const topmostParentBlock = hydrationQueue[0];
  23842. if (dehydratedBlockRegistry.has(topmostParentBlock)) {
  23843. // the topmost parent block is already in the registry and we can proceed
  23844. // with hydration.
  23845. await triggerHydrationForBlockQueue(injector, hydrationQueue, replayQueuedEventsFn);
  23846. }
  23847. else {
  23848. // the topmost parent block is not yet in the registry, which may mean
  23849. // a lazy loaded route, a control flow branch was taken, a route has
  23850. // been navigated, etc. So we need to queue up the hydration process
  23851. // so that it can be finished after the top block has had its defer
  23852. // instruction executed.
  23853. dehydratedBlockRegistry.awaitParentBlock(topmostParentBlock, async () => await triggerHydrationForBlockQueue(injector, hydrationQueue, replayQueuedEventsFn));
  23854. }
  23855. }
  23856. /**
  23857. * The core mechanism for incremental hydration. This triggers
  23858. * hydration for all the blocks in the tree that need to be hydrated
  23859. * and keeps track of all those blocks that were hydrated along the way.
  23860. *
  23861. * Note: the `replayQueuedEventsFn` is only provided when hydration is invoked
  23862. * as a result of an event replay (via JsAction). When hydration is invoked from
  23863. * an instruction set (e.g. `deferOnImmediate`) - there is no need to replay any
  23864. * events.
  23865. */
  23866. async function triggerHydrationForBlockQueue(injector, hydrationQueue, replayQueuedEventsFn) {
  23867. const dehydratedBlockRegistry = injector.get(DEHYDRATED_BLOCK_REGISTRY);
  23868. const blocksBeingHydrated = dehydratedBlockRegistry.hydrating;
  23869. // Indicate that we have some pending async work.
  23870. const pendingTasks = injector.get(PendingTasksInternal);
  23871. const taskId = pendingTasks.add();
  23872. // Actually do the triggering and hydration of the queue of blocks
  23873. for (let blockQueueIdx = 0; blockQueueIdx < hydrationQueue.length; blockQueueIdx++) {
  23874. const dehydratedBlockId = hydrationQueue[blockQueueIdx];
  23875. const dehydratedDeferBlock = dehydratedBlockRegistry.get(dehydratedBlockId);
  23876. if (dehydratedDeferBlock != null) {
  23877. // trigger the block resources and await next render for hydration. This should result
  23878. // in the next block ɵɵdefer instruction being called and that block being added to the dehydrated registry.
  23879. await triggerResourceLoadingForHydration(dehydratedDeferBlock);
  23880. await nextRender(injector);
  23881. // if the content has changed since server rendering, we need to check for the expected block
  23882. // being in the registry or if errors occurred. In that case, we need to clean up the remaining expected
  23883. // content that won't be rendered or fetched.
  23884. if (deferBlockHasErrored(dehydratedDeferBlock)) {
  23885. // Either the expected block has not yet had its ɵɵdefer instruction called or the block errored out when fetching
  23886. // resources. In the former case, either we're hydrating too soon or the client and server differ. In both cases,
  23887. // we need to clean up child content and promises.
  23888. removeDehydratedViewList(dehydratedDeferBlock);
  23889. cleanupRemainingHydrationQueue(hydrationQueue.slice(blockQueueIdx), dehydratedBlockRegistry);
  23890. break;
  23891. }
  23892. // The defer block has not errored and we've finished fetching resources and rendering.
  23893. // At this point it is safe to resolve the hydration promise.
  23894. blocksBeingHydrated.get(dehydratedBlockId).resolve();
  23895. }
  23896. else {
  23897. // The expected block has not yet had its ɵɵdefer instruction called. This is likely due to content changing between
  23898. // client and server. We need to clean up the dehydrated DOM in the container since it no longer is valid.
  23899. cleanupParentContainer(blockQueueIdx, hydrationQueue, dehydratedBlockRegistry);
  23900. cleanupRemainingHydrationQueue(hydrationQueue.slice(blockQueueIdx), dehydratedBlockRegistry);
  23901. break;
  23902. }
  23903. }
  23904. const lastBlockName = hydrationQueue[hydrationQueue.length - 1];
  23905. // Await hydration completion for the last block.
  23906. await blocksBeingHydrated.get(lastBlockName)?.promise;
  23907. // All async work is done, remove the taskId from the registry.
  23908. pendingTasks.remove(taskId);
  23909. // Replay any queued events, if any exist and the replay operation was requested.
  23910. if (replayQueuedEventsFn) {
  23911. replayQueuedEventsFn(hydrationQueue);
  23912. }
  23913. // Cleanup after hydration of all affected defer blocks.
  23914. cleanupHydratedDeferBlocks(dehydratedBlockRegistry.get(lastBlockName), hydrationQueue, dehydratedBlockRegistry, injector.get(ApplicationRef));
  23915. }
  23916. function deferBlockHasErrored(deferBlock) {
  23917. return (getLDeferBlockDetails(deferBlock.lView, deferBlock.tNode)[DEFER_BLOCK_STATE] ===
  23918. DeferBlockState.Error);
  23919. }
  23920. /**
  23921. * Clean up the parent container of a block where content changed between server and client.
  23922. * The parent of a block going through `triggerHydrationFromBlockName` will contain the
  23923. * dehydrated content that needs to be cleaned up. So we have to do the clean up from that location
  23924. * in the tree.
  23925. */
  23926. function cleanupParentContainer(currentBlockIdx, hydrationQueue, dehydratedBlockRegistry) {
  23927. // If a parent block exists, it's in the hydration queue in front of the current block.
  23928. const parentDeferBlockIdx = currentBlockIdx - 1;
  23929. const parentDeferBlock = parentDeferBlockIdx > -1
  23930. ? dehydratedBlockRegistry.get(hydrationQueue[parentDeferBlockIdx])
  23931. : null;
  23932. if (parentDeferBlock) {
  23933. cleanupLContainer(parentDeferBlock.lContainer);
  23934. }
  23935. }
  23936. function cleanupRemainingHydrationQueue(hydrationQueue, dehydratedBlockRegistry) {
  23937. const blocksBeingHydrated = dehydratedBlockRegistry.hydrating;
  23938. for (const dehydratedBlockId in hydrationQueue) {
  23939. blocksBeingHydrated.get(dehydratedBlockId)?.reject();
  23940. }
  23941. dehydratedBlockRegistry.cleanup(hydrationQueue);
  23942. }
  23943. /**
  23944. * Generates a new promise for every defer block in the hydrating queue
  23945. */
  23946. function populateHydratingStateForQueue(registry, queue) {
  23947. for (let blockId of queue) {
  23948. registry.hydrating.set(blockId, Promise.withResolvers());
  23949. }
  23950. }
  23951. // Waits for the next render cycle to complete
  23952. function nextRender(injector) {
  23953. return new Promise((resolveFn) => afterNextRender(resolveFn, { injector }));
  23954. }
  23955. async function triggerResourceLoadingForHydration(dehydratedBlock) {
  23956. const { tNode, lView } = dehydratedBlock;
  23957. const lDetails = getLDeferBlockDetails(lView, tNode);
  23958. return new Promise((resolve) => {
  23959. onDeferBlockCompletion(lDetails, resolve);
  23960. triggerDeferBlock(2 /* TriggerType.Hydrate */, lView, tNode);
  23961. });
  23962. }
  23963. /**
  23964. * Registers cleanup functions for a defer block when the block has finished
  23965. * fetching and rendering
  23966. */
  23967. function onDeferBlockCompletion(lDetails, callback) {
  23968. if (!Array.isArray(lDetails[ON_COMPLETE_FNS])) {
  23969. lDetails[ON_COMPLETE_FNS] = [];
  23970. }
  23971. lDetails[ON_COMPLETE_FNS].push(callback);
  23972. }
  23973. /**
  23974. * Determines whether specific trigger types should be attached during an instruction firing
  23975. * to ensure the proper triggers for a given type are used.
  23976. */
  23977. function shouldAttachTrigger(triggerType, lView, tNode) {
  23978. if (triggerType === 0 /* TriggerType.Regular */) {
  23979. return shouldAttachRegularTrigger(lView, tNode);
  23980. }
  23981. else if (triggerType === 2 /* TriggerType.Hydrate */) {
  23982. return !shouldAttachRegularTrigger(lView, tNode);
  23983. }
  23984. // TriggerType.Prefetch is active only on the client
  23985. return !(typeof ngServerMode !== 'undefined' && ngServerMode);
  23986. }
  23987. /**
  23988. * Defines whether a regular trigger logic (e.g. "on viewport") should be attached
  23989. * to a defer block. This function defines a condition, which mutually excludes
  23990. * `deferOn*` and `deferHydrateOn*` triggers, to make sure only one of the trigger
  23991. * types is active for a block with the current state.
  23992. */
  23993. function shouldAttachRegularTrigger(lView, tNode) {
  23994. const injector = lView[INJECTOR];
  23995. const tDetails = getTDeferBlockDetails(lView[TVIEW], tNode);
  23996. const incrementalHydrationEnabled = isIncrementalHydrationEnabled(injector);
  23997. const hasHydrateTriggers = tDetails.flags !== null &&
  23998. (tDetails.flags & 1 /* TDeferDetailsFlags.HasHydrateTriggers */) ===
  23999. 1 /* TDeferDetailsFlags.HasHydrateTriggers */;
  24000. // On the server:
  24001. if (typeof ngServerMode !== 'undefined' && ngServerMode) {
  24002. // Regular triggers are activated on the server when:
  24003. // - Either Incremental Hydration is *not* enabled
  24004. // - Or Incremental Hydration is enabled, but a given block doesn't have "hydrate" triggers
  24005. return !incrementalHydrationEnabled || !hasHydrateTriggers;
  24006. }
  24007. // On the client:
  24008. const lDetails = getLDeferBlockDetails(lView, tNode);
  24009. const wasServerSideRendered = lDetails[SSR_UNIQUE_ID] !== null;
  24010. if (hasHydrateTriggers && wasServerSideRendered && incrementalHydrationEnabled) {
  24011. return false;
  24012. }
  24013. return true;
  24014. }
  24015. /**
  24016. * Retrives a Defer Block's list of hydration triggers
  24017. */
  24018. function getHydrateTriggers(tView, tNode) {
  24019. const tDetails = getTDeferBlockDetails(tView, tNode);
  24020. return (tDetails.hydrateTriggers ??= new Map());
  24021. }
  24022. /**
  24023. * Loops through all defer block summaries and ensures all the blocks triggers are
  24024. * properly initialized
  24025. */
  24026. function processAndInitTriggers(injector, blockData, nodes) {
  24027. const idleElements = [];
  24028. const timerElements = [];
  24029. const viewportElements = [];
  24030. const immediateElements = [];
  24031. for (let [blockId, blockSummary] of blockData) {
  24032. const commentNode = nodes.get(blockId);
  24033. if (commentNode !== undefined) {
  24034. const numRootNodes = blockSummary.data[NUM_ROOT_NODES];
  24035. let currentNode = commentNode;
  24036. for (let i = 0; i < numRootNodes; i++) {
  24037. currentNode = currentNode.previousSibling;
  24038. if (currentNode.nodeType !== Node.ELEMENT_NODE) {
  24039. continue;
  24040. }
  24041. const elementTrigger = { el: currentNode, blockName: blockId };
  24042. // hydrate
  24043. if (blockSummary.hydrate.idle) {
  24044. idleElements.push(elementTrigger);
  24045. }
  24046. if (blockSummary.hydrate.immediate) {
  24047. immediateElements.push(elementTrigger);
  24048. }
  24049. if (blockSummary.hydrate.timer !== null) {
  24050. elementTrigger.delay = blockSummary.hydrate.timer;
  24051. timerElements.push(elementTrigger);
  24052. }
  24053. if (blockSummary.hydrate.viewport) {
  24054. viewportElements.push(elementTrigger);
  24055. }
  24056. }
  24057. }
  24058. }
  24059. setIdleTriggers(injector, idleElements);
  24060. setImmediateTriggers(injector, immediateElements);
  24061. setViewportTriggers(injector, viewportElements);
  24062. setTimerTriggers(injector, timerElements);
  24063. }
  24064. function setIdleTriggers(injector, elementTriggers) {
  24065. for (const elementTrigger of elementTriggers) {
  24066. const registry = injector.get(DEHYDRATED_BLOCK_REGISTRY);
  24067. const onInvoke = () => triggerHydrationFromBlockName(injector, elementTrigger.blockName);
  24068. const cleanupFn = onIdle(onInvoke, injector);
  24069. registry.addCleanupFn(elementTrigger.blockName, cleanupFn);
  24070. }
  24071. }
  24072. function setViewportTriggers(injector, elementTriggers) {
  24073. if (elementTriggers.length > 0) {
  24074. const registry = injector.get(DEHYDRATED_BLOCK_REGISTRY);
  24075. for (let elementTrigger of elementTriggers) {
  24076. const cleanupFn = onViewport(elementTrigger.el, () => triggerHydrationFromBlockName(injector, elementTrigger.blockName), injector);
  24077. registry.addCleanupFn(elementTrigger.blockName, cleanupFn);
  24078. }
  24079. }
  24080. }
  24081. function setTimerTriggers(injector, elementTriggers) {
  24082. for (const elementTrigger of elementTriggers) {
  24083. const registry = injector.get(DEHYDRATED_BLOCK_REGISTRY);
  24084. const onInvoke = () => triggerHydrationFromBlockName(injector, elementTrigger.blockName);
  24085. const timerFn = onTimer(elementTrigger.delay);
  24086. const cleanupFn = timerFn(onInvoke, injector);
  24087. registry.addCleanupFn(elementTrigger.blockName, cleanupFn);
  24088. }
  24089. }
  24090. function setImmediateTriggers(injector, elementTriggers) {
  24091. for (const elementTrigger of elementTriggers) {
  24092. // Note: we intentionally avoid awaiting each call and instead kick off
  24093. // the hydration process simultaneously for all defer blocks with this trigger;
  24094. triggerHydrationFromBlockName(injector, elementTrigger.blockName);
  24095. }
  24096. }
  24097. /**
  24098. * Creates runtime data structures for defer blocks.
  24099. *
  24100. * @param index Index of the `defer` instruction.
  24101. * @param primaryTmplIndex Index of the template with the primary block content.
  24102. * @param dependencyResolverFn Function that contains dependencies for this defer block.
  24103. * @param loadingTmplIndex Index of the template with the loading block content.
  24104. * @param placeholderTmplIndex Index of the template with the placeholder block content.
  24105. * @param errorTmplIndex Index of the template with the error block content.
  24106. * @param loadingConfigIndex Index in the constants array of the configuration of the loading.
  24107. * block.
  24108. * @param placeholderConfigIndex Index in the constants array of the configuration of the
  24109. * placeholder block.
  24110. * @param enableTimerScheduling Function that enables timer-related scheduling if `after`
  24111. * or `minimum` parameters are setup on the `@loading` or `@placeholder` blocks.
  24112. * @param flags A set of flags to define a particular behavior (e.g. to indicate that
  24113. * hydrate triggers are present and regular triggers should be deactivated
  24114. * in certain scenarios).
  24115. *
  24116. * @codeGenApi
  24117. */
  24118. function ɵɵdefer(index, primaryTmplIndex, dependencyResolverFn, loadingTmplIndex, placeholderTmplIndex, errorTmplIndex, loadingConfigIndex, placeholderConfigIndex, enableTimerScheduling, flags) {
  24119. const lView = getLView();
  24120. const tView = getTView();
  24121. const adjustedIndex = index + HEADER_OFFSET;
  24122. const tNode = declareTemplate(lView, tView, index, null, 0, 0);
  24123. const injector = lView[INJECTOR];
  24124. if (tView.firstCreatePass) {
  24125. performanceMarkFeature('NgDefer');
  24126. const tDetails = {
  24127. primaryTmplIndex,
  24128. loadingTmplIndex: loadingTmplIndex ?? null,
  24129. placeholderTmplIndex: placeholderTmplIndex ?? null,
  24130. errorTmplIndex: errorTmplIndex ?? null,
  24131. placeholderBlockConfig: null,
  24132. loadingBlockConfig: null,
  24133. dependencyResolverFn: dependencyResolverFn ?? null,
  24134. loadingState: DeferDependenciesLoadingState.NOT_STARTED,
  24135. loadingPromise: null,
  24136. providers: null,
  24137. hydrateTriggers: null,
  24138. debug: null,
  24139. flags: flags ?? 0 /* TDeferDetailsFlags.Default */,
  24140. };
  24141. enableTimerScheduling?.(tView, tDetails, placeholderConfigIndex, loadingConfigIndex);
  24142. setTDeferBlockDetails(tView, adjustedIndex, tDetails);
  24143. }
  24144. const lContainer = lView[adjustedIndex];
  24145. // If hydration is enabled, looks up dehydrated views in the DOM
  24146. // using hydration annotation info and stores those views on LContainer.
  24147. // In client-only mode, this function is a noop.
  24148. populateDehydratedViewsInLContainer(lContainer, tNode, lView);
  24149. let ssrBlockState = null;
  24150. let ssrUniqueId = null;
  24151. if (lContainer[DEHYDRATED_VIEWS]?.length > 0) {
  24152. const info = lContainer[DEHYDRATED_VIEWS][0].data;
  24153. ssrUniqueId = info[DEFER_BLOCK_ID] ?? null;
  24154. ssrBlockState = info[DEFER_BLOCK_STATE$1];
  24155. }
  24156. // Init instance-specific defer details and store it.
  24157. const lDetails = [
  24158. null, // NEXT_DEFER_BLOCK_STATE
  24159. DeferBlockInternalState.Initial, // DEFER_BLOCK_STATE
  24160. null, // STATE_IS_FROZEN_UNTIL
  24161. null, // LOADING_AFTER_CLEANUP_FN
  24162. null, // TRIGGER_CLEANUP_FNS
  24163. null, // PREFETCH_TRIGGER_CLEANUP_FNS
  24164. ssrUniqueId, // SSR_UNIQUE_ID
  24165. ssrBlockState, // SSR_BLOCK_STATE
  24166. null, // ON_COMPLETE_FNS
  24167. null, // HYDRATE_TRIGGER_CLEANUP_FNS
  24168. ];
  24169. setLDeferBlockDetails(lView, adjustedIndex, lDetails);
  24170. let registry = null;
  24171. if (ssrUniqueId !== null) {
  24172. ngDevMode && assertIncrementalHydrationIsConfigured(injector);
  24173. // Store this defer block in the registry, to have an access to
  24174. // internal data structures from hydration runtime code.
  24175. registry = injector.get(DEHYDRATED_BLOCK_REGISTRY);
  24176. registry.add(ssrUniqueId, { lView, tNode, lContainer });
  24177. }
  24178. const onLViewDestroy = () => {
  24179. invokeAllTriggerCleanupFns(lDetails);
  24180. if (ssrUniqueId !== null) {
  24181. registry?.cleanup([ssrUniqueId]);
  24182. }
  24183. };
  24184. // When defer block is triggered - unsubscribe from LView destroy cleanup.
  24185. storeTriggerCleanupFn(0 /* TriggerType.Regular */, lDetails, () => removeLViewOnDestroy(lView, onLViewDestroy));
  24186. storeLViewOnDestroy(lView, onLViewDestroy);
  24187. }
  24188. /**
  24189. * Loads defer block dependencies when a trigger value becomes truthy.
  24190. * @codeGenApi
  24191. */
  24192. function ɵɵdeferWhen(rawValue) {
  24193. const lView = getLView();
  24194. const tNode = getSelectedTNode();
  24195. if (ngDevMode) {
  24196. trackTriggerForDebugging(lView[TVIEW], tNode, 'when <expression>');
  24197. }
  24198. if (!shouldAttachTrigger(0 /* TriggerType.Regular */, lView, tNode))
  24199. return;
  24200. const bindingIndex = nextBindingIndex();
  24201. if (bindingUpdated(lView, bindingIndex, rawValue)) {
  24202. const prevConsumer = setActiveConsumer$1(null);
  24203. try {
  24204. const value = Boolean(rawValue); // handle truthy or falsy values
  24205. const lDetails = getLDeferBlockDetails(lView, tNode);
  24206. const renderedState = lDetails[DEFER_BLOCK_STATE];
  24207. if (value === false && renderedState === DeferBlockInternalState.Initial) {
  24208. // If nothing is rendered yet, render a placeholder (if defined).
  24209. renderPlaceholder(lView, tNode);
  24210. }
  24211. else if (value === true &&
  24212. (renderedState === DeferBlockInternalState.Initial ||
  24213. renderedState === DeferBlockState.Placeholder)) {
  24214. triggerDeferBlock(0 /* TriggerType.Regular */, lView, tNode);
  24215. }
  24216. }
  24217. finally {
  24218. setActiveConsumer$1(prevConsumer);
  24219. }
  24220. }
  24221. }
  24222. /**
  24223. * Prefetches the deferred content when a value becomes truthy.
  24224. * @codeGenApi
  24225. */
  24226. function ɵɵdeferPrefetchWhen(rawValue) {
  24227. const lView = getLView();
  24228. const tNode = getSelectedTNode();
  24229. if (ngDevMode) {
  24230. trackTriggerForDebugging(lView[TVIEW], tNode, 'prefetch when <expression>');
  24231. }
  24232. if (!shouldAttachTrigger(1 /* TriggerType.Prefetch */, lView, tNode))
  24233. return;
  24234. const bindingIndex = nextBindingIndex();
  24235. if (bindingUpdated(lView, bindingIndex, rawValue)) {
  24236. const prevConsumer = setActiveConsumer$1(null);
  24237. try {
  24238. const value = Boolean(rawValue); // handle truthy or falsy values
  24239. const tView = lView[TVIEW];
  24240. const tNode = getSelectedTNode();
  24241. const tDetails = getTDeferBlockDetails(tView, tNode);
  24242. if (value === true && tDetails.loadingState === DeferDependenciesLoadingState.NOT_STARTED) {
  24243. // If loading has not been started yet, trigger it now.
  24244. triggerPrefetching(tDetails, lView, tNode);
  24245. }
  24246. }
  24247. finally {
  24248. setActiveConsumer$1(prevConsumer);
  24249. }
  24250. }
  24251. }
  24252. /**
  24253. * Hydrates the deferred content when a value becomes truthy.
  24254. * @codeGenApi
  24255. */
  24256. function ɵɵdeferHydrateWhen(rawValue) {
  24257. const lView = getLView();
  24258. const tNode = getSelectedTNode();
  24259. if (ngDevMode) {
  24260. trackTriggerForDebugging(lView[TVIEW], tNode, 'hydrate when <expression>');
  24261. }
  24262. if (!shouldAttachTrigger(2 /* TriggerType.Hydrate */, lView, tNode))
  24263. return;
  24264. // TODO(incremental-hydration): audit all defer instructions to reduce unnecessary work by
  24265. // moving function calls inside their relevant control flow blocks
  24266. const bindingIndex = nextBindingIndex();
  24267. const tView = getTView();
  24268. const hydrateTriggers = getHydrateTriggers(tView, tNode);
  24269. hydrateTriggers.set(6 /* DeferBlockTrigger.When */, null);
  24270. if (bindingUpdated(lView, bindingIndex, rawValue)) {
  24271. if (typeof ngServerMode !== 'undefined' && ngServerMode) {
  24272. // We are on the server and SSR for defer blocks is enabled.
  24273. triggerDeferBlock(2 /* TriggerType.Hydrate */, lView, tNode);
  24274. }
  24275. else {
  24276. const injector = lView[INJECTOR];
  24277. const prevConsumer = setActiveConsumer$1(null);
  24278. try {
  24279. const value = Boolean(rawValue); // handle truthy or falsy values
  24280. if (value === true) {
  24281. // The `when` condition has changed to `true`, trigger defer block loading
  24282. // if the block is either in initial (nothing is rendered) or a placeholder
  24283. // state.
  24284. const lDetails = getLDeferBlockDetails(lView, tNode);
  24285. const ssrUniqueId = lDetails[SSR_UNIQUE_ID];
  24286. ngDevMode && assertSsrIdDefined(ssrUniqueId);
  24287. triggerHydrationFromBlockName(injector, ssrUniqueId);
  24288. }
  24289. }
  24290. finally {
  24291. setActiveConsumer$1(prevConsumer);
  24292. }
  24293. }
  24294. }
  24295. }
  24296. /**
  24297. * Specifies that hydration never occurs.
  24298. * @codeGenApi
  24299. */
  24300. function ɵɵdeferHydrateNever() {
  24301. const lView = getLView();
  24302. const tNode = getCurrentTNode();
  24303. if (ngDevMode) {
  24304. trackTriggerForDebugging(lView[TVIEW], tNode, 'hydrate never');
  24305. }
  24306. if (!shouldAttachTrigger(2 /* TriggerType.Hydrate */, lView, tNode))
  24307. return;
  24308. const hydrateTriggers = getHydrateTriggers(getTView(), tNode);
  24309. hydrateTriggers.set(7 /* DeferBlockTrigger.Never */, null);
  24310. if (typeof ngServerMode !== 'undefined' && ngServerMode) {
  24311. // We are on the server and SSR for defer blocks is enabled.
  24312. triggerDeferBlock(2 /* TriggerType.Hydrate */, lView, tNode);
  24313. }
  24314. }
  24315. /**
  24316. * Sets up logic to handle the `on idle` deferred trigger.
  24317. * @codeGenApi
  24318. */
  24319. function ɵɵdeferOnIdle() {
  24320. const lView = getLView();
  24321. const tNode = getCurrentTNode();
  24322. if (ngDevMode) {
  24323. trackTriggerForDebugging(lView[TVIEW], tNode, 'on idle');
  24324. }
  24325. if (!shouldAttachTrigger(0 /* TriggerType.Regular */, lView, tNode))
  24326. return;
  24327. scheduleDelayedTrigger(onIdle);
  24328. }
  24329. /**
  24330. * Sets up logic to handle the `prefetch on idle` deferred trigger.
  24331. * @codeGenApi
  24332. */
  24333. function ɵɵdeferPrefetchOnIdle() {
  24334. const lView = getLView();
  24335. const tNode = getCurrentTNode();
  24336. if (ngDevMode) {
  24337. trackTriggerForDebugging(lView[TVIEW], tNode, 'prefetch on idle');
  24338. }
  24339. if (!shouldAttachTrigger(1 /* TriggerType.Prefetch */, lView, tNode))
  24340. return;
  24341. scheduleDelayedPrefetching(onIdle);
  24342. }
  24343. /**
  24344. * Sets up logic to handle the `on idle` deferred trigger.
  24345. * @codeGenApi
  24346. */
  24347. function ɵɵdeferHydrateOnIdle() {
  24348. const lView = getLView();
  24349. const tNode = getCurrentTNode();
  24350. if (ngDevMode) {
  24351. trackTriggerForDebugging(lView[TVIEW], tNode, 'hydrate on idle');
  24352. }
  24353. if (!shouldAttachTrigger(2 /* TriggerType.Hydrate */, lView, tNode))
  24354. return;
  24355. const hydrateTriggers = getHydrateTriggers(getTView(), tNode);
  24356. hydrateTriggers.set(0 /* DeferBlockTrigger.Idle */, null);
  24357. if (typeof ngServerMode !== 'undefined' && ngServerMode) {
  24358. // We are on the server and SSR for defer blocks is enabled.
  24359. triggerDeferBlock(2 /* TriggerType.Hydrate */, lView, tNode);
  24360. }
  24361. else {
  24362. scheduleDelayedHydrating(onIdle, lView, tNode);
  24363. }
  24364. }
  24365. /**
  24366. * Sets up logic to handle the `on immediate` deferred trigger.
  24367. * @codeGenApi
  24368. */
  24369. function ɵɵdeferOnImmediate() {
  24370. const lView = getLView();
  24371. const tNode = getCurrentTNode();
  24372. if (ngDevMode) {
  24373. trackTriggerForDebugging(lView[TVIEW], tNode, 'on immediate');
  24374. }
  24375. if (!shouldAttachTrigger(0 /* TriggerType.Regular */, lView, tNode))
  24376. return;
  24377. // Render placeholder block only if loading template is not present and we're on
  24378. // the client to avoid content flickering, since it would be immediately replaced
  24379. // by the loading block.
  24380. const tDetails = getTDeferBlockDetails(lView[TVIEW], tNode);
  24381. if (tDetails.loadingTmplIndex === null) {
  24382. renderPlaceholder(lView, tNode);
  24383. }
  24384. triggerDeferBlock(0 /* TriggerType.Regular */, lView, tNode);
  24385. }
  24386. /**
  24387. * Sets up logic to handle the `prefetch on immediate` deferred trigger.
  24388. * @codeGenApi
  24389. */
  24390. function ɵɵdeferPrefetchOnImmediate() {
  24391. const lView = getLView();
  24392. const tNode = getCurrentTNode();
  24393. if (ngDevMode) {
  24394. trackTriggerForDebugging(lView[TVIEW], tNode, 'prefetch on immediate');
  24395. }
  24396. if (!shouldAttachTrigger(1 /* TriggerType.Prefetch */, lView, tNode))
  24397. return;
  24398. const tView = lView[TVIEW];
  24399. const tDetails = getTDeferBlockDetails(tView, tNode);
  24400. if (tDetails.loadingState === DeferDependenciesLoadingState.NOT_STARTED) {
  24401. triggerResourceLoading(tDetails, lView, tNode);
  24402. }
  24403. }
  24404. /**
  24405. * Sets up logic to handle the `on immediate` hydrate trigger.
  24406. * @codeGenApi
  24407. */
  24408. function ɵɵdeferHydrateOnImmediate() {
  24409. const lView = getLView();
  24410. const tNode = getCurrentTNode();
  24411. if (ngDevMode) {
  24412. trackTriggerForDebugging(lView[TVIEW], tNode, 'hydrate on immediate');
  24413. }
  24414. if (!shouldAttachTrigger(2 /* TriggerType.Hydrate */, lView, tNode))
  24415. return;
  24416. const hydrateTriggers = getHydrateTriggers(getTView(), tNode);
  24417. hydrateTriggers.set(1 /* DeferBlockTrigger.Immediate */, null);
  24418. if (typeof ngServerMode !== 'undefined' && ngServerMode) {
  24419. triggerDeferBlock(2 /* TriggerType.Hydrate */, lView, tNode);
  24420. }
  24421. else {
  24422. const injector = lView[INJECTOR];
  24423. const lDetails = getLDeferBlockDetails(lView, tNode);
  24424. const ssrUniqueId = lDetails[SSR_UNIQUE_ID];
  24425. ngDevMode && assertSsrIdDefined(ssrUniqueId);
  24426. triggerHydrationFromBlockName(injector, ssrUniqueId);
  24427. }
  24428. }
  24429. /**
  24430. * Creates runtime data structures for the `on timer` deferred trigger.
  24431. * @param delay Amount of time to wait before loading the content.
  24432. * @codeGenApi
  24433. */
  24434. function ɵɵdeferOnTimer(delay) {
  24435. const lView = getLView();
  24436. const tNode = getCurrentTNode();
  24437. if (ngDevMode) {
  24438. trackTriggerForDebugging(lView[TVIEW], tNode, `on timer(${delay}ms)`);
  24439. }
  24440. if (!shouldAttachTrigger(0 /* TriggerType.Regular */, lView, tNode))
  24441. return;
  24442. scheduleDelayedTrigger(onTimer(delay));
  24443. }
  24444. /**
  24445. * Creates runtime data structures for the `prefetch on timer` deferred trigger.
  24446. * @param delay Amount of time to wait before prefetching the content.
  24447. * @codeGenApi
  24448. */
  24449. function ɵɵdeferPrefetchOnTimer(delay) {
  24450. const lView = getLView();
  24451. const tNode = getCurrentTNode();
  24452. if (ngDevMode) {
  24453. trackTriggerForDebugging(lView[TVIEW], tNode, `prefetch on timer(${delay}ms)`);
  24454. }
  24455. if (!shouldAttachTrigger(1 /* TriggerType.Prefetch */, lView, tNode))
  24456. return;
  24457. scheduleDelayedPrefetching(onTimer(delay));
  24458. }
  24459. /**
  24460. * Creates runtime data structures for the `on timer` hydrate trigger.
  24461. * @param delay Amount of time to wait before loading the content.
  24462. * @codeGenApi
  24463. */
  24464. function ɵɵdeferHydrateOnTimer(delay) {
  24465. const lView = getLView();
  24466. const tNode = getCurrentTNode();
  24467. if (ngDevMode) {
  24468. trackTriggerForDebugging(lView[TVIEW], tNode, `hydrate on timer(${delay}ms)`);
  24469. }
  24470. if (!shouldAttachTrigger(2 /* TriggerType.Hydrate */, lView, tNode))
  24471. return;
  24472. const hydrateTriggers = getHydrateTriggers(getTView(), tNode);
  24473. hydrateTriggers.set(5 /* DeferBlockTrigger.Timer */, { delay });
  24474. if (typeof ngServerMode !== 'undefined' && ngServerMode) {
  24475. // We are on the server and SSR for defer blocks is enabled.
  24476. triggerDeferBlock(2 /* TriggerType.Hydrate */, lView, tNode);
  24477. }
  24478. else {
  24479. scheduleDelayedHydrating(onTimer(delay), lView, tNode);
  24480. }
  24481. }
  24482. /**
  24483. * Creates runtime data structures for the `on hover` deferred trigger.
  24484. * @param triggerIndex Index at which to find the trigger element.
  24485. * @param walkUpTimes Number of times to walk up/down the tree hierarchy to find the trigger.
  24486. * @codeGenApi
  24487. */
  24488. function ɵɵdeferOnHover(triggerIndex, walkUpTimes) {
  24489. const lView = getLView();
  24490. const tNode = getCurrentTNode();
  24491. if (ngDevMode) {
  24492. trackTriggerForDebugging(lView[TVIEW], tNode, `on hover${walkUpTimes === -1 ? '' : '(<target>)'}`);
  24493. }
  24494. if (!shouldAttachTrigger(0 /* TriggerType.Regular */, lView, tNode))
  24495. return;
  24496. renderPlaceholder(lView, tNode);
  24497. // Avoid adding event listeners when this instruction is invoked on the server.
  24498. if (!(typeof ngServerMode !== 'undefined' && ngServerMode)) {
  24499. registerDomTrigger(lView, tNode, triggerIndex, walkUpTimes, onHover, () => triggerDeferBlock(0 /* TriggerType.Regular */, lView, tNode), 0 /* TriggerType.Regular */);
  24500. }
  24501. }
  24502. /**
  24503. * Creates runtime data structures for the `prefetch on hover` deferred trigger.
  24504. * @param triggerIndex Index at which to find the trigger element.
  24505. * @param walkUpTimes Number of times to walk up/down the tree hierarchy to find the trigger.
  24506. * @codeGenApi
  24507. */
  24508. function ɵɵdeferPrefetchOnHover(triggerIndex, walkUpTimes) {
  24509. const lView = getLView();
  24510. const tNode = getCurrentTNode();
  24511. if (ngDevMode) {
  24512. trackTriggerForDebugging(lView[TVIEW], tNode, `prefetch on hover${walkUpTimes === -1 ? '' : '(<target>)'}`);
  24513. }
  24514. if (!shouldAttachTrigger(1 /* TriggerType.Prefetch */, lView, tNode))
  24515. return;
  24516. const tView = lView[TVIEW];
  24517. const tDetails = getTDeferBlockDetails(tView, tNode);
  24518. if (tDetails.loadingState === DeferDependenciesLoadingState.NOT_STARTED) {
  24519. registerDomTrigger(lView, tNode, triggerIndex, walkUpTimes, onHover, () => triggerPrefetching(tDetails, lView, tNode), 1 /* TriggerType.Prefetch */);
  24520. }
  24521. }
  24522. /**
  24523. * Creates runtime data structures for the `on hover` hydrate trigger.
  24524. * @codeGenApi
  24525. */
  24526. function ɵɵdeferHydrateOnHover() {
  24527. const lView = getLView();
  24528. const tNode = getCurrentTNode();
  24529. if (ngDevMode) {
  24530. trackTriggerForDebugging(lView[TVIEW], tNode, 'hydrate on hover');
  24531. }
  24532. if (!shouldAttachTrigger(2 /* TriggerType.Hydrate */, lView, tNode))
  24533. return;
  24534. const hydrateTriggers = getHydrateTriggers(getTView(), tNode);
  24535. hydrateTriggers.set(4 /* DeferBlockTrigger.Hover */, null);
  24536. if (typeof ngServerMode !== 'undefined' && ngServerMode) {
  24537. // We are on the server and SSR for defer blocks is enabled.
  24538. triggerDeferBlock(2 /* TriggerType.Hydrate */, lView, tNode);
  24539. }
  24540. // The actual triggering of hydration on hover is handled by JSAction in
  24541. // event_replay.ts.
  24542. }
  24543. /**
  24544. * Creates runtime data structures for the `on interaction` deferred trigger.
  24545. * @param triggerIndex Index at which to find the trigger element.
  24546. * @param walkUpTimes Number of times to walk up/down the tree hierarchy to find the trigger.
  24547. * @codeGenApi
  24548. */
  24549. function ɵɵdeferOnInteraction(triggerIndex, walkUpTimes) {
  24550. const lView = getLView();
  24551. const tNode = getCurrentTNode();
  24552. if (ngDevMode) {
  24553. trackTriggerForDebugging(lView[TVIEW], tNode, `on interaction${walkUpTimes === -1 ? '' : '(<target>)'}`);
  24554. }
  24555. if (!shouldAttachTrigger(0 /* TriggerType.Regular */, lView, tNode))
  24556. return;
  24557. renderPlaceholder(lView, tNode);
  24558. // Avoid adding event listeners when this instruction is invoked on the server.
  24559. if (!(typeof ngServerMode !== 'undefined' && ngServerMode)) {
  24560. registerDomTrigger(lView, tNode, triggerIndex, walkUpTimes, onInteraction, () => triggerDeferBlock(0 /* TriggerType.Regular */, lView, tNode), 0 /* TriggerType.Regular */);
  24561. }
  24562. }
  24563. /**
  24564. * Creates runtime data structures for the `prefetch on interaction` deferred trigger.
  24565. * @param triggerIndex Index at which to find the trigger element.
  24566. * @param walkUpTimes Number of times to walk up/down the tree hierarchy to find the trigger.
  24567. * @codeGenApi
  24568. */
  24569. function ɵɵdeferPrefetchOnInteraction(triggerIndex, walkUpTimes) {
  24570. const lView = getLView();
  24571. const tNode = getCurrentTNode();
  24572. if (ngDevMode) {
  24573. trackTriggerForDebugging(lView[TVIEW], tNode, `prefetch on interaction${walkUpTimes === -1 ? '' : '(<target>)'}`);
  24574. }
  24575. if (!shouldAttachTrigger(1 /* TriggerType.Prefetch */, lView, tNode))
  24576. return;
  24577. const tView = lView[TVIEW];
  24578. const tDetails = getTDeferBlockDetails(tView, tNode);
  24579. if (tDetails.loadingState === DeferDependenciesLoadingState.NOT_STARTED) {
  24580. registerDomTrigger(lView, tNode, triggerIndex, walkUpTimes, onInteraction, () => triggerPrefetching(tDetails, lView, tNode), 1 /* TriggerType.Prefetch */);
  24581. }
  24582. }
  24583. /**
  24584. * Creates runtime data structures for the `on interaction` hydrate trigger.
  24585. * @codeGenApi
  24586. */
  24587. function ɵɵdeferHydrateOnInteraction() {
  24588. const lView = getLView();
  24589. const tNode = getCurrentTNode();
  24590. if (ngDevMode) {
  24591. trackTriggerForDebugging(lView[TVIEW], tNode, 'hydrate on interaction');
  24592. }
  24593. if (!shouldAttachTrigger(2 /* TriggerType.Hydrate */, lView, tNode))
  24594. return;
  24595. const hydrateTriggers = getHydrateTriggers(getTView(), tNode);
  24596. hydrateTriggers.set(3 /* DeferBlockTrigger.Interaction */, null);
  24597. if (typeof ngServerMode !== 'undefined' && ngServerMode) {
  24598. // We are on the server and SSR for defer blocks is enabled.
  24599. triggerDeferBlock(2 /* TriggerType.Hydrate */, lView, tNode);
  24600. }
  24601. // The actual triggering of hydration on interaction is handled by JSAction in
  24602. // event_replay.ts.
  24603. }
  24604. /**
  24605. * Creates runtime data structures for the `on viewport` deferred trigger.
  24606. * @param triggerIndex Index at which to find the trigger element.
  24607. * @param walkUpTimes Number of times to walk up/down the tree hierarchy to find the trigger.
  24608. * @codeGenApi
  24609. */
  24610. function ɵɵdeferOnViewport(triggerIndex, walkUpTimes) {
  24611. const lView = getLView();
  24612. const tNode = getCurrentTNode();
  24613. if (ngDevMode) {
  24614. trackTriggerForDebugging(lView[TVIEW], tNode, `on viewport${walkUpTimes === -1 ? '' : '(<target>)'}`);
  24615. }
  24616. if (!shouldAttachTrigger(0 /* TriggerType.Regular */, lView, tNode))
  24617. return;
  24618. renderPlaceholder(lView, tNode);
  24619. // Avoid adding event listeners when this instruction is invoked on the server.
  24620. if (!(typeof ngServerMode !== 'undefined' && ngServerMode)) {
  24621. registerDomTrigger(lView, tNode, triggerIndex, walkUpTimes, onViewport, () => triggerDeferBlock(0 /* TriggerType.Regular */, lView, tNode), 0 /* TriggerType.Regular */);
  24622. }
  24623. }
  24624. /**
  24625. * Creates runtime data structures for the `prefetch on viewport` deferred trigger.
  24626. * @param triggerIndex Index at which to find the trigger element.
  24627. * @param walkUpTimes Number of times to walk up/down the tree hierarchy to find the trigger.
  24628. * @codeGenApi
  24629. */
  24630. function ɵɵdeferPrefetchOnViewport(triggerIndex, walkUpTimes) {
  24631. const lView = getLView();
  24632. const tNode = getCurrentTNode();
  24633. if (ngDevMode) {
  24634. trackTriggerForDebugging(lView[TVIEW], tNode, `prefetch on viewport${walkUpTimes === -1 ? '' : '(<target>)'}`);
  24635. }
  24636. if (!shouldAttachTrigger(1 /* TriggerType.Prefetch */, lView, tNode))
  24637. return;
  24638. const tView = lView[TVIEW];
  24639. const tDetails = getTDeferBlockDetails(tView, tNode);
  24640. if (tDetails.loadingState === DeferDependenciesLoadingState.NOT_STARTED) {
  24641. registerDomTrigger(lView, tNode, triggerIndex, walkUpTimes, onViewport, () => triggerPrefetching(tDetails, lView, tNode), 1 /* TriggerType.Prefetch */);
  24642. }
  24643. }
  24644. /**
  24645. * Creates runtime data structures for the `on viewport` hydrate trigger.
  24646. * @codeGenApi
  24647. */
  24648. function ɵɵdeferHydrateOnViewport() {
  24649. const lView = getLView();
  24650. const tNode = getCurrentTNode();
  24651. if (ngDevMode) {
  24652. trackTriggerForDebugging(lView[TVIEW], tNode, 'hydrate on viewport');
  24653. }
  24654. if (!shouldAttachTrigger(2 /* TriggerType.Hydrate */, lView, tNode))
  24655. return;
  24656. const hydrateTriggers = getHydrateTriggers(getTView(), tNode);
  24657. hydrateTriggers.set(2 /* DeferBlockTrigger.Viewport */, null);
  24658. if (typeof ngServerMode !== 'undefined' && ngServerMode) {
  24659. // We are on the server and SSR for defer blocks is enabled.
  24660. triggerDeferBlock(2 /* TriggerType.Hydrate */, lView, tNode);
  24661. }
  24662. // The actual triggering of hydration on viewport happens in triggering.ts,
  24663. // since these instructions won't exist for dehydrated content.
  24664. }
  24665. /**
  24666. * Updates the value of or removes a bound attribute on an Element.
  24667. *
  24668. * Used in the case of `[attr.title]="value"`
  24669. *
  24670. * @param name name The name of the attribute.
  24671. * @param value value The attribute is removed when value is `null` or `undefined`.
  24672. * Otherwise the attribute value is set to the stringified value.
  24673. * @param sanitizer An optional function used to sanitize the value.
  24674. * @param namespace Optional namespace to use when setting the attribute.
  24675. *
  24676. * @codeGenApi
  24677. */
  24678. function ɵɵattribute(name, value, sanitizer, namespace) {
  24679. const lView = getLView();
  24680. const bindingIndex = nextBindingIndex();
  24681. if (bindingUpdated(lView, bindingIndex, value)) {
  24682. const tView = getTView();
  24683. const tNode = getSelectedTNode();
  24684. elementAttributeInternal(tNode, lView, name, value, sanitizer, namespace);
  24685. ngDevMode && storePropertyBindingMetadata(tView.data, tNode, 'attr.' + name, bindingIndex);
  24686. }
  24687. return ɵɵattribute;
  24688. }
  24689. /**
  24690. * Create interpolation bindings with a variable number of expressions.
  24691. *
  24692. * If there are 1 to 8 expressions `interpolation1()` to `interpolation8()` should be used instead.
  24693. * Those are faster because there is no need to create an array of expressions and iterate over it.
  24694. *
  24695. * `values`:
  24696. * - has static text at even indexes,
  24697. * - has evaluated expressions at odd indexes.
  24698. *
  24699. * Returns the concatenated string when any of the arguments changes, `NO_CHANGE` otherwise.
  24700. */
  24701. function interpolationV(lView, values) {
  24702. ngDevMode && assertLessThan(2, values.length, 'should have at least 3 values');
  24703. ngDevMode && assertEqual(values.length % 2, 1, 'should have an odd number of values');
  24704. let isBindingUpdated = false;
  24705. let bindingIndex = getBindingIndex();
  24706. for (let i = 1; i < values.length; i += 2) {
  24707. // Check if bindings (odd indexes) have changed
  24708. isBindingUpdated = bindingUpdated(lView, bindingIndex++, values[i]) || isBindingUpdated;
  24709. }
  24710. setBindingIndex(bindingIndex);
  24711. if (!isBindingUpdated) {
  24712. return NO_CHANGE;
  24713. }
  24714. // Build the updated content
  24715. let content = values[0];
  24716. for (let i = 1; i < values.length; i += 2) {
  24717. content += renderStringify(values[i]) + values[i + 1];
  24718. }
  24719. return content;
  24720. }
  24721. /**
  24722. * Creates an interpolation binding with 1 expression.
  24723. *
  24724. * @param prefix static value used for concatenation only.
  24725. * @param v0 value checked for change.
  24726. * @param suffix static value used for concatenation only.
  24727. */
  24728. function interpolation1(lView, prefix, v0, suffix) {
  24729. const different = bindingUpdated(lView, nextBindingIndex(), v0);
  24730. return different ? prefix + renderStringify(v0) + suffix : NO_CHANGE;
  24731. }
  24732. /**
  24733. * Creates an interpolation binding with 2 expressions.
  24734. */
  24735. function interpolation2(lView, prefix, v0, i0, v1, suffix) {
  24736. const bindingIndex = getBindingIndex();
  24737. const different = bindingUpdated2(lView, bindingIndex, v0, v1);
  24738. incrementBindingIndex(2);
  24739. return different ? prefix + renderStringify(v0) + i0 + renderStringify(v1) + suffix : NO_CHANGE;
  24740. }
  24741. /**
  24742. * Creates an interpolation binding with 3 expressions.
  24743. */
  24744. function interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix) {
  24745. const bindingIndex = getBindingIndex();
  24746. const different = bindingUpdated3(lView, bindingIndex, v0, v1, v2);
  24747. incrementBindingIndex(3);
  24748. return different
  24749. ? prefix + renderStringify(v0) + i0 + renderStringify(v1) + i1 + renderStringify(v2) + suffix
  24750. : NO_CHANGE;
  24751. }
  24752. /**
  24753. * Create an interpolation binding with 4 expressions.
  24754. */
  24755. function interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix) {
  24756. const bindingIndex = getBindingIndex();
  24757. const different = bindingUpdated4(lView, bindingIndex, v0, v1, v2, v3);
  24758. incrementBindingIndex(4);
  24759. return different
  24760. ? prefix +
  24761. renderStringify(v0) +
  24762. i0 +
  24763. renderStringify(v1) +
  24764. i1 +
  24765. renderStringify(v2) +
  24766. i2 +
  24767. renderStringify(v3) +
  24768. suffix
  24769. : NO_CHANGE;
  24770. }
  24771. /**
  24772. * Creates an interpolation binding with 5 expressions.
  24773. */
  24774. function interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix) {
  24775. const bindingIndex = getBindingIndex();
  24776. let different = bindingUpdated4(lView, bindingIndex, v0, v1, v2, v3);
  24777. different = bindingUpdated(lView, bindingIndex + 4, v4) || different;
  24778. incrementBindingIndex(5);
  24779. return different
  24780. ? prefix +
  24781. renderStringify(v0) +
  24782. i0 +
  24783. renderStringify(v1) +
  24784. i1 +
  24785. renderStringify(v2) +
  24786. i2 +
  24787. renderStringify(v3) +
  24788. i3 +
  24789. renderStringify(v4) +
  24790. suffix
  24791. : NO_CHANGE;
  24792. }
  24793. /**
  24794. * Creates an interpolation binding with 6 expressions.
  24795. */
  24796. function interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix) {
  24797. const bindingIndex = getBindingIndex();
  24798. let different = bindingUpdated4(lView, bindingIndex, v0, v1, v2, v3);
  24799. different = bindingUpdated2(lView, bindingIndex + 4, v4, v5) || different;
  24800. incrementBindingIndex(6);
  24801. return different
  24802. ? prefix +
  24803. renderStringify(v0) +
  24804. i0 +
  24805. renderStringify(v1) +
  24806. i1 +
  24807. renderStringify(v2) +
  24808. i2 +
  24809. renderStringify(v3) +
  24810. i3 +
  24811. renderStringify(v4) +
  24812. i4 +
  24813. renderStringify(v5) +
  24814. suffix
  24815. : NO_CHANGE;
  24816. }
  24817. /**
  24818. * Creates an interpolation binding with 7 expressions.
  24819. */
  24820. function interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix) {
  24821. const bindingIndex = getBindingIndex();
  24822. let different = bindingUpdated4(lView, bindingIndex, v0, v1, v2, v3);
  24823. different = bindingUpdated3(lView, bindingIndex + 4, v4, v5, v6) || different;
  24824. incrementBindingIndex(7);
  24825. return different
  24826. ? prefix +
  24827. renderStringify(v0) +
  24828. i0 +
  24829. renderStringify(v1) +
  24830. i1 +
  24831. renderStringify(v2) +
  24832. i2 +
  24833. renderStringify(v3) +
  24834. i3 +
  24835. renderStringify(v4) +
  24836. i4 +
  24837. renderStringify(v5) +
  24838. i5 +
  24839. renderStringify(v6) +
  24840. suffix
  24841. : NO_CHANGE;
  24842. }
  24843. /**
  24844. * Creates an interpolation binding with 8 expressions.
  24845. */
  24846. function interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix) {
  24847. const bindingIndex = getBindingIndex();
  24848. let different = bindingUpdated4(lView, bindingIndex, v0, v1, v2, v3);
  24849. different = bindingUpdated4(lView, bindingIndex + 4, v4, v5, v6, v7) || different;
  24850. incrementBindingIndex(8);
  24851. return different
  24852. ? prefix +
  24853. renderStringify(v0) +
  24854. i0 +
  24855. renderStringify(v1) +
  24856. i1 +
  24857. renderStringify(v2) +
  24858. i2 +
  24859. renderStringify(v3) +
  24860. i3 +
  24861. renderStringify(v4) +
  24862. i4 +
  24863. renderStringify(v5) +
  24864. i5 +
  24865. renderStringify(v6) +
  24866. i6 +
  24867. renderStringify(v7) +
  24868. suffix
  24869. : NO_CHANGE;
  24870. }
  24871. /**
  24872. *
  24873. * Update an interpolated attribute on an element with single bound value surrounded by text.
  24874. *
  24875. * Used when the value passed to a property has 1 interpolated value in it:
  24876. *
  24877. * ```html
  24878. * <div attr.title="prefix{{v0}}suffix"></div>
  24879. * ```
  24880. *
  24881. * Its compiled representation is::
  24882. *
  24883. * ```ts
  24884. * ɵɵattributeInterpolate1('title', 'prefix', v0, 'suffix');
  24885. * ```
  24886. *
  24887. * @param attrName The name of the attribute to update
  24888. * @param prefix Static value used for concatenation only.
  24889. * @param v0 Value checked for change.
  24890. * @param suffix Static value used for concatenation only.
  24891. * @param sanitizer An optional sanitizer function
  24892. * @returns itself, so that it may be chained.
  24893. * @codeGenApi
  24894. */
  24895. function ɵɵattributeInterpolate1(attrName, prefix, v0, suffix, sanitizer, namespace) {
  24896. const lView = getLView();
  24897. const interpolatedValue = interpolation1(lView, prefix, v0, suffix);
  24898. if (interpolatedValue !== NO_CHANGE) {
  24899. const tNode = getSelectedTNode();
  24900. elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
  24901. ngDevMode &&
  24902. storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 1, prefix, suffix);
  24903. }
  24904. return ɵɵattributeInterpolate1;
  24905. }
  24906. /**
  24907. *
  24908. * Update an interpolated attribute on an element with 2 bound values surrounded by text.
  24909. *
  24910. * Used when the value passed to a property has 2 interpolated values in it:
  24911. *
  24912. * ```html
  24913. * <div attr.title="prefix{{v0}}-{{v1}}suffix"></div>
  24914. * ```
  24915. *
  24916. * Its compiled representation is::
  24917. *
  24918. * ```ts
  24919. * ɵɵattributeInterpolate2('title', 'prefix', v0, '-', v1, 'suffix');
  24920. * ```
  24921. *
  24922. * @param attrName The name of the attribute to update
  24923. * @param prefix Static value used for concatenation only.
  24924. * @param v0 Value checked for change.
  24925. * @param i0 Static value used for concatenation only.
  24926. * @param v1 Value checked for change.
  24927. * @param suffix Static value used for concatenation only.
  24928. * @param sanitizer An optional sanitizer function
  24929. * @returns itself, so that it may be chained.
  24930. * @codeGenApi
  24931. */
  24932. function ɵɵattributeInterpolate2(attrName, prefix, v0, i0, v1, suffix, sanitizer, namespace) {
  24933. const lView = getLView();
  24934. const interpolatedValue = interpolation2(lView, prefix, v0, i0, v1, suffix);
  24935. if (interpolatedValue !== NO_CHANGE) {
  24936. const tNode = getSelectedTNode();
  24937. elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
  24938. ngDevMode &&
  24939. storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 2, prefix, i0, suffix);
  24940. }
  24941. return ɵɵattributeInterpolate2;
  24942. }
  24943. /**
  24944. *
  24945. * Update an interpolated attribute on an element with 3 bound values surrounded by text.
  24946. *
  24947. * Used when the value passed to a property has 3 interpolated values in it:
  24948. *
  24949. * ```html
  24950. * <div attr.title="prefix{{v0}}-{{v1}}-{{v2}}suffix"></div>
  24951. * ```
  24952. *
  24953. * Its compiled representation is::
  24954. *
  24955. * ```ts
  24956. * ɵɵattributeInterpolate3(
  24957. * 'title', 'prefix', v0, '-', v1, '-', v2, 'suffix');
  24958. * ```
  24959. *
  24960. * @param attrName The name of the attribute to update
  24961. * @param prefix Static value used for concatenation only.
  24962. * @param v0 Value checked for change.
  24963. * @param i0 Static value used for concatenation only.
  24964. * @param v1 Value checked for change.
  24965. * @param i1 Static value used for concatenation only.
  24966. * @param v2 Value checked for change.
  24967. * @param suffix Static value used for concatenation only.
  24968. * @param sanitizer An optional sanitizer function
  24969. * @returns itself, so that it may be chained.
  24970. * @codeGenApi
  24971. */
  24972. function ɵɵattributeInterpolate3(attrName, prefix, v0, i0, v1, i1, v2, suffix, sanitizer, namespace) {
  24973. const lView = getLView();
  24974. const interpolatedValue = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix);
  24975. if (interpolatedValue !== NO_CHANGE) {
  24976. const tNode = getSelectedTNode();
  24977. elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
  24978. ngDevMode &&
  24979. storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 3, prefix, i0, i1, suffix);
  24980. }
  24981. return ɵɵattributeInterpolate3;
  24982. }
  24983. /**
  24984. *
  24985. * Update an interpolated attribute on an element with 4 bound values surrounded by text.
  24986. *
  24987. * Used when the value passed to a property has 4 interpolated values in it:
  24988. *
  24989. * ```html
  24990. * <div attr.title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}suffix"></div>
  24991. * ```
  24992. *
  24993. * Its compiled representation is::
  24994. *
  24995. * ```ts
  24996. * ɵɵattributeInterpolate4(
  24997. * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, 'suffix');
  24998. * ```
  24999. *
  25000. * @param attrName The name of the attribute to update
  25001. * @param prefix Static value used for concatenation only.
  25002. * @param v0 Value checked for change.
  25003. * @param i0 Static value used for concatenation only.
  25004. * @param v1 Value checked for change.
  25005. * @param i1 Static value used for concatenation only.
  25006. * @param v2 Value checked for change.
  25007. * @param i2 Static value used for concatenation only.
  25008. * @param v3 Value checked for change.
  25009. * @param suffix Static value used for concatenation only.
  25010. * @param sanitizer An optional sanitizer function
  25011. * @returns itself, so that it may be chained.
  25012. * @codeGenApi
  25013. */
  25014. function ɵɵattributeInterpolate4(attrName, prefix, v0, i0, v1, i1, v2, i2, v3, suffix, sanitizer, namespace) {
  25015. const lView = getLView();
  25016. const interpolatedValue = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix);
  25017. if (interpolatedValue !== NO_CHANGE) {
  25018. const tNode = getSelectedTNode();
  25019. elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
  25020. ngDevMode &&
  25021. storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 4, prefix, i0, i1, i2, suffix);
  25022. }
  25023. return ɵɵattributeInterpolate4;
  25024. }
  25025. /**
  25026. *
  25027. * Update an interpolated attribute on an element with 5 bound values surrounded by text.
  25028. *
  25029. * Used when the value passed to a property has 5 interpolated values in it:
  25030. *
  25031. * ```html
  25032. * <div attr.title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}suffix"></div>
  25033. * ```
  25034. *
  25035. * Its compiled representation is::
  25036. *
  25037. * ```ts
  25038. * ɵɵattributeInterpolate5(
  25039. * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, 'suffix');
  25040. * ```
  25041. *
  25042. * @param attrName The name of the attribute to update
  25043. * @param prefix Static value used for concatenation only.
  25044. * @param v0 Value checked for change.
  25045. * @param i0 Static value used for concatenation only.
  25046. * @param v1 Value checked for change.
  25047. * @param i1 Static value used for concatenation only.
  25048. * @param v2 Value checked for change.
  25049. * @param i2 Static value used for concatenation only.
  25050. * @param v3 Value checked for change.
  25051. * @param i3 Static value used for concatenation only.
  25052. * @param v4 Value checked for change.
  25053. * @param suffix Static value used for concatenation only.
  25054. * @param sanitizer An optional sanitizer function
  25055. * @returns itself, so that it may be chained.
  25056. * @codeGenApi
  25057. */
  25058. function ɵɵattributeInterpolate5(attrName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix, sanitizer, namespace) {
  25059. const lView = getLView();
  25060. const interpolatedValue = interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix);
  25061. if (interpolatedValue !== NO_CHANGE) {
  25062. const tNode = getSelectedTNode();
  25063. elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
  25064. ngDevMode &&
  25065. storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 5, prefix, i0, i1, i2, i3, suffix);
  25066. }
  25067. return ɵɵattributeInterpolate5;
  25068. }
  25069. /**
  25070. *
  25071. * Update an interpolated attribute on an element with 6 bound values surrounded by text.
  25072. *
  25073. * Used when the value passed to a property has 6 interpolated values in it:
  25074. *
  25075. * ```html
  25076. * <div attr.title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}suffix"></div>
  25077. * ```
  25078. *
  25079. * Its compiled representation is::
  25080. *
  25081. * ```ts
  25082. * ɵɵattributeInterpolate6(
  25083. * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, 'suffix');
  25084. * ```
  25085. *
  25086. * @param attrName The name of the attribute to update
  25087. * @param prefix Static value used for concatenation only.
  25088. * @param v0 Value checked for change.
  25089. * @param i0 Static value used for concatenation only.
  25090. * @param v1 Value checked for change.
  25091. * @param i1 Static value used for concatenation only.
  25092. * @param v2 Value checked for change.
  25093. * @param i2 Static value used for concatenation only.
  25094. * @param v3 Value checked for change.
  25095. * @param i3 Static value used for concatenation only.
  25096. * @param v4 Value checked for change.
  25097. * @param i4 Static value used for concatenation only.
  25098. * @param v5 Value checked for change.
  25099. * @param suffix Static value used for concatenation only.
  25100. * @param sanitizer An optional sanitizer function
  25101. * @returns itself, so that it may be chained.
  25102. * @codeGenApi
  25103. */
  25104. function ɵɵattributeInterpolate6(attrName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix, sanitizer, namespace) {
  25105. const lView = getLView();
  25106. const interpolatedValue = interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix);
  25107. if (interpolatedValue !== NO_CHANGE) {
  25108. const tNode = getSelectedTNode();
  25109. elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
  25110. ngDevMode &&
  25111. storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 6, prefix, i0, i1, i2, i3, i4, suffix);
  25112. }
  25113. return ɵɵattributeInterpolate6;
  25114. }
  25115. /**
  25116. *
  25117. * Update an interpolated attribute on an element with 7 bound values surrounded by text.
  25118. *
  25119. * Used when the value passed to a property has 7 interpolated values in it:
  25120. *
  25121. * ```html
  25122. * <div attr.title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}suffix"></div>
  25123. * ```
  25124. *
  25125. * Its compiled representation is::
  25126. *
  25127. * ```ts
  25128. * ɵɵattributeInterpolate7(
  25129. * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, 'suffix');
  25130. * ```
  25131. *
  25132. * @param attrName The name of the attribute to update
  25133. * @param prefix Static value used for concatenation only.
  25134. * @param v0 Value checked for change.
  25135. * @param i0 Static value used for concatenation only.
  25136. * @param v1 Value checked for change.
  25137. * @param i1 Static value used for concatenation only.
  25138. * @param v2 Value checked for change.
  25139. * @param i2 Static value used for concatenation only.
  25140. * @param v3 Value checked for change.
  25141. * @param i3 Static value used for concatenation only.
  25142. * @param v4 Value checked for change.
  25143. * @param i4 Static value used for concatenation only.
  25144. * @param v5 Value checked for change.
  25145. * @param i5 Static value used for concatenation only.
  25146. * @param v6 Value checked for change.
  25147. * @param suffix Static value used for concatenation only.
  25148. * @param sanitizer An optional sanitizer function
  25149. * @returns itself, so that it may be chained.
  25150. * @codeGenApi
  25151. */
  25152. function ɵɵattributeInterpolate7(attrName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix, sanitizer, namespace) {
  25153. const lView = getLView();
  25154. const interpolatedValue = interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix);
  25155. if (interpolatedValue !== NO_CHANGE) {
  25156. const tNode = getSelectedTNode();
  25157. elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
  25158. ngDevMode &&
  25159. storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 7, prefix, i0, i1, i2, i3, i4, i5, suffix);
  25160. }
  25161. return ɵɵattributeInterpolate7;
  25162. }
  25163. /**
  25164. *
  25165. * Update an interpolated attribute on an element with 8 bound values surrounded by text.
  25166. *
  25167. * Used when the value passed to a property has 8 interpolated values in it:
  25168. *
  25169. * ```html
  25170. * <div attr.title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}suffix"></div>
  25171. * ```
  25172. *
  25173. * Its compiled representation is::
  25174. *
  25175. * ```ts
  25176. * ɵɵattributeInterpolate8(
  25177. * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, 'suffix');
  25178. * ```
  25179. *
  25180. * @param attrName The name of the attribute to update
  25181. * @param prefix Static value used for concatenation only.
  25182. * @param v0 Value checked for change.
  25183. * @param i0 Static value used for concatenation only.
  25184. * @param v1 Value checked for change.
  25185. * @param i1 Static value used for concatenation only.
  25186. * @param v2 Value checked for change.
  25187. * @param i2 Static value used for concatenation only.
  25188. * @param v3 Value checked for change.
  25189. * @param i3 Static value used for concatenation only.
  25190. * @param v4 Value checked for change.
  25191. * @param i4 Static value used for concatenation only.
  25192. * @param v5 Value checked for change.
  25193. * @param i5 Static value used for concatenation only.
  25194. * @param v6 Value checked for change.
  25195. * @param i6 Static value used for concatenation only.
  25196. * @param v7 Value checked for change.
  25197. * @param suffix Static value used for concatenation only.
  25198. * @param sanitizer An optional sanitizer function
  25199. * @returns itself, so that it may be chained.
  25200. * @codeGenApi
  25201. */
  25202. function ɵɵattributeInterpolate8(attrName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix, sanitizer, namespace) {
  25203. const lView = getLView();
  25204. const interpolatedValue = interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix);
  25205. if (interpolatedValue !== NO_CHANGE) {
  25206. const tNode = getSelectedTNode();
  25207. elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
  25208. ngDevMode &&
  25209. storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 8, prefix, i0, i1, i2, i3, i4, i5, i6, suffix);
  25210. }
  25211. return ɵɵattributeInterpolate8;
  25212. }
  25213. /**
  25214. * Update an interpolated attribute on an element with 9 or more bound values surrounded by text.
  25215. *
  25216. * Used when the number of interpolated values exceeds 8.
  25217. *
  25218. * ```html
  25219. * <div
  25220. * title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}-{{v8}}-{{v9}}suffix"></div>
  25221. * ```
  25222. *
  25223. * Its compiled representation is::
  25224. *
  25225. * ```ts
  25226. * ɵɵattributeInterpolateV(
  25227. * 'title', ['prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, '-', v9,
  25228. * 'suffix']);
  25229. * ```
  25230. *
  25231. * @param attrName The name of the attribute to update.
  25232. * @param values The collection of values and the strings in-between those values, beginning with
  25233. * a string prefix and ending with a string suffix.
  25234. * (e.g. `['prefix', value0, '-', value1, '-', value2, ..., value99, 'suffix']`)
  25235. * @param sanitizer An optional sanitizer function
  25236. * @returns itself, so that it may be chained.
  25237. * @codeGenApi
  25238. */
  25239. function ɵɵattributeInterpolateV(attrName, values, sanitizer, namespace) {
  25240. const lView = getLView();
  25241. const interpolated = interpolationV(lView, values);
  25242. if (interpolated !== NO_CHANGE) {
  25243. const tNode = getSelectedTNode();
  25244. elementAttributeInternal(tNode, lView, attrName, interpolated, sanitizer, namespace);
  25245. if (ngDevMode) {
  25246. const interpolationInBetween = [values[0]]; // prefix
  25247. for (let i = 2; i < values.length; i += 2) {
  25248. interpolationInBetween.push(values[i]);
  25249. }
  25250. storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - interpolationInBetween.length + 1, ...interpolationInBetween);
  25251. }
  25252. }
  25253. return ɵɵattributeInterpolateV;
  25254. }
  25255. function toTStylingRange(prev, next) {
  25256. ngDevMode && assertNumberInRange(prev, 0, 32767 /* StylingRange.UNSIGNED_MASK */);
  25257. ngDevMode && assertNumberInRange(next, 0, 32767 /* StylingRange.UNSIGNED_MASK */);
  25258. return ((prev << 17 /* StylingRange.PREV_SHIFT */) | (next << 2 /* StylingRange.NEXT_SHIFT */));
  25259. }
  25260. function getTStylingRangePrev(tStylingRange) {
  25261. ngDevMode && assertNumber(tStylingRange, 'expected number');
  25262. return (tStylingRange >> 17 /* StylingRange.PREV_SHIFT */) & 32767 /* StylingRange.UNSIGNED_MASK */;
  25263. }
  25264. function getTStylingRangePrevDuplicate(tStylingRange) {
  25265. ngDevMode && assertNumber(tStylingRange, 'expected number');
  25266. return (tStylingRange & 2 /* StylingRange.PREV_DUPLICATE */) == 2 /* StylingRange.PREV_DUPLICATE */;
  25267. }
  25268. function setTStylingRangePrev(tStylingRange, previous) {
  25269. ngDevMode && assertNumber(tStylingRange, 'expected number');
  25270. ngDevMode && assertNumberInRange(previous, 0, 32767 /* StylingRange.UNSIGNED_MASK */);
  25271. return ((tStylingRange & 131071 /* StylingRange.PREV_MASK */) |
  25272. (previous << 17 /* StylingRange.PREV_SHIFT */));
  25273. }
  25274. function setTStylingRangePrevDuplicate(tStylingRange) {
  25275. ngDevMode && assertNumber(tStylingRange, 'expected number');
  25276. return (tStylingRange | 2 /* StylingRange.PREV_DUPLICATE */);
  25277. }
  25278. function getTStylingRangeNext(tStylingRange) {
  25279. ngDevMode && assertNumber(tStylingRange, 'expected number');
  25280. return (tStylingRange & 131068 /* StylingRange.NEXT_MASK */) >> 2 /* StylingRange.NEXT_SHIFT */;
  25281. }
  25282. function setTStylingRangeNext(tStylingRange, next) {
  25283. ngDevMode && assertNumber(tStylingRange, 'expected number');
  25284. ngDevMode && assertNumberInRange(next, 0, 32767 /* StylingRange.UNSIGNED_MASK */);
  25285. return ((tStylingRange & -131069 /* StylingRange.NEXT_MASK */) | //
  25286. (next << 2 /* StylingRange.NEXT_SHIFT */));
  25287. }
  25288. function getTStylingRangeNextDuplicate(tStylingRange) {
  25289. ngDevMode && assertNumber(tStylingRange, 'expected number');
  25290. return (tStylingRange & 1 /* StylingRange.NEXT_DUPLICATE */) === 1 /* StylingRange.NEXT_DUPLICATE */;
  25291. }
  25292. function setTStylingRangeNextDuplicate(tStylingRange) {
  25293. ngDevMode && assertNumber(tStylingRange, 'expected number');
  25294. return (tStylingRange | 1 /* StylingRange.NEXT_DUPLICATE */);
  25295. }
  25296. /**
  25297. * Insert new `tStyleValue` at `TData` and link existing style bindings such that we maintain linked
  25298. * list of styles and compute the duplicate flag.
  25299. *
  25300. * Note: this function is executed during `firstUpdatePass` only to populate the `TView.data`.
  25301. *
  25302. * The function works by keeping track of `tStylingRange` which contains two pointers pointing to
  25303. * the head/tail of the template portion of the styles.
  25304. * - if `isHost === false` (we are template) then insertion is at tail of `TStylingRange`
  25305. * - if `isHost === true` (we are host binding) then insertion is at head of `TStylingRange`
  25306. *
  25307. * @param tData The `TData` to insert into.
  25308. * @param tNode `TNode` associated with the styling element.
  25309. * @param tStylingKey See `TStylingKey`.
  25310. * @param index location of where `tStyleValue` should be stored (and linked into list.)
  25311. * @param isHostBinding `true` if the insertion is for a `hostBinding`. (insertion is in front of
  25312. * template.)
  25313. * @param isClassBinding True if the associated `tStylingKey` as a `class` styling.
  25314. * `tNode.classBindings` should be used (or `tNode.styleBindings` otherwise.)
  25315. */
  25316. function insertTStylingBinding(tData, tNode, tStylingKeyWithStatic, index, isHostBinding, isClassBinding) {
  25317. ngDevMode && assertFirstUpdatePass(getTView());
  25318. let tBindings = isClassBinding ? tNode.classBindings : tNode.styleBindings;
  25319. let tmplHead = getTStylingRangePrev(tBindings);
  25320. let tmplTail = getTStylingRangeNext(tBindings);
  25321. tData[index] = tStylingKeyWithStatic;
  25322. let isKeyDuplicateOfStatic = false;
  25323. let tStylingKey;
  25324. if (Array.isArray(tStylingKeyWithStatic)) {
  25325. // We are case when the `TStylingKey` contains static fields as well.
  25326. const staticKeyValueArray = tStylingKeyWithStatic;
  25327. tStylingKey = staticKeyValueArray[1]; // unwrap.
  25328. // We need to check if our key is present in the static so that we can mark it as duplicate.
  25329. if (tStylingKey === null ||
  25330. keyValueArrayIndexOf(staticKeyValueArray, tStylingKey) > 0) {
  25331. // tStylingKey is present in the statics, need to mark it as duplicate.
  25332. isKeyDuplicateOfStatic = true;
  25333. }
  25334. }
  25335. else {
  25336. tStylingKey = tStylingKeyWithStatic;
  25337. }
  25338. if (isHostBinding) {
  25339. // We are inserting host bindings
  25340. // If we don't have template bindings then `tail` is 0.
  25341. const hasTemplateBindings = tmplTail !== 0;
  25342. // This is important to know because that means that the `head` can't point to the first
  25343. // template bindings (there are none.) Instead the head points to the tail of the template.
  25344. if (hasTemplateBindings) {
  25345. // template head's "prev" will point to last host binding or to 0 if no host bindings yet
  25346. const previousNode = getTStylingRangePrev(tData[tmplHead + 1]);
  25347. tData[index + 1] = toTStylingRange(previousNode, tmplHead);
  25348. // if a host binding has already been registered, we need to update the next of that host
  25349. // binding to point to this one
  25350. if (previousNode !== 0) {
  25351. // We need to update the template-tail value to point to us.
  25352. tData[previousNode + 1] = setTStylingRangeNext(tData[previousNode + 1], index);
  25353. }
  25354. // The "previous" of the template binding head should point to this host binding
  25355. tData[tmplHead + 1] = setTStylingRangePrev(tData[tmplHead + 1], index);
  25356. }
  25357. else {
  25358. tData[index + 1] = toTStylingRange(tmplHead, 0);
  25359. // if a host binding has already been registered, we need to update the next of that host
  25360. // binding to point to this one
  25361. if (tmplHead !== 0) {
  25362. // We need to update the template-tail value to point to us.
  25363. tData[tmplHead + 1] = setTStylingRangeNext(tData[tmplHead + 1], index);
  25364. }
  25365. // if we don't have template, the head points to template-tail, and needs to be advanced.
  25366. tmplHead = index;
  25367. }
  25368. }
  25369. else {
  25370. // We are inserting in template section.
  25371. // We need to set this binding's "previous" to the current template tail
  25372. tData[index + 1] = toTStylingRange(tmplTail, 0);
  25373. ngDevMode &&
  25374. assertEqual(tmplHead !== 0 && tmplTail === 0, false, 'Adding template bindings after hostBindings is not allowed.');
  25375. if (tmplHead === 0) {
  25376. tmplHead = index;
  25377. }
  25378. else {
  25379. // We need to update the previous value "next" to point to this binding
  25380. tData[tmplTail + 1] = setTStylingRangeNext(tData[tmplTail + 1], index);
  25381. }
  25382. tmplTail = index;
  25383. }
  25384. // Now we need to update / compute the duplicates.
  25385. // Starting with our location search towards head (least priority)
  25386. if (isKeyDuplicateOfStatic) {
  25387. tData[index + 1] = setTStylingRangePrevDuplicate(tData[index + 1]);
  25388. }
  25389. markDuplicates(tData, tStylingKey, index, true);
  25390. markDuplicates(tData, tStylingKey, index, false);
  25391. markDuplicateOfResidualStyling(tNode, tStylingKey, tData, index, isClassBinding);
  25392. tBindings = toTStylingRange(tmplHead, tmplTail);
  25393. if (isClassBinding) {
  25394. tNode.classBindings = tBindings;
  25395. }
  25396. else {
  25397. tNode.styleBindings = tBindings;
  25398. }
  25399. }
  25400. /**
  25401. * Look into the residual styling to see if the current `tStylingKey` is duplicate of residual.
  25402. *
  25403. * @param tNode `TNode` where the residual is stored.
  25404. * @param tStylingKey `TStylingKey` to store.
  25405. * @param tData `TData` associated with the current `LView`.
  25406. * @param index location of where `tStyleValue` should be stored (and linked into list.)
  25407. * @param isClassBinding True if the associated `tStylingKey` as a `class` styling.
  25408. * `tNode.classBindings` should be used (or `tNode.styleBindings` otherwise.)
  25409. */
  25410. function markDuplicateOfResidualStyling(tNode, tStylingKey, tData, index, isClassBinding) {
  25411. const residual = isClassBinding ? tNode.residualClasses : tNode.residualStyles;
  25412. if (residual != null /* or undefined */ &&
  25413. typeof tStylingKey == 'string' &&
  25414. keyValueArrayIndexOf(residual, tStylingKey) >= 0) {
  25415. // We have duplicate in the residual so mark ourselves as duplicate.
  25416. tData[index + 1] = setTStylingRangeNextDuplicate(tData[index + 1]);
  25417. }
  25418. }
  25419. /**
  25420. * Marks `TStyleValue`s as duplicates if another style binding in the list has the same
  25421. * `TStyleValue`.
  25422. *
  25423. * NOTE: this function is intended to be called twice once with `isPrevDir` set to `true` and once
  25424. * with it set to `false` to search both the previous as well as next items in the list.
  25425. *
  25426. * No duplicate case
  25427. * ```
  25428. * [style.color]
  25429. * [style.width.px] <<- index
  25430. * [style.height.px]
  25431. * ```
  25432. *
  25433. * In the above case adding `[style.width.px]` to the existing `[style.color]` produces no
  25434. * duplicates because `width` is not found in any other part of the linked list.
  25435. *
  25436. * Duplicate case
  25437. * ```
  25438. * [style.color]
  25439. * [style.width.em]
  25440. * [style.width.px] <<- index
  25441. * ```
  25442. * In the above case adding `[style.width.px]` will produce a duplicate with `[style.width.em]`
  25443. * because `width` is found in the chain.
  25444. *
  25445. * Map case 1
  25446. * ```
  25447. * [style.width.px]
  25448. * [style.color]
  25449. * [style] <<- index
  25450. * ```
  25451. * In the above case adding `[style]` will produce a duplicate with any other bindings because
  25452. * `[style]` is a Map and as such is fully dynamic and could produce `color` or `width`.
  25453. *
  25454. * Map case 2
  25455. * ```
  25456. * [style]
  25457. * [style.width.px]
  25458. * [style.color] <<- index
  25459. * ```
  25460. * In the above case adding `[style.color]` will produce a duplicate because there is already a
  25461. * `[style]` binding which is a Map and as such is fully dynamic and could produce `color` or
  25462. * `width`.
  25463. *
  25464. * NOTE: Once `[style]` (Map) is added into the system all things are mapped as duplicates.
  25465. * NOTE: We use `style` as example, but same logic is applied to `class`es as well.
  25466. *
  25467. * @param tData `TData` where the linked list is stored.
  25468. * @param tStylingKey `TStylingKeyPrimitive` which contains the value to compare to other keys in
  25469. * the linked list.
  25470. * @param index Starting location in the linked list to search from
  25471. * @param isPrevDir Direction.
  25472. * - `true` for previous (lower priority);
  25473. * - `false` for next (higher priority).
  25474. */
  25475. function markDuplicates(tData, tStylingKey, index, isPrevDir) {
  25476. const tStylingAtIndex = tData[index + 1];
  25477. const isMap = tStylingKey === null;
  25478. let cursor = isPrevDir
  25479. ? getTStylingRangePrev(tStylingAtIndex)
  25480. : getTStylingRangeNext(tStylingAtIndex);
  25481. let foundDuplicate = false;
  25482. // We keep iterating as long as we have a cursor
  25483. // AND either:
  25484. // - we found what we are looking for, OR
  25485. // - we are a map in which case we have to continue searching even after we find what we were
  25486. // looking for since we are a wild card and everything needs to be flipped to duplicate.
  25487. while (cursor !== 0 && (foundDuplicate === false || isMap)) {
  25488. ngDevMode && assertIndexInRange(tData, cursor);
  25489. const tStylingValueAtCursor = tData[cursor];
  25490. const tStyleRangeAtCursor = tData[cursor + 1];
  25491. if (isStylingMatch(tStylingValueAtCursor, tStylingKey)) {
  25492. foundDuplicate = true;
  25493. tData[cursor + 1] = isPrevDir
  25494. ? setTStylingRangeNextDuplicate(tStyleRangeAtCursor)
  25495. : setTStylingRangePrevDuplicate(tStyleRangeAtCursor);
  25496. }
  25497. cursor = isPrevDir
  25498. ? getTStylingRangePrev(tStyleRangeAtCursor)
  25499. : getTStylingRangeNext(tStyleRangeAtCursor);
  25500. }
  25501. if (foundDuplicate) {
  25502. // if we found a duplicate, than mark ourselves.
  25503. tData[index + 1] = isPrevDir
  25504. ? setTStylingRangePrevDuplicate(tStylingAtIndex)
  25505. : setTStylingRangeNextDuplicate(tStylingAtIndex);
  25506. }
  25507. }
  25508. /**
  25509. * Determines if two `TStylingKey`s are a match.
  25510. *
  25511. * When computing whether a binding contains a duplicate, we need to compare if the instruction
  25512. * `TStylingKey` has a match.
  25513. *
  25514. * Here are examples of `TStylingKey`s which match given `tStylingKeyCursor` is:
  25515. * - `color`
  25516. * - `color` // Match another color
  25517. * - `null` // That means that `tStylingKey` is a `classMap`/`styleMap` instruction
  25518. * - `['', 'color', 'other', true]` // wrapped `color` so match
  25519. * - `['', null, 'other', true]` // wrapped `null` so match
  25520. * - `['', 'width', 'color', 'value']` // wrapped static value contains a match on `'color'`
  25521. * - `null` // `tStylingKeyCursor` always match as it is `classMap`/`styleMap` instruction
  25522. *
  25523. * @param tStylingKeyCursor
  25524. * @param tStylingKey
  25525. */
  25526. function isStylingMatch(tStylingKeyCursor, tStylingKey) {
  25527. ngDevMode &&
  25528. assertNotEqual(Array.isArray(tStylingKey), true, "Expected that 'tStylingKey' has been unwrapped");
  25529. if (tStylingKeyCursor === null || // If the cursor is `null` it means that we have map at that
  25530. // location so we must assume that we have a match.
  25531. tStylingKey == null || // If `tStylingKey` is `null` then it is a map therefor assume that it
  25532. // contains a match.
  25533. (Array.isArray(tStylingKeyCursor) ? tStylingKeyCursor[1] : tStylingKeyCursor) === tStylingKey // If the keys match explicitly than we are a match.
  25534. ) {
  25535. return true;
  25536. }
  25537. else if (Array.isArray(tStylingKeyCursor) && typeof tStylingKey === 'string') {
  25538. // if we did not find a match, but `tStylingKeyCursor` is `KeyValueArray` that means cursor has
  25539. // statics and we need to check those as well.
  25540. return keyValueArrayIndexOf(tStylingKeyCursor, tStylingKey) >= 0; // see if we are matching the key
  25541. }
  25542. return false;
  25543. }
  25544. // Global state of the parser. (This makes parser non-reentrant, but that is not an issue)
  25545. const parserState = {
  25546. textEnd: 0,
  25547. key: 0,
  25548. keyEnd: 0,
  25549. value: 0,
  25550. valueEnd: 0,
  25551. };
  25552. /**
  25553. * Retrieves the last parsed `key` of style.
  25554. * @param text the text to substring the key from.
  25555. */
  25556. function getLastParsedKey(text) {
  25557. return text.substring(parserState.key, parserState.keyEnd);
  25558. }
  25559. /**
  25560. * Retrieves the last parsed `value` of style.
  25561. * @param text the text to substring the key from.
  25562. */
  25563. function getLastParsedValue(text) {
  25564. return text.substring(parserState.value, parserState.valueEnd);
  25565. }
  25566. /**
  25567. * Initializes `className` string for parsing and parses the first token.
  25568. *
  25569. * This function is intended to be used in this format:
  25570. * ```ts
  25571. * for (let i = parseClassName(text); i >= 0; i = parseClassNameNext(text, i)) {
  25572. * const key = getLastParsedKey();
  25573. * ...
  25574. * }
  25575. * ```
  25576. * @param text `className` to parse
  25577. * @returns index where the next invocation of `parseClassNameNext` should resume.
  25578. */
  25579. function parseClassName(text) {
  25580. resetParserState(text);
  25581. return parseClassNameNext(text, consumeWhitespace(text, 0, parserState.textEnd));
  25582. }
  25583. /**
  25584. * Parses next `className` token.
  25585. *
  25586. * This function is intended to be used in this format:
  25587. * ```ts
  25588. * for (let i = parseClassName(text); i >= 0; i = parseClassNameNext(text, i)) {
  25589. * const key = getLastParsedKey();
  25590. * ...
  25591. * }
  25592. * ```
  25593. *
  25594. * @param text `className` to parse
  25595. * @param index where the parsing should resume.
  25596. * @returns index where the next invocation of `parseClassNameNext` should resume.
  25597. */
  25598. function parseClassNameNext(text, index) {
  25599. const end = parserState.textEnd;
  25600. if (end === index) {
  25601. return -1;
  25602. }
  25603. index = parserState.keyEnd = consumeClassToken(text, (parserState.key = index), end);
  25604. return consumeWhitespace(text, index, end);
  25605. }
  25606. /**
  25607. * Initializes `cssText` string for parsing and parses the first key/values.
  25608. *
  25609. * This function is intended to be used in this format:
  25610. * ```ts
  25611. * for (let i = parseStyle(text); i >= 0; i = parseStyleNext(text, i))) {
  25612. * const key = getLastParsedKey();
  25613. * const value = getLastParsedValue();
  25614. * ...
  25615. * }
  25616. * ```
  25617. * @param text `cssText` to parse
  25618. * @returns index where the next invocation of `parseStyleNext` should resume.
  25619. */
  25620. function parseStyle(text) {
  25621. resetParserState(text);
  25622. return parseStyleNext(text, consumeWhitespace(text, 0, parserState.textEnd));
  25623. }
  25624. /**
  25625. * Parses the next `cssText` key/values.
  25626. *
  25627. * This function is intended to be used in this format:
  25628. * ```ts
  25629. * for (let i = parseStyle(text); i >= 0; i = parseStyleNext(text, i))) {
  25630. * const key = getLastParsedKey();
  25631. * const value = getLastParsedValue();
  25632. * ...
  25633. * }
  25634. *
  25635. * @param text `cssText` to parse
  25636. * @param index where the parsing should resume.
  25637. * @returns index where the next invocation of `parseStyleNext` should resume.
  25638. */
  25639. function parseStyleNext(text, startIndex) {
  25640. const end = parserState.textEnd;
  25641. let index = (parserState.key = consumeWhitespace(text, startIndex, end));
  25642. if (end === index) {
  25643. // we reached an end so just quit
  25644. return -1;
  25645. }
  25646. index = parserState.keyEnd = consumeStyleKey(text, index, end);
  25647. index = consumeSeparator(text, index, end, 58 /* CharCode.COLON */);
  25648. index = parserState.value = consumeWhitespace(text, index, end);
  25649. index = parserState.valueEnd = consumeStyleValue(text, index, end);
  25650. return consumeSeparator(text, index, end, 59 /* CharCode.SEMI_COLON */);
  25651. }
  25652. /**
  25653. * Reset the global state of the styling parser.
  25654. * @param text The styling text to parse.
  25655. */
  25656. function resetParserState(text) {
  25657. parserState.key = 0;
  25658. parserState.keyEnd = 0;
  25659. parserState.value = 0;
  25660. parserState.valueEnd = 0;
  25661. parserState.textEnd = text.length;
  25662. }
  25663. /**
  25664. * Returns index of next non-whitespace character.
  25665. *
  25666. * @param text Text to scan
  25667. * @param startIndex Starting index of character where the scan should start.
  25668. * @param endIndex Ending index of character where the scan should end.
  25669. * @returns Index of next non-whitespace character (May be the same as `start` if no whitespace at
  25670. * that location.)
  25671. */
  25672. function consumeWhitespace(text, startIndex, endIndex) {
  25673. while (startIndex < endIndex && text.charCodeAt(startIndex) <= 32 /* CharCode.SPACE */) {
  25674. startIndex++;
  25675. }
  25676. return startIndex;
  25677. }
  25678. /**
  25679. * Returns index of last char in class token.
  25680. *
  25681. * @param text Text to scan
  25682. * @param startIndex Starting index of character where the scan should start.
  25683. * @param endIndex Ending index of character where the scan should end.
  25684. * @returns Index after last char in class token.
  25685. */
  25686. function consumeClassToken(text, startIndex, endIndex) {
  25687. while (startIndex < endIndex && text.charCodeAt(startIndex) > 32 /* CharCode.SPACE */) {
  25688. startIndex++;
  25689. }
  25690. return startIndex;
  25691. }
  25692. /**
  25693. * Consumes all of the characters belonging to style key and token.
  25694. *
  25695. * @param text Text to scan
  25696. * @param startIndex Starting index of character where the scan should start.
  25697. * @param endIndex Ending index of character where the scan should end.
  25698. * @returns Index after last style key character.
  25699. */
  25700. function consumeStyleKey(text, startIndex, endIndex) {
  25701. let ch;
  25702. while (startIndex < endIndex &&
  25703. ((ch = text.charCodeAt(startIndex)) === 45 /* CharCode.DASH */ ||
  25704. ch === 95 /* CharCode.UNDERSCORE */ ||
  25705. ((ch & -33 /* CharCode.UPPER_CASE */) >= 65 /* CharCode.A */ && (ch & -33 /* CharCode.UPPER_CASE */) <= 90 /* CharCode.Z */) ||
  25706. (ch >= 48 /* CharCode.ZERO */ && ch <= 57 /* CharCode.NINE */))) {
  25707. startIndex++;
  25708. }
  25709. return startIndex;
  25710. }
  25711. /**
  25712. * Consumes all whitespace and the separator `:` after the style key.
  25713. *
  25714. * @param text Text to scan
  25715. * @param startIndex Starting index of character where the scan should start.
  25716. * @param endIndex Ending index of character where the scan should end.
  25717. * @returns Index after separator and surrounding whitespace.
  25718. */
  25719. function consumeSeparator(text, startIndex, endIndex, separator) {
  25720. startIndex = consumeWhitespace(text, startIndex, endIndex);
  25721. if (startIndex < endIndex) {
  25722. if (ngDevMode && text.charCodeAt(startIndex) !== separator) {
  25723. malformedStyleError(text, String.fromCharCode(separator), startIndex);
  25724. }
  25725. startIndex++;
  25726. }
  25727. return startIndex;
  25728. }
  25729. /**
  25730. * Consumes style value honoring `url()` and `""` text.
  25731. *
  25732. * @param text Text to scan
  25733. * @param startIndex Starting index of character where the scan should start.
  25734. * @param endIndex Ending index of character where the scan should end.
  25735. * @returns Index after last style value character.
  25736. */
  25737. function consumeStyleValue(text, startIndex, endIndex) {
  25738. let ch1 = -1; // 1st previous character
  25739. let ch2 = -1; // 2nd previous character
  25740. let ch3 = -1; // 3rd previous character
  25741. let i = startIndex;
  25742. let lastChIndex = i;
  25743. while (i < endIndex) {
  25744. const ch = text.charCodeAt(i++);
  25745. if (ch === 59 /* CharCode.SEMI_COLON */) {
  25746. return lastChIndex;
  25747. }
  25748. else if (ch === 34 /* CharCode.DOUBLE_QUOTE */ || ch === 39 /* CharCode.SINGLE_QUOTE */) {
  25749. lastChIndex = i = consumeQuotedText(text, ch, i, endIndex);
  25750. }
  25751. else if (startIndex === i - 4 && // We have seen only 4 characters so far "URL(" (Ignore "foo_URL()")
  25752. ch3 === 85 /* CharCode.U */ &&
  25753. ch2 === 82 /* CharCode.R */ &&
  25754. ch1 === 76 /* CharCode.L */ &&
  25755. ch === 40 /* CharCode.OPEN_PAREN */) {
  25756. lastChIndex = i = consumeQuotedText(text, 41 /* CharCode.CLOSE_PAREN */, i, endIndex);
  25757. }
  25758. else if (ch > 32 /* CharCode.SPACE */) {
  25759. // if we have a non-whitespace character then capture its location
  25760. lastChIndex = i;
  25761. }
  25762. ch3 = ch2;
  25763. ch2 = ch1;
  25764. ch1 = ch & -33 /* CharCode.UPPER_CASE */;
  25765. }
  25766. return lastChIndex;
  25767. }
  25768. /**
  25769. * Consumes all of the quoted characters.
  25770. *
  25771. * @param text Text to scan
  25772. * @param quoteCharCode CharCode of either `"` or `'` quote or `)` for `url(...)`.
  25773. * @param startIndex Starting index of character where the scan should start.
  25774. * @param endIndex Ending index of character where the scan should end.
  25775. * @returns Index after quoted characters.
  25776. */
  25777. function consumeQuotedText(text, quoteCharCode, startIndex, endIndex) {
  25778. let ch1 = -1; // 1st previous character
  25779. let index = startIndex;
  25780. while (index < endIndex) {
  25781. const ch = text.charCodeAt(index++);
  25782. if (ch == quoteCharCode && ch1 !== 92 /* CharCode.BACK_SLASH */) {
  25783. return index;
  25784. }
  25785. if (ch == 92 /* CharCode.BACK_SLASH */ && ch1 === 92 /* CharCode.BACK_SLASH */) {
  25786. // two back slashes cancel each other out. For example `"\\"` should properly end the
  25787. // quotation. (It should not assume that the last `"` is escaped.)
  25788. ch1 = 0;
  25789. }
  25790. else {
  25791. ch1 = ch;
  25792. }
  25793. }
  25794. throw ngDevMode
  25795. ? malformedStyleError(text, String.fromCharCode(quoteCharCode), endIndex)
  25796. : new Error();
  25797. }
  25798. function malformedStyleError(text, expecting, index) {
  25799. ngDevMode && assertEqual(typeof text === 'string', true, 'String expected here');
  25800. throw throwError(`Malformed style at location ${index} in string '` +
  25801. text.substring(0, index) +
  25802. '[>>' +
  25803. text.substring(index, index + 1) +
  25804. '<<]' +
  25805. text.slice(index + 1) +
  25806. `'. Expecting '${expecting}'.`);
  25807. }
  25808. /**
  25809. * Update a property on a selected element.
  25810. *
  25811. * Operates on the element selected by index via the {@link select} instruction.
  25812. *
  25813. * If the property name also exists as an input property on one of the element's directives,
  25814. * the component property will be set instead of the element property. This check must
  25815. * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled
  25816. *
  25817. * @param propName Name of property. Because it is going to DOM, this is not subject to
  25818. * renaming as part of minification.
  25819. * @param value New value to write.
  25820. * @param sanitizer An optional function used to sanitize the value.
  25821. * @returns This function returns itself so that it may be chained
  25822. * (e.g. `property('name', ctx.name)('title', ctx.title)`)
  25823. *
  25824. * @codeGenApi
  25825. */
  25826. function ɵɵproperty(propName, value, sanitizer) {
  25827. const lView = getLView();
  25828. const bindingIndex = nextBindingIndex();
  25829. if (bindingUpdated(lView, bindingIndex, value)) {
  25830. const tView = getTView();
  25831. const tNode = getSelectedTNode();
  25832. elementPropertyInternal(tView, tNode, lView, propName, value, lView[RENDERER], sanitizer, false);
  25833. ngDevMode && storePropertyBindingMetadata(tView.data, tNode, propName, bindingIndex);
  25834. }
  25835. return ɵɵproperty;
  25836. }
  25837. /**
  25838. * Given `<div style="..." my-dir>` and `MyDir` with `@Input('style')` we need to write to
  25839. * directive input.
  25840. */
  25841. function setDirectiveInputsWhichShadowsStyling(tView, tNode, lView, value, isClassBased) {
  25842. // We support both 'class' and `className` hence the fallback.
  25843. setAllInputsForProperty(tNode, tView, lView, isClassBased ? 'class' : 'style', value);
  25844. }
  25845. /**
  25846. * Update a style binding on an element with the provided value.
  25847. *
  25848. * If the style value is falsy then it will be removed from the element
  25849. * (or assigned a different value depending if there are any styles placed
  25850. * on the element with `styleMap` or any static styles that are
  25851. * present from when the element was created with `styling`).
  25852. *
  25853. * Note that the styling element is updated as part of `stylingApply`.
  25854. *
  25855. * @param prop A valid CSS property.
  25856. * @param value New value to write (`null` or an empty string to remove).
  25857. * @param suffix Optional suffix. Used with scalar values to add unit such as `px`.
  25858. *
  25859. * Note that this will apply the provided style value to the host element if this function is called
  25860. * within a host binding function.
  25861. *
  25862. * @codeGenApi
  25863. */
  25864. function ɵɵstyleProp(prop, value, suffix) {
  25865. checkStylingProperty(prop, value, suffix, false);
  25866. return ɵɵstyleProp;
  25867. }
  25868. /**
  25869. * Update a class binding on an element with the provided value.
  25870. *
  25871. * This instruction is meant to handle the `[class.foo]="exp"` case and,
  25872. * therefore, the class binding itself must already be allocated using
  25873. * `styling` within the creation block.
  25874. *
  25875. * @param prop A valid CSS class (only one).
  25876. * @param value A true/false value which will turn the class on or off.
  25877. *
  25878. * Note that this will apply the provided class value to the host element if this function
  25879. * is called within a host binding function.
  25880. *
  25881. * @codeGenApi
  25882. */
  25883. function ɵɵclassProp(className, value) {
  25884. checkStylingProperty(className, value, null, true);
  25885. return ɵɵclassProp;
  25886. }
  25887. /**
  25888. * Update style bindings using an object literal on an element.
  25889. *
  25890. * This instruction is meant to apply styling via the `[style]="exp"` template bindings.
  25891. * When styles are applied to the element they will then be updated with respect to
  25892. * any styles/classes set via `styleProp`. If any styles are set to falsy
  25893. * then they will be removed from the element.
  25894. *
  25895. * Note that the styling instruction will not be applied until `stylingApply` is called.
  25896. *
  25897. * @param styles A key/value style map of the styles that will be applied to the given element.
  25898. * Any missing styles (that have already been applied to the element beforehand) will be
  25899. * removed (unset) from the element's styling.
  25900. *
  25901. * Note that this will apply the provided styleMap value to the host element if this function
  25902. * is called within a host binding.
  25903. *
  25904. * @codeGenApi
  25905. */
  25906. function ɵɵstyleMap(styles) {
  25907. checkStylingMap(styleKeyValueArraySet, styleStringParser, styles, false);
  25908. }
  25909. /**
  25910. * Parse text as style and add values to KeyValueArray.
  25911. *
  25912. * This code is pulled out to a separate function so that it can be tree shaken away if it is not
  25913. * needed. It is only referenced from `ɵɵstyleMap`.
  25914. *
  25915. * @param keyValueArray KeyValueArray to add parsed values to.
  25916. * @param text text to parse.
  25917. */
  25918. function styleStringParser(keyValueArray, text) {
  25919. for (let i = parseStyle(text); i >= 0; i = parseStyleNext(text, i)) {
  25920. styleKeyValueArraySet(keyValueArray, getLastParsedKey(text), getLastParsedValue(text));
  25921. }
  25922. }
  25923. /**
  25924. * Update class bindings using an object literal or class-string on an element.
  25925. *
  25926. * This instruction is meant to apply styling via the `[class]="exp"` template bindings.
  25927. * When classes are applied to the element they will then be updated with
  25928. * respect to any styles/classes set via `classProp`. If any
  25929. * classes are set to falsy then they will be removed from the element.
  25930. *
  25931. * Note that the styling instruction will not be applied until `stylingApply` is called.
  25932. * Note that this will the provided classMap value to the host element if this function is called
  25933. * within a host binding.
  25934. *
  25935. * @param classes A key/value map or string of CSS classes that will be added to the
  25936. * given element. Any missing classes (that have already been applied to the element
  25937. * beforehand) will be removed (unset) from the element's list of CSS classes.
  25938. *
  25939. * @codeGenApi
  25940. */
  25941. function ɵɵclassMap(classes) {
  25942. checkStylingMap(classKeyValueArraySet, classStringParser, classes, true);
  25943. }
  25944. /**
  25945. * Parse text as class and add values to KeyValueArray.
  25946. *
  25947. * This code is pulled out to a separate function so that it can be tree shaken away if it is not
  25948. * needed. It is only referenced from `ɵɵclassMap`.
  25949. *
  25950. * @param keyValueArray KeyValueArray to add parsed values to.
  25951. * @param text text to parse.
  25952. */
  25953. function classStringParser(keyValueArray, text) {
  25954. for (let i = parseClassName(text); i >= 0; i = parseClassNameNext(text, i)) {
  25955. keyValueArraySet(keyValueArray, getLastParsedKey(text), true);
  25956. }
  25957. }
  25958. /**
  25959. * Common code between `ɵɵclassProp` and `ɵɵstyleProp`.
  25960. *
  25961. * @param prop property name.
  25962. * @param value binding value.
  25963. * @param suffix suffix for the property (e.g. `em` or `px`)
  25964. * @param isClassBased `true` if `class` change (`false` if `style`)
  25965. */
  25966. function checkStylingProperty(prop, value, suffix, isClassBased) {
  25967. const lView = getLView();
  25968. const tView = getTView();
  25969. // Styling instructions use 2 slots per binding.
  25970. // 1. one for the value / TStylingKey
  25971. // 2. one for the intermittent-value / TStylingRange
  25972. const bindingIndex = incrementBindingIndex(2);
  25973. if (tView.firstUpdatePass) {
  25974. stylingFirstUpdatePass(tView, prop, bindingIndex, isClassBased);
  25975. }
  25976. if (value !== NO_CHANGE && bindingUpdated(lView, bindingIndex, value)) {
  25977. const tNode = tView.data[getSelectedIndex()];
  25978. updateStyling(tView, tNode, lView, lView[RENDERER], prop, (lView[bindingIndex + 1] = normalizeSuffix(value, suffix)), isClassBased, bindingIndex);
  25979. }
  25980. }
  25981. /**
  25982. * Common code between `ɵɵclassMap` and `ɵɵstyleMap`.
  25983. *
  25984. * @param keyValueArraySet (See `keyValueArraySet` in "util/array_utils") Gets passed in as a
  25985. * function so that `style` can be processed. This is done for tree shaking purposes.
  25986. * @param stringParser Parser used to parse `value` if `string`. (Passed in as `style` and `class`
  25987. * have different parsers.)
  25988. * @param value bound value from application
  25989. * @param isClassBased `true` if `class` change (`false` if `style`)
  25990. */
  25991. function checkStylingMap(keyValueArraySet, stringParser, value, isClassBased) {
  25992. const tView = getTView();
  25993. const bindingIndex = incrementBindingIndex(2);
  25994. if (tView.firstUpdatePass) {
  25995. stylingFirstUpdatePass(tView, null, bindingIndex, isClassBased);
  25996. }
  25997. const lView = getLView();
  25998. if (value !== NO_CHANGE && bindingUpdated(lView, bindingIndex, value)) {
  25999. // `getSelectedIndex()` should be here (rather than in instruction) so that it is guarded by the
  26000. // if so as not to read unnecessarily.
  26001. const tNode = tView.data[getSelectedIndex()];
  26002. if (hasStylingInputShadow(tNode, isClassBased) && !isInHostBindings(tView, bindingIndex)) {
  26003. if (ngDevMode) {
  26004. // verify that if we are shadowing then `TData` is appropriately marked so that we skip
  26005. // processing this binding in styling resolution.
  26006. const tStylingKey = tView.data[bindingIndex];
  26007. assertEqual(Array.isArray(tStylingKey) ? tStylingKey[1] : tStylingKey, false, "Styling linked list shadow input should be marked as 'false'");
  26008. }
  26009. // VE does not concatenate the static portion like we are doing here.
  26010. // Instead VE just ignores the static completely if dynamic binding is present.
  26011. // Because of locality we have already set the static portion because we don't know if there
  26012. // is a dynamic portion until later. If we would ignore the static portion it would look like
  26013. // the binding has removed it. This would confuse `[ngStyle]`/`[ngClass]` to do the wrong
  26014. // thing as it would think that the static portion was removed. For this reason we
  26015. // concatenate it so that `[ngStyle]`/`[ngClass]` can continue to work on changed.
  26016. let staticPrefix = isClassBased ? tNode.classesWithoutHost : tNode.stylesWithoutHost;
  26017. ngDevMode &&
  26018. isClassBased === false &&
  26019. staticPrefix !== null &&
  26020. assertEqual(staticPrefix.endsWith(';'), true, "Expecting static portion to end with ';'");
  26021. if (staticPrefix !== null) {
  26022. // We want to make sure that falsy values of `value` become empty strings.
  26023. value = concatStringsWithSpace(staticPrefix, value ? value : '');
  26024. }
  26025. // Given `<div [style] my-dir>` such that `my-dir` has `@Input('style')`.
  26026. // This takes over the `[style]` binding. (Same for `[class]`)
  26027. setDirectiveInputsWhichShadowsStyling(tView, tNode, lView, value, isClassBased);
  26028. }
  26029. else {
  26030. updateStylingMap(tView, tNode, lView, lView[RENDERER], lView[bindingIndex + 1], (lView[bindingIndex + 1] = toStylingKeyValueArray(keyValueArraySet, stringParser, value)), isClassBased, bindingIndex);
  26031. }
  26032. }
  26033. }
  26034. /**
  26035. * Determines when the binding is in `hostBindings` section
  26036. *
  26037. * @param tView Current `TView`
  26038. * @param bindingIndex index of binding which we would like if it is in `hostBindings`
  26039. */
  26040. function isInHostBindings(tView, bindingIndex) {
  26041. // All host bindings are placed after the expando section.
  26042. return bindingIndex >= tView.expandoStartIndex;
  26043. }
  26044. /**
  26045. * Collects the necessary information to insert the binding into a linked list of style bindings
  26046. * using `insertTStylingBinding`.
  26047. *
  26048. * @param tView `TView` where the binding linked list will be stored.
  26049. * @param tStylingKey Property/key of the binding.
  26050. * @param bindingIndex Index of binding associated with the `prop`
  26051. * @param isClassBased `true` if `class` change (`false` if `style`)
  26052. */
  26053. function stylingFirstUpdatePass(tView, tStylingKey, bindingIndex, isClassBased) {
  26054. ngDevMode && assertFirstUpdatePass(tView);
  26055. const tData = tView.data;
  26056. if (tData[bindingIndex + 1] === null) {
  26057. // The above check is necessary because we don't clear first update pass until first successful
  26058. // (no exception) template execution. This prevents the styling instruction from double adding
  26059. // itself to the list.
  26060. // `getSelectedIndex()` should be here (rather than in instruction) so that it is guarded by the
  26061. // if so as not to read unnecessarily.
  26062. const tNode = tData[getSelectedIndex()];
  26063. ngDevMode && assertDefined(tNode, 'TNode expected');
  26064. const isHostBindings = isInHostBindings(tView, bindingIndex);
  26065. if (hasStylingInputShadow(tNode, isClassBased) && tStylingKey === null && !isHostBindings) {
  26066. // `tStylingKey === null` implies that we are either `[style]` or `[class]` binding.
  26067. // If there is a directive which uses `@Input('style')` or `@Input('class')` than
  26068. // we need to neutralize this binding since that directive is shadowing it.
  26069. // We turn this into a noop by setting the key to `false`
  26070. tStylingKey = false;
  26071. }
  26072. tStylingKey = wrapInStaticStylingKey(tData, tNode, tStylingKey, isClassBased);
  26073. insertTStylingBinding(tData, tNode, tStylingKey, bindingIndex, isHostBindings, isClassBased);
  26074. }
  26075. }
  26076. /**
  26077. * Adds static styling information to the binding if applicable.
  26078. *
  26079. * The linked list of styles not only stores the list and keys, but also stores static styling
  26080. * information on some of the keys. This function determines if the key should contain the styling
  26081. * information and computes it.
  26082. *
  26083. * See `TStylingStatic` for more details.
  26084. *
  26085. * @param tData `TData` where the linked list is stored.
  26086. * @param tNode `TNode` for which the styling is being computed.
  26087. * @param stylingKey `TStylingKeyPrimitive` which may need to be wrapped into `TStylingKey`
  26088. * @param isClassBased `true` if `class` (`false` if `style`)
  26089. */
  26090. function wrapInStaticStylingKey(tData, tNode, stylingKey, isClassBased) {
  26091. const hostDirectiveDef = getCurrentDirectiveDef(tData);
  26092. let residual = isClassBased ? tNode.residualClasses : tNode.residualStyles;
  26093. if (hostDirectiveDef === null) {
  26094. // We are in template node.
  26095. // If template node already had styling instruction then it has already collected the static
  26096. // styling and there is no need to collect them again. We know that we are the first styling
  26097. // instruction because the `TNode.*Bindings` points to 0 (nothing has been inserted yet).
  26098. const isFirstStylingInstructionInTemplate = (isClassBased ? tNode.classBindings : tNode.styleBindings) === 0;
  26099. if (isFirstStylingInstructionInTemplate) {
  26100. // It would be nice to be able to get the statics from `mergeAttrs`, however, at this point
  26101. // they are already merged and it would not be possible to figure which property belongs where
  26102. // in the priority.
  26103. stylingKey = collectStylingFromDirectives(null, tData, tNode, stylingKey, isClassBased);
  26104. stylingKey = collectStylingFromTAttrs(stylingKey, tNode.attrs, isClassBased);
  26105. // We know that if we have styling binding in template we can't have residual.
  26106. residual = null;
  26107. }
  26108. }
  26109. else {
  26110. // We are in host binding node and there was no binding instruction in template node.
  26111. // This means that we need to compute the residual.
  26112. const directiveStylingLast = tNode.directiveStylingLast;
  26113. const isFirstStylingInstructionInHostBinding = directiveStylingLast === -1 || tData[directiveStylingLast] !== hostDirectiveDef;
  26114. if (isFirstStylingInstructionInHostBinding) {
  26115. stylingKey = collectStylingFromDirectives(hostDirectiveDef, tData, tNode, stylingKey, isClassBased);
  26116. if (residual === null) {
  26117. // - If `null` than either:
  26118. // - Template styling instruction already ran and it has consumed the static
  26119. // styling into its `TStylingKey` and so there is no need to update residual. Instead
  26120. // we need to update the `TStylingKey` associated with the first template node
  26121. // instruction. OR
  26122. // - Some other styling instruction ran and determined that there are no residuals
  26123. let templateStylingKey = getTemplateHeadTStylingKey(tData, tNode, isClassBased);
  26124. if (templateStylingKey !== undefined && Array.isArray(templateStylingKey)) {
  26125. // Only recompute if `templateStylingKey` had static values. (If no static value found
  26126. // then there is nothing to do since this operation can only produce less static keys, not
  26127. // more.)
  26128. templateStylingKey = collectStylingFromDirectives(null, tData, tNode, templateStylingKey[1] /* unwrap previous statics */, isClassBased);
  26129. templateStylingKey = collectStylingFromTAttrs(templateStylingKey, tNode.attrs, isClassBased);
  26130. setTemplateHeadTStylingKey(tData, tNode, isClassBased, templateStylingKey);
  26131. }
  26132. }
  26133. else {
  26134. // We only need to recompute residual if it is not `null`.
  26135. // - If existing residual (implies there was no template styling). This means that some of
  26136. // the statics may have moved from the residual to the `stylingKey` and so we have to
  26137. // recompute.
  26138. // - If `undefined` this is the first time we are running.
  26139. residual = collectResidual(tData, tNode, isClassBased);
  26140. }
  26141. }
  26142. }
  26143. if (residual !== undefined) {
  26144. isClassBased ? (tNode.residualClasses = residual) : (tNode.residualStyles = residual);
  26145. }
  26146. return stylingKey;
  26147. }
  26148. /**
  26149. * Retrieve the `TStylingKey` for the template styling instruction.
  26150. *
  26151. * This is needed since `hostBinding` styling instructions are inserted after the template
  26152. * instruction. While the template instruction needs to update the residual in `TNode` the
  26153. * `hostBinding` instructions need to update the `TStylingKey` of the template instruction because
  26154. * the template instruction is downstream from the `hostBindings` instructions.
  26155. *
  26156. * @param tData `TData` where the linked list is stored.
  26157. * @param tNode `TNode` for which the styling is being computed.
  26158. * @param isClassBased `true` if `class` (`false` if `style`)
  26159. * @return `TStylingKey` if found or `undefined` if not found.
  26160. */
  26161. function getTemplateHeadTStylingKey(tData, tNode, isClassBased) {
  26162. const bindings = isClassBased ? tNode.classBindings : tNode.styleBindings;
  26163. if (getTStylingRangeNext(bindings) === 0) {
  26164. // There does not seem to be a styling instruction in the `template`.
  26165. return undefined;
  26166. }
  26167. return tData[getTStylingRangePrev(bindings)];
  26168. }
  26169. /**
  26170. * Update the `TStylingKey` of the first template instruction in `TNode`.
  26171. *
  26172. * Logically `hostBindings` styling instructions are of lower priority than that of the template.
  26173. * However, they execute after the template styling instructions. This means that they get inserted
  26174. * in front of the template styling instructions.
  26175. *
  26176. * If we have a template styling instruction and a new `hostBindings` styling instruction is
  26177. * executed it means that it may need to steal static fields from the template instruction. This
  26178. * method allows us to update the first template instruction `TStylingKey` with a new value.
  26179. *
  26180. * Assume:
  26181. * ```angular-ts
  26182. * <div my-dir style="color: red" [style.color]="tmplExp"></div>
  26183. *
  26184. * @Directive({
  26185. * host: {
  26186. * 'style': 'width: 100px',
  26187. * '[style.color]': 'dirExp',
  26188. * }
  26189. * })
  26190. * class MyDir {}
  26191. * ```
  26192. *
  26193. * when `[style.color]="tmplExp"` executes it creates this data structure.
  26194. * ```ts
  26195. * ['', 'color', 'color', 'red', 'width', '100px'],
  26196. * ```
  26197. *
  26198. * The reason for this is that the template instruction does not know if there are styling
  26199. * instructions and must assume that there are none and must collect all of the static styling.
  26200. * (both
  26201. * `color' and 'width`)
  26202. *
  26203. * When `'[style.color]': 'dirExp',` executes we need to insert a new data into the linked list.
  26204. * ```ts
  26205. * ['', 'color', 'width', '100px'], // newly inserted
  26206. * ['', 'color', 'color', 'red', 'width', '100px'], // this is wrong
  26207. * ```
  26208. *
  26209. * Notice that the template statics is now wrong as it incorrectly contains `width` so we need to
  26210. * update it like so:
  26211. * ```ts
  26212. * ['', 'color', 'width', '100px'],
  26213. * ['', 'color', 'color', 'red'], // UPDATE
  26214. * ```
  26215. *
  26216. * @param tData `TData` where the linked list is stored.
  26217. * @param tNode `TNode` for which the styling is being computed.
  26218. * @param isClassBased `true` if `class` (`false` if `style`)
  26219. * @param tStylingKey New `TStylingKey` which is replacing the old one.
  26220. */
  26221. function setTemplateHeadTStylingKey(tData, tNode, isClassBased, tStylingKey) {
  26222. const bindings = isClassBased ? tNode.classBindings : tNode.styleBindings;
  26223. ngDevMode &&
  26224. assertNotEqual(getTStylingRangeNext(bindings), 0, 'Expecting to have at least one template styling binding.');
  26225. tData[getTStylingRangePrev(bindings)] = tStylingKey;
  26226. }
  26227. /**
  26228. * Collect all static values after the current `TNode.directiveStylingLast` index.
  26229. *
  26230. * Collect the remaining styling information which has not yet been collected by an existing
  26231. * styling instruction.
  26232. *
  26233. * @param tData `TData` where the `DirectiveDefs` are stored.
  26234. * @param tNode `TNode` which contains the directive range.
  26235. * @param isClassBased `true` if `class` (`false` if `style`)
  26236. */
  26237. function collectResidual(tData, tNode, isClassBased) {
  26238. let residual = undefined;
  26239. const directiveEnd = tNode.directiveEnd;
  26240. ngDevMode &&
  26241. assertNotEqual(tNode.directiveStylingLast, -1, 'By the time this function gets called at least one hostBindings-node styling instruction must have executed.');
  26242. // We add `1 + tNode.directiveStart` because we need to skip the current directive (as we are
  26243. // collecting things after the last `hostBindings` directive which had a styling instruction.)
  26244. for (let i = 1 + tNode.directiveStylingLast; i < directiveEnd; i++) {
  26245. const attrs = tData[i].hostAttrs;
  26246. residual = collectStylingFromTAttrs(residual, attrs, isClassBased);
  26247. }
  26248. return collectStylingFromTAttrs(residual, tNode.attrs, isClassBased);
  26249. }
  26250. /**
  26251. * Collect the static styling information with lower priority than `hostDirectiveDef`.
  26252. *
  26253. * (This is opposite of residual styling.)
  26254. *
  26255. * @param hostDirectiveDef `DirectiveDef` for which we want to collect lower priority static
  26256. * styling. (Or `null` if template styling)
  26257. * @param tData `TData` where the linked list is stored.
  26258. * @param tNode `TNode` for which the styling is being computed.
  26259. * @param stylingKey Existing `TStylingKey` to update or wrap.
  26260. * @param isClassBased `true` if `class` (`false` if `style`)
  26261. */
  26262. function collectStylingFromDirectives(hostDirectiveDef, tData, tNode, stylingKey, isClassBased) {
  26263. // We need to loop because there can be directives which have `hostAttrs` but don't have
  26264. // `hostBindings` so this loop catches up to the current directive..
  26265. let currentDirective = null;
  26266. const directiveEnd = tNode.directiveEnd;
  26267. let directiveStylingLast = tNode.directiveStylingLast;
  26268. if (directiveStylingLast === -1) {
  26269. directiveStylingLast = tNode.directiveStart;
  26270. }
  26271. else {
  26272. directiveStylingLast++;
  26273. }
  26274. while (directiveStylingLast < directiveEnd) {
  26275. currentDirective = tData[directiveStylingLast];
  26276. ngDevMode && assertDefined(currentDirective, 'expected to be defined');
  26277. stylingKey = collectStylingFromTAttrs(stylingKey, currentDirective.hostAttrs, isClassBased);
  26278. if (currentDirective === hostDirectiveDef)
  26279. break;
  26280. directiveStylingLast++;
  26281. }
  26282. if (hostDirectiveDef !== null) {
  26283. // we only advance the styling cursor if we are collecting data from host bindings.
  26284. // Template executes before host bindings and so if we would update the index,
  26285. // host bindings would not get their statics.
  26286. tNode.directiveStylingLast = directiveStylingLast;
  26287. }
  26288. return stylingKey;
  26289. }
  26290. /**
  26291. * Convert `TAttrs` into `TStylingStatic`.
  26292. *
  26293. * @param stylingKey existing `TStylingKey` to update or wrap.
  26294. * @param attrs `TAttributes` to process.
  26295. * @param isClassBased `true` if `class` (`false` if `style`)
  26296. */
  26297. function collectStylingFromTAttrs(stylingKey, attrs, isClassBased) {
  26298. const desiredMarker = isClassBased ? 1 /* AttributeMarker.Classes */ : 2 /* AttributeMarker.Styles */;
  26299. let currentMarker = -1 /* AttributeMarker.ImplicitAttributes */;
  26300. if (attrs !== null) {
  26301. for (let i = 0; i < attrs.length; i++) {
  26302. const item = attrs[i];
  26303. if (typeof item === 'number') {
  26304. currentMarker = item;
  26305. }
  26306. else {
  26307. if (currentMarker === desiredMarker) {
  26308. if (!Array.isArray(stylingKey)) {
  26309. stylingKey = stylingKey === undefined ? [] : ['', stylingKey];
  26310. }
  26311. keyValueArraySet(stylingKey, item, isClassBased ? true : attrs[++i]);
  26312. }
  26313. }
  26314. }
  26315. }
  26316. return stylingKey === undefined ? null : stylingKey;
  26317. }
  26318. /**
  26319. * Convert user input to `KeyValueArray`.
  26320. *
  26321. * This function takes user input which could be `string`, Object literal, or iterable and converts
  26322. * it into a consistent representation. The output of this is `KeyValueArray` (which is an array
  26323. * where
  26324. * even indexes contain keys and odd indexes contain values for those keys).
  26325. *
  26326. * The advantage of converting to `KeyValueArray` is that we can perform diff in an input
  26327. * independent
  26328. * way.
  26329. * (ie we can compare `foo bar` to `['bar', 'baz'] and determine a set of changes which need to be
  26330. * applied)
  26331. *
  26332. * The fact that `KeyValueArray` is sorted is very important because it allows us to compute the
  26333. * difference in linear fashion without the need to allocate any additional data.
  26334. *
  26335. * For example if we kept this as a `Map` we would have to iterate over previous `Map` to determine
  26336. * which values need to be deleted, over the new `Map` to determine additions, and we would have to
  26337. * keep additional `Map` to keep track of duplicates or items which have not yet been visited.
  26338. *
  26339. * @param keyValueArraySet (See `keyValueArraySet` in "util/array_utils") Gets passed in as a
  26340. * function so that `style` can be processed. This is done
  26341. * for tree shaking purposes.
  26342. * @param stringParser The parser is passed in so that it will be tree shakable. See
  26343. * `styleStringParser` and `classStringParser`
  26344. * @param value The value to parse/convert to `KeyValueArray`
  26345. */
  26346. function toStylingKeyValueArray(keyValueArraySet, stringParser, value) {
  26347. if (value == null /*|| value === undefined */ || value === '')
  26348. return EMPTY_ARRAY;
  26349. const styleKeyValueArray = [];
  26350. const unwrappedValue = unwrapSafeValue(value);
  26351. if (Array.isArray(unwrappedValue)) {
  26352. for (let i = 0; i < unwrappedValue.length; i++) {
  26353. keyValueArraySet(styleKeyValueArray, unwrappedValue[i], true);
  26354. }
  26355. }
  26356. else if (typeof unwrappedValue === 'object') {
  26357. for (const key in unwrappedValue) {
  26358. if (unwrappedValue.hasOwnProperty(key)) {
  26359. keyValueArraySet(styleKeyValueArray, key, unwrappedValue[key]);
  26360. }
  26361. }
  26362. }
  26363. else if (typeof unwrappedValue === 'string') {
  26364. stringParser(styleKeyValueArray, unwrappedValue);
  26365. }
  26366. else {
  26367. ngDevMode &&
  26368. throwError('Unsupported styling type ' + typeof unwrappedValue + ': ' + unwrappedValue);
  26369. }
  26370. return styleKeyValueArray;
  26371. }
  26372. /**
  26373. * Set a `value` for a `key`.
  26374. *
  26375. * See: `keyValueArraySet` for details
  26376. *
  26377. * @param keyValueArray KeyValueArray to add to.
  26378. * @param key Style key to add.
  26379. * @param value The value to set.
  26380. */
  26381. function styleKeyValueArraySet(keyValueArray, key, value) {
  26382. keyValueArraySet(keyValueArray, key, unwrapSafeValue(value));
  26383. }
  26384. /**
  26385. * Class-binding-specific function for setting the `value` for a `key`.
  26386. *
  26387. * See: `keyValueArraySet` for details
  26388. *
  26389. * @param keyValueArray KeyValueArray to add to.
  26390. * @param key Style key to add.
  26391. * @param value The value to set.
  26392. */
  26393. function classKeyValueArraySet(keyValueArray, key, value) {
  26394. // We use `classList.add` to eventually add the CSS classes to the DOM node. Any value passed into
  26395. // `add` is stringified and added to the `class` attribute, e.g. even null, undefined or numbers
  26396. // will be added. Stringify the key here so that our internal data structure matches the value in
  26397. // the DOM. The only exceptions are empty strings and strings that contain spaces for which
  26398. // the browser throws an error. We ignore such values, because the error is somewhat cryptic.
  26399. const stringKey = String(key);
  26400. if (stringKey !== '' && !stringKey.includes(' ')) {
  26401. keyValueArraySet(keyValueArray, stringKey, value);
  26402. }
  26403. }
  26404. /**
  26405. * Update map based styling.
  26406. *
  26407. * Map based styling could be anything which contains more than one binding. For example `string`,
  26408. * or object literal. Dealing with all of these types would complicate the logic so
  26409. * instead this function expects that the complex input is first converted into normalized
  26410. * `KeyValueArray`. The advantage of normalization is that we get the values sorted, which makes it
  26411. * very cheap to compute deltas between the previous and current value.
  26412. *
  26413. * @param tView Associated `TView.data` contains the linked list of binding priorities.
  26414. * @param tNode `TNode` where the binding is located.
  26415. * @param lView `LView` contains the values associated with other styling binding at this `TNode`.
  26416. * @param renderer Renderer to use if any updates.
  26417. * @param oldKeyValueArray Previous value represented as `KeyValueArray`
  26418. * @param newKeyValueArray Current value represented as `KeyValueArray`
  26419. * @param isClassBased `true` if `class` (`false` if `style`)
  26420. * @param bindingIndex Binding index of the binding.
  26421. */
  26422. function updateStylingMap(tView, tNode, lView, renderer, oldKeyValueArray, newKeyValueArray, isClassBased, bindingIndex) {
  26423. if (oldKeyValueArray === NO_CHANGE) {
  26424. // On first execution the oldKeyValueArray is NO_CHANGE => treat it as empty KeyValueArray.
  26425. oldKeyValueArray = EMPTY_ARRAY;
  26426. }
  26427. let oldIndex = 0;
  26428. let newIndex = 0;
  26429. let oldKey = 0 < oldKeyValueArray.length ? oldKeyValueArray[0] : null;
  26430. let newKey = 0 < newKeyValueArray.length ? newKeyValueArray[0] : null;
  26431. while (oldKey !== null || newKey !== null) {
  26432. ngDevMode && assertLessThan(oldIndex, 999, 'Are we stuck in infinite loop?');
  26433. ngDevMode && assertLessThan(newIndex, 999, 'Are we stuck in infinite loop?');
  26434. const oldValue = oldIndex < oldKeyValueArray.length ? oldKeyValueArray[oldIndex + 1] : undefined;
  26435. const newValue = newIndex < newKeyValueArray.length ? newKeyValueArray[newIndex + 1] : undefined;
  26436. let setKey = null;
  26437. let setValue = undefined;
  26438. if (oldKey === newKey) {
  26439. // UPDATE: Keys are equal => new value is overwriting old value.
  26440. oldIndex += 2;
  26441. newIndex += 2;
  26442. if (oldValue !== newValue) {
  26443. setKey = newKey;
  26444. setValue = newValue;
  26445. }
  26446. }
  26447. else if (newKey === null || (oldKey !== null && oldKey < newKey)) {
  26448. // DELETE: oldKey key is missing or we did not find the oldKey in the newValue
  26449. // (because the keyValueArray is sorted and `newKey` is found later alphabetically).
  26450. // `"background" < "color"` so we need to delete `"background"` because it is not found in the
  26451. // new array.
  26452. oldIndex += 2;
  26453. setKey = oldKey;
  26454. }
  26455. else {
  26456. // CREATE: newKey's is earlier alphabetically than oldKey's (or no oldKey) => we have new key.
  26457. // `"color" > "background"` so we need to add `color` because it is in new array but not in
  26458. // old array.
  26459. ngDevMode && assertDefined(newKey, 'Expecting to have a valid key');
  26460. newIndex += 2;
  26461. setKey = newKey;
  26462. setValue = newValue;
  26463. }
  26464. if (setKey !== null) {
  26465. updateStyling(tView, tNode, lView, renderer, setKey, setValue, isClassBased, bindingIndex);
  26466. }
  26467. oldKey = oldIndex < oldKeyValueArray.length ? oldKeyValueArray[oldIndex] : null;
  26468. newKey = newIndex < newKeyValueArray.length ? newKeyValueArray[newIndex] : null;
  26469. }
  26470. }
  26471. /**
  26472. * Update a simple (property name) styling.
  26473. *
  26474. * This function takes `prop` and updates the DOM to that value. The function takes the binding
  26475. * value as well as binding priority into consideration to determine which value should be written
  26476. * to DOM. (For example it may be determined that there is a higher priority overwrite which blocks
  26477. * the DOM write, or if the value goes to `undefined` a lower priority overwrite may be consulted.)
  26478. *
  26479. * @param tView Associated `TView.data` contains the linked list of binding priorities.
  26480. * @param tNode `TNode` where the binding is located.
  26481. * @param lView `LView` contains the values associated with other styling binding at this `TNode`.
  26482. * @param renderer Renderer to use if any updates.
  26483. * @param prop Either style property name or a class name.
  26484. * @param value Either style value for `prop` or `true`/`false` if `prop` is class.
  26485. * @param isClassBased `true` if `class` (`false` if `style`)
  26486. * @param bindingIndex Binding index of the binding.
  26487. */
  26488. function updateStyling(tView, tNode, lView, renderer, prop, value, isClassBased, bindingIndex) {
  26489. if (!(tNode.type & 3 /* TNodeType.AnyRNode */)) {
  26490. // It is possible to have styling on non-elements (such as ng-container).
  26491. // This is rare, but it does happen. In such a case, just ignore the binding.
  26492. return;
  26493. }
  26494. const tData = tView.data;
  26495. const tRange = tData[bindingIndex + 1];
  26496. const higherPriorityValue = getTStylingRangeNextDuplicate(tRange)
  26497. ? findStylingValue(tData, tNode, lView, prop, getTStylingRangeNext(tRange), isClassBased)
  26498. : undefined;
  26499. if (!isStylingValuePresent(higherPriorityValue)) {
  26500. // We don't have a next duplicate, or we did not find a duplicate value.
  26501. if (!isStylingValuePresent(value)) {
  26502. // We should delete current value or restore to lower priority value.
  26503. if (getTStylingRangePrevDuplicate(tRange)) {
  26504. // We have a possible prev duplicate, let's retrieve it.
  26505. value = findStylingValue(tData, null, lView, prop, bindingIndex, isClassBased);
  26506. }
  26507. }
  26508. const rNode = getNativeByIndex(getSelectedIndex(), lView);
  26509. applyStyling(renderer, isClassBased, rNode, prop, value);
  26510. }
  26511. }
  26512. /**
  26513. * Search for styling value with higher priority which is overwriting current value, or a
  26514. * value of lower priority to which we should fall back if the value is `undefined`.
  26515. *
  26516. * When value is being applied at a location, related values need to be consulted.
  26517. * - If there is a higher priority binding, we should be using that one instead.
  26518. * For example `<div [style]="{color:exp1}" [style.color]="exp2">` change to `exp1`
  26519. * requires that we check `exp2` to see if it is set to value other than `undefined`.
  26520. * - If there is a lower priority binding and we are changing to `undefined`
  26521. * For example `<div [style]="{color:exp1}" [style.color]="exp2">` change to `exp2` to
  26522. * `undefined` requires that we check `exp1` (and static values) and use that as new value.
  26523. *
  26524. * NOTE: The styling stores two values.
  26525. * 1. The raw value which came from the application is stored at `index + 0` location. (This value
  26526. * is used for dirty checking).
  26527. * 2. The normalized value is stored at `index + 1`.
  26528. *
  26529. * @param tData `TData` used for traversing the priority.
  26530. * @param tNode `TNode` to use for resolving static styling. Also controls search direction.
  26531. * - `TNode` search next and quit as soon as `isStylingValuePresent(value)` is true.
  26532. * If no value found consult `tNode.residualStyle`/`tNode.residualClass` for default value.
  26533. * - `null` search prev and go all the way to end. Return last value where
  26534. * `isStylingValuePresent(value)` is true.
  26535. * @param lView `LView` used for retrieving the actual values.
  26536. * @param prop Property which we are interested in.
  26537. * @param index Starting index in the linked list of styling bindings where the search should start.
  26538. * @param isClassBased `true` if `class` (`false` if `style`)
  26539. */
  26540. function findStylingValue(tData, tNode, lView, prop, index, isClassBased) {
  26541. // `TNode` to use for resolving static styling. Also controls search direction.
  26542. // - `TNode` search next and quit as soon as `isStylingValuePresent(value)` is true.
  26543. // If no value found consult `tNode.residualStyle`/`tNode.residualClass` for default value.
  26544. // - `null` search prev and go all the way to end. Return last value where
  26545. // `isStylingValuePresent(value)` is true.
  26546. const isPrevDirection = tNode === null;
  26547. let value = undefined;
  26548. while (index > 0) {
  26549. const rawKey = tData[index];
  26550. const containsStatics = Array.isArray(rawKey);
  26551. // Unwrap the key if we contain static values.
  26552. const key = containsStatics ? rawKey[1] : rawKey;
  26553. const isStylingMap = key === null;
  26554. let valueAtLViewIndex = lView[index + 1];
  26555. if (valueAtLViewIndex === NO_CHANGE) {
  26556. // In firstUpdatePass the styling instructions create a linked list of styling.
  26557. // On subsequent passes it is possible for a styling instruction to try to read a binding
  26558. // which
  26559. // has not yet executed. In that case we will find `NO_CHANGE` and we should assume that
  26560. // we have `undefined` (or empty array in case of styling-map instruction) instead. This
  26561. // allows the resolution to apply the value (which may later be overwritten when the
  26562. // binding actually executes.)
  26563. valueAtLViewIndex = isStylingMap ? EMPTY_ARRAY : undefined;
  26564. }
  26565. let currentValue = isStylingMap
  26566. ? keyValueArrayGet(valueAtLViewIndex, prop)
  26567. : key === prop
  26568. ? valueAtLViewIndex
  26569. : undefined;
  26570. if (containsStatics && !isStylingValuePresent(currentValue)) {
  26571. currentValue = keyValueArrayGet(rawKey, prop);
  26572. }
  26573. if (isStylingValuePresent(currentValue)) {
  26574. value = currentValue;
  26575. if (isPrevDirection) {
  26576. return value;
  26577. }
  26578. }
  26579. const tRange = tData[index + 1];
  26580. index = isPrevDirection ? getTStylingRangePrev(tRange) : getTStylingRangeNext(tRange);
  26581. }
  26582. if (tNode !== null) {
  26583. // in case where we are going in next direction AND we did not find anything, we need to
  26584. // consult residual styling
  26585. let residual = isClassBased ? tNode.residualClasses : tNode.residualStyles;
  26586. if (residual != null /** OR residual !=== undefined */) {
  26587. value = keyValueArrayGet(residual, prop);
  26588. }
  26589. }
  26590. return value;
  26591. }
  26592. /**
  26593. * Determines if the binding value should be used (or if the value is 'undefined' and hence priority
  26594. * resolution should be used.)
  26595. *
  26596. * @param value Binding style value.
  26597. */
  26598. function isStylingValuePresent(value) {
  26599. // Currently only `undefined` value is considered non-binding. That is `undefined` says I don't
  26600. // have an opinion as to what this binding should be and you should consult other bindings by
  26601. // priority to determine the valid value.
  26602. // This is extracted into a single function so that we have a single place to control this.
  26603. return value !== undefined;
  26604. }
  26605. /**
  26606. * Normalizes and/or adds a suffix to the value.
  26607. *
  26608. * If value is `null`/`undefined` no suffix is added
  26609. * @param value
  26610. * @param suffix
  26611. */
  26612. function normalizeSuffix(value, suffix) {
  26613. if (value == null || value === '') ;
  26614. else if (typeof suffix === 'string') {
  26615. value = value + suffix;
  26616. }
  26617. else if (typeof value === 'object') {
  26618. value = stringify(unwrapSafeValue(value));
  26619. }
  26620. return value;
  26621. }
  26622. /**
  26623. * Tests if the `TNode` has input shadow.
  26624. *
  26625. * An input shadow is when a directive steals (shadows) the input by using `@Input('style')` or
  26626. * `@Input('class')` as input.
  26627. *
  26628. * @param tNode `TNode` which we would like to see if it has shadow.
  26629. * @param isClassBased `true` if `class` (`false` if `style`)
  26630. */
  26631. function hasStylingInputShadow(tNode, isClassBased) {
  26632. return (tNode.flags & (isClassBased ? 8 /* TNodeFlags.hasClassInput */ : 16 /* TNodeFlags.hasStyleInput */)) !== 0;
  26633. }
  26634. /**
  26635. *
  26636. * Update an interpolated class on an element with single bound value surrounded by text.
  26637. *
  26638. * Used when the value passed to a property has 1 interpolated value in it:
  26639. *
  26640. * ```html
  26641. * <div class="prefix{{v0}}suffix"></div>
  26642. * ```
  26643. *
  26644. * Its compiled representation is:
  26645. *
  26646. * ```ts
  26647. * ɵɵclassMapInterpolate1('prefix', v0, 'suffix');
  26648. * ```
  26649. *
  26650. * @param prefix Static value used for concatenation only.
  26651. * @param v0 Value checked for change.
  26652. * @param suffix Static value used for concatenation only.
  26653. * @codeGenApi
  26654. */
  26655. function ɵɵclassMapInterpolate1(prefix, v0, suffix) {
  26656. const lView = getLView();
  26657. const interpolatedValue = interpolation1(lView, prefix, v0, suffix);
  26658. checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
  26659. }
  26660. /**
  26661. *
  26662. * Update an interpolated class on an element with 2 bound values surrounded by text.
  26663. *
  26664. * Used when the value passed to a property has 2 interpolated values in it:
  26665. *
  26666. * ```html
  26667. * <div class="prefix{{v0}}-{{v1}}suffix"></div>
  26668. * ```
  26669. *
  26670. * Its compiled representation is:
  26671. *
  26672. * ```ts
  26673. * ɵɵclassMapInterpolate2('prefix', v0, '-', v1, 'suffix');
  26674. * ```
  26675. *
  26676. * @param prefix Static value used for concatenation only.
  26677. * @param v0 Value checked for change.
  26678. * @param i0 Static value used for concatenation only.
  26679. * @param v1 Value checked for change.
  26680. * @param suffix Static value used for concatenation only.
  26681. * @codeGenApi
  26682. */
  26683. function ɵɵclassMapInterpolate2(prefix, v0, i0, v1, suffix) {
  26684. const lView = getLView();
  26685. const interpolatedValue = interpolation2(lView, prefix, v0, i0, v1, suffix);
  26686. checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
  26687. }
  26688. /**
  26689. *
  26690. * Update an interpolated class on an element with 3 bound values surrounded by text.
  26691. *
  26692. * Used when the value passed to a property has 3 interpolated values in it:
  26693. *
  26694. * ```html
  26695. * <div class="prefix{{v0}}-{{v1}}-{{v2}}suffix"></div>
  26696. * ```
  26697. *
  26698. * Its compiled representation is:
  26699. *
  26700. * ```ts
  26701. * ɵɵclassMapInterpolate3(
  26702. * 'prefix', v0, '-', v1, '-', v2, 'suffix');
  26703. * ```
  26704. *
  26705. * @param prefix Static value used for concatenation only.
  26706. * @param v0 Value checked for change.
  26707. * @param i0 Static value used for concatenation only.
  26708. * @param v1 Value checked for change.
  26709. * @param i1 Static value used for concatenation only.
  26710. * @param v2 Value checked for change.
  26711. * @param suffix Static value used for concatenation only.
  26712. * @codeGenApi
  26713. */
  26714. function ɵɵclassMapInterpolate3(prefix, v0, i0, v1, i1, v2, suffix) {
  26715. const lView = getLView();
  26716. const interpolatedValue = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix);
  26717. checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
  26718. }
  26719. /**
  26720. *
  26721. * Update an interpolated class on an element with 4 bound values surrounded by text.
  26722. *
  26723. * Used when the value passed to a property has 4 interpolated values in it:
  26724. *
  26725. * ```html
  26726. * <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}suffix"></div>
  26727. * ```
  26728. *
  26729. * Its compiled representation is:
  26730. *
  26731. * ```ts
  26732. * ɵɵclassMapInterpolate4(
  26733. * 'prefix', v0, '-', v1, '-', v2, '-', v3, 'suffix');
  26734. * ```
  26735. *
  26736. * @param prefix Static value used for concatenation only.
  26737. * @param v0 Value checked for change.
  26738. * @param i0 Static value used for concatenation only.
  26739. * @param v1 Value checked for change.
  26740. * @param i1 Static value used for concatenation only.
  26741. * @param v2 Value checked for change.
  26742. * @param i2 Static value used for concatenation only.
  26743. * @param v3 Value checked for change.
  26744. * @param suffix Static value used for concatenation only.
  26745. * @codeGenApi
  26746. */
  26747. function ɵɵclassMapInterpolate4(prefix, v0, i0, v1, i1, v2, i2, v3, suffix) {
  26748. const lView = getLView();
  26749. const interpolatedValue = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix);
  26750. checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
  26751. }
  26752. /**
  26753. *
  26754. * Update an interpolated class on an element with 5 bound values surrounded by text.
  26755. *
  26756. * Used when the value passed to a property has 5 interpolated values in it:
  26757. *
  26758. * ```html
  26759. * <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}suffix"></div>
  26760. * ```
  26761. *
  26762. * Its compiled representation is:
  26763. *
  26764. * ```ts
  26765. * ɵɵclassMapInterpolate5(
  26766. * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, 'suffix');
  26767. * ```
  26768. *
  26769. * @param prefix Static value used for concatenation only.
  26770. * @param v0 Value checked for change.
  26771. * @param i0 Static value used for concatenation only.
  26772. * @param v1 Value checked for change.
  26773. * @param i1 Static value used for concatenation only.
  26774. * @param v2 Value checked for change.
  26775. * @param i2 Static value used for concatenation only.
  26776. * @param v3 Value checked for change.
  26777. * @param i3 Static value used for concatenation only.
  26778. * @param v4 Value checked for change.
  26779. * @param suffix Static value used for concatenation only.
  26780. * @codeGenApi
  26781. */
  26782. function ɵɵclassMapInterpolate5(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix) {
  26783. const lView = getLView();
  26784. const interpolatedValue = interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix);
  26785. checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
  26786. }
  26787. /**
  26788. *
  26789. * Update an interpolated class on an element with 6 bound values surrounded by text.
  26790. *
  26791. * Used when the value passed to a property has 6 interpolated values in it:
  26792. *
  26793. * ```html
  26794. * <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}suffix"></div>
  26795. * ```
  26796. *
  26797. * Its compiled representation is:
  26798. *
  26799. * ```ts
  26800. * ɵɵclassMapInterpolate6(
  26801. * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, 'suffix');
  26802. * ```
  26803. *
  26804. * @param prefix Static value used for concatenation only.
  26805. * @param v0 Value checked for change.
  26806. * @param i0 Static value used for concatenation only.
  26807. * @param v1 Value checked for change.
  26808. * @param i1 Static value used for concatenation only.
  26809. * @param v2 Value checked for change.
  26810. * @param i2 Static value used for concatenation only.
  26811. * @param v3 Value checked for change.
  26812. * @param i3 Static value used for concatenation only.
  26813. * @param v4 Value checked for change.
  26814. * @param i4 Static value used for concatenation only.
  26815. * @param v5 Value checked for change.
  26816. * @param suffix Static value used for concatenation only.
  26817. * @codeGenApi
  26818. */
  26819. function ɵɵclassMapInterpolate6(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix) {
  26820. const lView = getLView();
  26821. const interpolatedValue = interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix);
  26822. checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
  26823. }
  26824. /**
  26825. *
  26826. * Update an interpolated class on an element with 7 bound values surrounded by text.
  26827. *
  26828. * Used when the value passed to a property has 7 interpolated values in it:
  26829. *
  26830. * ```html
  26831. * <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}suffix"></div>
  26832. * ```
  26833. *
  26834. * Its compiled representation is:
  26835. *
  26836. * ```ts
  26837. * ɵɵclassMapInterpolate7(
  26838. * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, 'suffix');
  26839. * ```
  26840. *
  26841. * @param prefix Static value used for concatenation only.
  26842. * @param v0 Value checked for change.
  26843. * @param i0 Static value used for concatenation only.
  26844. * @param v1 Value checked for change.
  26845. * @param i1 Static value used for concatenation only.
  26846. * @param v2 Value checked for change.
  26847. * @param i2 Static value used for concatenation only.
  26848. * @param v3 Value checked for change.
  26849. * @param i3 Static value used for concatenation only.
  26850. * @param v4 Value checked for change.
  26851. * @param i4 Static value used for concatenation only.
  26852. * @param v5 Value checked for change.
  26853. * @param i5 Static value used for concatenation only.
  26854. * @param v6 Value checked for change.
  26855. * @param suffix Static value used for concatenation only.
  26856. * @codeGenApi
  26857. */
  26858. function ɵɵclassMapInterpolate7(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix) {
  26859. const lView = getLView();
  26860. const interpolatedValue = interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix);
  26861. checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
  26862. }
  26863. /**
  26864. *
  26865. * Update an interpolated class on an element with 8 bound values surrounded by text.
  26866. *
  26867. * Used when the value passed to a property has 8 interpolated values in it:
  26868. *
  26869. * ```html
  26870. * <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}suffix"></div>
  26871. * ```
  26872. *
  26873. * Its compiled representation is:
  26874. *
  26875. * ```ts
  26876. * ɵɵclassMapInterpolate8(
  26877. * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, 'suffix');
  26878. * ```
  26879. *
  26880. * @param prefix Static value used for concatenation only.
  26881. * @param v0 Value checked for change.
  26882. * @param i0 Static value used for concatenation only.
  26883. * @param v1 Value checked for change.
  26884. * @param i1 Static value used for concatenation only.
  26885. * @param v2 Value checked for change.
  26886. * @param i2 Static value used for concatenation only.
  26887. * @param v3 Value checked for change.
  26888. * @param i3 Static value used for concatenation only.
  26889. * @param v4 Value checked for change.
  26890. * @param i4 Static value used for concatenation only.
  26891. * @param v5 Value checked for change.
  26892. * @param i5 Static value used for concatenation only.
  26893. * @param v6 Value checked for change.
  26894. * @param i6 Static value used for concatenation only.
  26895. * @param v7 Value checked for change.
  26896. * @param suffix Static value used for concatenation only.
  26897. * @codeGenApi
  26898. */
  26899. function ɵɵclassMapInterpolate8(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix) {
  26900. const lView = getLView();
  26901. const interpolatedValue = interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix);
  26902. checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
  26903. }
  26904. /**
  26905. * Update an interpolated class on an element with 9 or more bound values surrounded by text.
  26906. *
  26907. * Used when the number of interpolated values exceeds 8.
  26908. *
  26909. * ```html
  26910. * <div
  26911. * class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}-{{v8}}-{{v9}}suffix"></div>
  26912. * ```
  26913. *
  26914. * Its compiled representation is:
  26915. *
  26916. * ```ts
  26917. * ɵɵclassMapInterpolateV(
  26918. * ['prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, '-', v9,
  26919. * 'suffix']);
  26920. * ```
  26921. *.
  26922. * @param values The collection of values and the strings in-between those values, beginning with
  26923. * a string prefix and ending with a string suffix.
  26924. * (e.g. `['prefix', value0, '-', value1, '-', value2, ..., value99, 'suffix']`)
  26925. * @codeGenApi
  26926. */
  26927. function ɵɵclassMapInterpolateV(values) {
  26928. const lView = getLView();
  26929. const interpolatedValue = interpolationV(lView, values);
  26930. checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
  26931. }
  26932. /*!
  26933. * @license
  26934. * Copyright Google LLC All Rights Reserved.
  26935. *
  26936. * Use of this source code is governed by an MIT-style license that can be
  26937. * found in the LICENSE file at https://angular.dev/license
  26938. */
  26939. /**
  26940. * Instruction that returns the component instance in which the current instruction is executing.
  26941. * This is a constant-time version of `nextContent` for the case where we know that we need the
  26942. * component instance specifically, rather than the context of a particular template.
  26943. *
  26944. * @codeGenApi
  26945. */
  26946. function ɵɵcomponentInstance() {
  26947. const instance = getLView()[DECLARATION_COMPONENT_VIEW][CONTEXT];
  26948. ngDevMode && assertDefined(instance, 'Expected component instance to be defined');
  26949. return instance;
  26950. }
  26951. /**
  26952. * A type representing the live collection to be reconciled with any new (incoming) collection. This
  26953. * is an adapter class that makes it possible to work with different internal data structures,
  26954. * regardless of the actual values of the incoming collection.
  26955. */
  26956. class LiveCollection {
  26957. destroy(item) {
  26958. // noop by default
  26959. }
  26960. updateValue(index, value) {
  26961. // noop by default
  26962. }
  26963. // operations below could be implemented on top of the operations defined so far, but having
  26964. // them explicitly allow clear expression of intent and potentially more performant
  26965. // implementations
  26966. swap(index1, index2) {
  26967. const startIdx = Math.min(index1, index2);
  26968. const endIdx = Math.max(index1, index2);
  26969. const endItem = this.detach(endIdx);
  26970. if (endIdx - startIdx > 1) {
  26971. const startItem = this.detach(startIdx);
  26972. this.attach(startIdx, endItem);
  26973. this.attach(endIdx, startItem);
  26974. }
  26975. else {
  26976. this.attach(startIdx, endItem);
  26977. }
  26978. }
  26979. move(prevIndex, newIdx) {
  26980. this.attach(newIdx, this.detach(prevIndex));
  26981. }
  26982. }
  26983. function valuesMatching(liveIdx, liveValue, newIdx, newValue, trackBy) {
  26984. if (liveIdx === newIdx && Object.is(liveValue, newValue)) {
  26985. // matching and no value identity to update
  26986. return 1;
  26987. }
  26988. else if (Object.is(trackBy(liveIdx, liveValue), trackBy(newIdx, newValue))) {
  26989. // matching but requires value identity update
  26990. return -1;
  26991. }
  26992. return 0;
  26993. }
  26994. function recordDuplicateKeys(keyToIdx, key, idx) {
  26995. const idxSoFar = keyToIdx.get(key);
  26996. if (idxSoFar !== undefined) {
  26997. idxSoFar.add(idx);
  26998. }
  26999. else {
  27000. keyToIdx.set(key, new Set([idx]));
  27001. }
  27002. }
  27003. /**
  27004. * The live collection reconciliation algorithm that perform various in-place operations, so it
  27005. * reflects the content of the new (incoming) collection.
  27006. *
  27007. * The reconciliation algorithm has 2 code paths:
  27008. * - "fast" path that don't require any memory allocation;
  27009. * - "slow" path that requires additional memory allocation for intermediate data structures used to
  27010. * collect additional information about the live collection.
  27011. * It might happen that the algorithm switches between the two modes in question in a single
  27012. * reconciliation path - generally it tries to stay on the "fast" path as much as possible.
  27013. *
  27014. * The overall complexity of the algorithm is O(n + m) for speed and O(n) for memory (where n is the
  27015. * length of the live collection and m is the length of the incoming collection). Given the problem
  27016. * at hand the complexity / performance constraints makes it impossible to perform the absolute
  27017. * minimum of operation to reconcile the 2 collections. The algorithm makes different tradeoffs to
  27018. * stay within reasonable performance bounds and may apply sub-optimal number of operations in
  27019. * certain situations.
  27020. *
  27021. * @param liveCollection the current, live collection;
  27022. * @param newCollection the new, incoming collection;
  27023. * @param trackByFn key generation function that determines equality between items in the life and
  27024. * incoming collection;
  27025. */
  27026. function reconcile(liveCollection, newCollection, trackByFn) {
  27027. let detachedItems = undefined;
  27028. let liveKeysInTheFuture = undefined;
  27029. let liveStartIdx = 0;
  27030. let liveEndIdx = liveCollection.length - 1;
  27031. const duplicateKeys = ngDevMode ? new Map() : undefined;
  27032. if (Array.isArray(newCollection)) {
  27033. let newEndIdx = newCollection.length - 1;
  27034. while (liveStartIdx <= liveEndIdx && liveStartIdx <= newEndIdx) {
  27035. // compare from the beginning
  27036. const liveStartValue = liveCollection.at(liveStartIdx);
  27037. const newStartValue = newCollection[liveStartIdx];
  27038. if (ngDevMode) {
  27039. recordDuplicateKeys(duplicateKeys, trackByFn(liveStartIdx, newStartValue), liveStartIdx);
  27040. }
  27041. const isStartMatching = valuesMatching(liveStartIdx, liveStartValue, liveStartIdx, newStartValue, trackByFn);
  27042. if (isStartMatching !== 0) {
  27043. if (isStartMatching < 0) {
  27044. liveCollection.updateValue(liveStartIdx, newStartValue);
  27045. }
  27046. liveStartIdx++;
  27047. continue;
  27048. }
  27049. // compare from the end
  27050. // TODO(perf): do _all_ the matching from the end
  27051. const liveEndValue = liveCollection.at(liveEndIdx);
  27052. const newEndValue = newCollection[newEndIdx];
  27053. if (ngDevMode) {
  27054. recordDuplicateKeys(duplicateKeys, trackByFn(newEndIdx, newEndValue), newEndIdx);
  27055. }
  27056. const isEndMatching = valuesMatching(liveEndIdx, liveEndValue, newEndIdx, newEndValue, trackByFn);
  27057. if (isEndMatching !== 0) {
  27058. if (isEndMatching < 0) {
  27059. liveCollection.updateValue(liveEndIdx, newEndValue);
  27060. }
  27061. liveEndIdx--;
  27062. newEndIdx--;
  27063. continue;
  27064. }
  27065. // Detect swap and moves:
  27066. const liveStartKey = trackByFn(liveStartIdx, liveStartValue);
  27067. const liveEndKey = trackByFn(liveEndIdx, liveEndValue);
  27068. const newStartKey = trackByFn(liveStartIdx, newStartValue);
  27069. if (Object.is(newStartKey, liveEndKey)) {
  27070. const newEndKey = trackByFn(newEndIdx, newEndValue);
  27071. // detect swap on both ends;
  27072. if (Object.is(newEndKey, liveStartKey)) {
  27073. liveCollection.swap(liveStartIdx, liveEndIdx);
  27074. liveCollection.updateValue(liveEndIdx, newEndValue);
  27075. newEndIdx--;
  27076. liveEndIdx--;
  27077. }
  27078. else {
  27079. // the new item is the same as the live item with the end pointer - this is a move forward
  27080. // to an earlier index;
  27081. liveCollection.move(liveEndIdx, liveStartIdx);
  27082. }
  27083. liveCollection.updateValue(liveStartIdx, newStartValue);
  27084. liveStartIdx++;
  27085. continue;
  27086. }
  27087. // Fallback to the slow path: we need to learn more about the content of the live and new
  27088. // collections.
  27089. detachedItems ??= new UniqueValueMultiKeyMap();
  27090. liveKeysInTheFuture ??= initLiveItemsInTheFuture(liveCollection, liveStartIdx, liveEndIdx, trackByFn);
  27091. // Check if I'm inserting a previously detached item: if so, attach it here
  27092. if (attachPreviouslyDetached(liveCollection, detachedItems, liveStartIdx, newStartKey)) {
  27093. liveCollection.updateValue(liveStartIdx, newStartValue);
  27094. liveStartIdx++;
  27095. liveEndIdx++;
  27096. }
  27097. else if (!liveKeysInTheFuture.has(newStartKey)) {
  27098. // Check if we seen a new item that doesn't exist in the old collection and must be INSERTED
  27099. const newItem = liveCollection.create(liveStartIdx, newCollection[liveStartIdx]);
  27100. liveCollection.attach(liveStartIdx, newItem);
  27101. liveStartIdx++;
  27102. liveEndIdx++;
  27103. }
  27104. else {
  27105. // We know that the new item exists later on in old collection but we don't know its index
  27106. // and as the consequence can't move it (don't know where to find it). Detach the old item,
  27107. // hoping that it unlocks the fast path again.
  27108. detachedItems.set(liveStartKey, liveCollection.detach(liveStartIdx));
  27109. liveEndIdx--;
  27110. }
  27111. }
  27112. // Final cleanup steps:
  27113. // - more items in the new collection => insert
  27114. while (liveStartIdx <= newEndIdx) {
  27115. createOrAttach(liveCollection, detachedItems, trackByFn, liveStartIdx, newCollection[liveStartIdx]);
  27116. liveStartIdx++;
  27117. }
  27118. }
  27119. else if (newCollection != null) {
  27120. // iterable - immediately fallback to the slow path
  27121. const newCollectionIterator = newCollection[Symbol.iterator]();
  27122. let newIterationResult = newCollectionIterator.next();
  27123. while (!newIterationResult.done && liveStartIdx <= liveEndIdx) {
  27124. const liveValue = liveCollection.at(liveStartIdx);
  27125. const newValue = newIterationResult.value;
  27126. if (ngDevMode) {
  27127. recordDuplicateKeys(duplicateKeys, trackByFn(liveStartIdx, newValue), liveStartIdx);
  27128. }
  27129. const isStartMatching = valuesMatching(liveStartIdx, liveValue, liveStartIdx, newValue, trackByFn);
  27130. if (isStartMatching !== 0) {
  27131. // found a match - move on, but update value
  27132. if (isStartMatching < 0) {
  27133. liveCollection.updateValue(liveStartIdx, newValue);
  27134. }
  27135. liveStartIdx++;
  27136. newIterationResult = newCollectionIterator.next();
  27137. }
  27138. else {
  27139. detachedItems ??= new UniqueValueMultiKeyMap();
  27140. liveKeysInTheFuture ??= initLiveItemsInTheFuture(liveCollection, liveStartIdx, liveEndIdx, trackByFn);
  27141. // Check if I'm inserting a previously detached item: if so, attach it here
  27142. const newKey = trackByFn(liveStartIdx, newValue);
  27143. if (attachPreviouslyDetached(liveCollection, detachedItems, liveStartIdx, newKey)) {
  27144. liveCollection.updateValue(liveStartIdx, newValue);
  27145. liveStartIdx++;
  27146. liveEndIdx++;
  27147. newIterationResult = newCollectionIterator.next();
  27148. }
  27149. else if (!liveKeysInTheFuture.has(newKey)) {
  27150. liveCollection.attach(liveStartIdx, liveCollection.create(liveStartIdx, newValue));
  27151. liveStartIdx++;
  27152. liveEndIdx++;
  27153. newIterationResult = newCollectionIterator.next();
  27154. }
  27155. else {
  27156. // it is a move forward - detach the current item without advancing in collections
  27157. const liveKey = trackByFn(liveStartIdx, liveValue);
  27158. detachedItems.set(liveKey, liveCollection.detach(liveStartIdx));
  27159. liveEndIdx--;
  27160. }
  27161. }
  27162. }
  27163. // this is a new item as we run out of the items in the old collection - create or attach a
  27164. // previously detached one
  27165. while (!newIterationResult.done) {
  27166. createOrAttach(liveCollection, detachedItems, trackByFn, liveCollection.length, newIterationResult.value);
  27167. newIterationResult = newCollectionIterator.next();
  27168. }
  27169. }
  27170. // Cleanups common to the array and iterable:
  27171. // - more items in the live collection => delete starting from the end;
  27172. while (liveStartIdx <= liveEndIdx) {
  27173. liveCollection.destroy(liveCollection.detach(liveEndIdx--));
  27174. }
  27175. // - destroy items that were detached but never attached again.
  27176. detachedItems?.forEach((item) => {
  27177. liveCollection.destroy(item);
  27178. });
  27179. // report duplicate keys (dev mode only)
  27180. if (ngDevMode) {
  27181. let duplicatedKeysMsg = [];
  27182. for (const [key, idxSet] of duplicateKeys) {
  27183. if (idxSet.size > 1) {
  27184. const idx = [...idxSet].sort((a, b) => a - b);
  27185. for (let i = 1; i < idx.length; i++) {
  27186. duplicatedKeysMsg.push(`key "${stringifyForError(key)}" at index "${idx[i - 1]}" and "${idx[i]}"`);
  27187. }
  27188. }
  27189. }
  27190. if (duplicatedKeysMsg.length > 0) {
  27191. const message = formatRuntimeError(-955 /* RuntimeErrorCode.LOOP_TRACK_DUPLICATE_KEYS */, 'The provided track expression resulted in duplicated keys for a given collection. ' +
  27192. 'Adjust the tracking expression such that it uniquely identifies all the items in the collection. ' +
  27193. 'Duplicated keys were: \n' +
  27194. duplicatedKeysMsg.join(', \n') +
  27195. '.');
  27196. console.warn(message);
  27197. }
  27198. }
  27199. }
  27200. function attachPreviouslyDetached(prevCollection, detachedItems, index, key) {
  27201. if (detachedItems !== undefined && detachedItems.has(key)) {
  27202. prevCollection.attach(index, detachedItems.get(key));
  27203. detachedItems.delete(key);
  27204. return true;
  27205. }
  27206. return false;
  27207. }
  27208. function createOrAttach(liveCollection, detachedItems, trackByFn, index, value) {
  27209. if (!attachPreviouslyDetached(liveCollection, detachedItems, index, trackByFn(index, value))) {
  27210. const newItem = liveCollection.create(index, value);
  27211. liveCollection.attach(index, newItem);
  27212. }
  27213. else {
  27214. liveCollection.updateValue(index, value);
  27215. }
  27216. }
  27217. function initLiveItemsInTheFuture(liveCollection, start, end, trackByFn) {
  27218. const keys = new Set();
  27219. for (let i = start; i <= end; i++) {
  27220. keys.add(trackByFn(i, liveCollection.at(i)));
  27221. }
  27222. return keys;
  27223. }
  27224. /**
  27225. * A specific, partial implementation of the Map interface with the following characteristics:
  27226. * - allows multiple values for a given key;
  27227. * - maintain FIFO order for multiple values corresponding to a given key;
  27228. * - assumes that all values are unique.
  27229. *
  27230. * The implementation aims at having the minimal overhead for cases where keys are _not_ duplicated
  27231. * (the most common case in the list reconciliation algorithm). To achieve this, the first value for
  27232. * a given key is stored in a regular map. Then, when more values are set for a given key, we
  27233. * maintain a form of linked list in a separate map. To maintain this linked list we assume that all
  27234. * values (in the entire collection) are unique.
  27235. */
  27236. class UniqueValueMultiKeyMap {
  27237. // A map from a key to the first value corresponding to this key.
  27238. kvMap = new Map();
  27239. // A map that acts as a linked list of values - each value maps to the next value in this "linked
  27240. // list" (this only works if values are unique). Allocated lazily to avoid memory consumption when
  27241. // there are no duplicated values.
  27242. _vMap = undefined;
  27243. has(key) {
  27244. return this.kvMap.has(key);
  27245. }
  27246. delete(key) {
  27247. if (!this.has(key))
  27248. return false;
  27249. const value = this.kvMap.get(key);
  27250. if (this._vMap !== undefined && this._vMap.has(value)) {
  27251. this.kvMap.set(key, this._vMap.get(value));
  27252. this._vMap.delete(value);
  27253. }
  27254. else {
  27255. this.kvMap.delete(key);
  27256. }
  27257. return true;
  27258. }
  27259. get(key) {
  27260. return this.kvMap.get(key);
  27261. }
  27262. set(key, value) {
  27263. if (this.kvMap.has(key)) {
  27264. let prevValue = this.kvMap.get(key);
  27265. // Note: we don't use `assertNotSame`, because the value needs to be stringified even if
  27266. // there is no error which can freeze the browser for large values (see #58509).
  27267. if (ngDevMode && prevValue === value) {
  27268. throw new Error(`Detected a duplicated value ${value} for the key ${key}`);
  27269. }
  27270. if (this._vMap === undefined) {
  27271. this._vMap = new Map();
  27272. }
  27273. const vMap = this._vMap;
  27274. while (vMap.has(prevValue)) {
  27275. prevValue = vMap.get(prevValue);
  27276. }
  27277. vMap.set(prevValue, value);
  27278. }
  27279. else {
  27280. this.kvMap.set(key, value);
  27281. }
  27282. }
  27283. forEach(cb) {
  27284. for (let [key, value] of this.kvMap) {
  27285. cb(value, key);
  27286. if (this._vMap !== undefined) {
  27287. const vMap = this._vMap;
  27288. while (vMap.has(value)) {
  27289. value = vMap.get(value);
  27290. cb(value, key);
  27291. }
  27292. }
  27293. }
  27294. }
  27295. }
  27296. /**
  27297. * The conditional instruction represents the basic building block on the runtime side to support
  27298. * built-in "if" and "switch". On the high level this instruction is responsible for adding and
  27299. * removing views selected by a conditional expression.
  27300. *
  27301. * @param matchingTemplateIndex Index of a template TNode representing a conditional view to be
  27302. * inserted; -1 represents a special case when there is no view to insert.
  27303. * @param contextValue Value that should be exposed as the context of the conditional.
  27304. * @codeGenApi
  27305. */
  27306. function ɵɵconditional(matchingTemplateIndex, contextValue) {
  27307. performanceMarkFeature('NgControlFlow');
  27308. const hostLView = getLView();
  27309. const bindingIndex = nextBindingIndex();
  27310. const prevMatchingTemplateIndex = hostLView[bindingIndex] !== NO_CHANGE ? hostLView[bindingIndex] : -1;
  27311. const prevContainer = prevMatchingTemplateIndex !== -1
  27312. ? getLContainer(hostLView, HEADER_OFFSET + prevMatchingTemplateIndex)
  27313. : undefined;
  27314. const viewInContainerIdx = 0;
  27315. if (bindingUpdated(hostLView, bindingIndex, matchingTemplateIndex)) {
  27316. const prevConsumer = setActiveConsumer$1(null);
  27317. try {
  27318. // The index of the view to show changed - remove the previously displayed one
  27319. // (it is a noop if there are no active views in a container).
  27320. if (prevContainer !== undefined) {
  27321. removeLViewFromLContainer(prevContainer, viewInContainerIdx);
  27322. }
  27323. // Index -1 is a special case where none of the conditions evaluates to
  27324. // a truthy value and as the consequence we've got no view to show.
  27325. if (matchingTemplateIndex !== -1) {
  27326. const nextLContainerIndex = HEADER_OFFSET + matchingTemplateIndex;
  27327. const nextContainer = getLContainer(hostLView, nextLContainerIndex);
  27328. const templateTNode = getExistingTNode(hostLView[TVIEW], nextLContainerIndex);
  27329. const dehydratedView = findMatchingDehydratedView(nextContainer, templateTNode.tView.ssrId);
  27330. const embeddedLView = createAndRenderEmbeddedLView(hostLView, templateTNode, contextValue, {
  27331. dehydratedView,
  27332. });
  27333. addLViewToLContainer(nextContainer, embeddedLView, viewInContainerIdx, shouldAddViewToDom(templateTNode, dehydratedView));
  27334. }
  27335. }
  27336. finally {
  27337. setActiveConsumer$1(prevConsumer);
  27338. }
  27339. }
  27340. else if (prevContainer !== undefined) {
  27341. // We might keep displaying the same template but the actual value of the expression could have
  27342. // changed - re-bind in context.
  27343. const lView = getLViewFromLContainer(prevContainer, viewInContainerIdx);
  27344. if (lView !== undefined) {
  27345. lView[CONTEXT] = contextValue;
  27346. }
  27347. }
  27348. }
  27349. class RepeaterContext {
  27350. lContainer;
  27351. $implicit;
  27352. $index;
  27353. constructor(lContainer, $implicit, $index) {
  27354. this.lContainer = lContainer;
  27355. this.$implicit = $implicit;
  27356. this.$index = $index;
  27357. }
  27358. get $count() {
  27359. return this.lContainer.length - CONTAINER_HEADER_OFFSET;
  27360. }
  27361. }
  27362. /**
  27363. * A built-in trackBy function used for situations where users specified collection index as a
  27364. * tracking expression. Having this function body in the runtime avoids unnecessary code generation.
  27365. *
  27366. * @param index
  27367. * @returns
  27368. */
  27369. function ɵɵrepeaterTrackByIndex(index) {
  27370. return index;
  27371. }
  27372. /**
  27373. * A built-in trackBy function used for situations where users specified collection item reference
  27374. * as a tracking expression. Having this function body in the runtime avoids unnecessary code
  27375. * generation.
  27376. *
  27377. * @param index
  27378. * @returns
  27379. */
  27380. function ɵɵrepeaterTrackByIdentity(_, value) {
  27381. return value;
  27382. }
  27383. class RepeaterMetadata {
  27384. hasEmptyBlock;
  27385. trackByFn;
  27386. liveCollection;
  27387. constructor(hasEmptyBlock, trackByFn, liveCollection) {
  27388. this.hasEmptyBlock = hasEmptyBlock;
  27389. this.trackByFn = trackByFn;
  27390. this.liveCollection = liveCollection;
  27391. }
  27392. }
  27393. /**
  27394. * The repeaterCreate instruction runs in the creation part of the template pass and initializes
  27395. * internal data structures required by the update pass of the built-in repeater logic. Repeater
  27396. * metadata are allocated in the data part of LView with the following layout:
  27397. * - LView[HEADER_OFFSET + index] - metadata
  27398. * - LView[HEADER_OFFSET + index + 1] - reference to a template function rendering an item
  27399. * - LView[HEADER_OFFSET + index + 2] - optional reference to a template function rendering an empty
  27400. * block
  27401. *
  27402. * @param index Index at which to store the metadata of the repeater.
  27403. * @param templateFn Reference to the template of the main repeater block.
  27404. * @param decls The number of nodes, local refs, and pipes for the main block.
  27405. * @param vars The number of bindings for the main block.
  27406. * @param tagName The name of the container element, if applicable
  27407. * @param attrsIndex Index of template attributes in the `consts` array.
  27408. * @param trackByFn Reference to the tracking function.
  27409. * @param trackByUsesComponentInstance Whether the tracking function has any references to the
  27410. * component instance. If it doesn't, we can avoid rebinding it.
  27411. * @param emptyTemplateFn Reference to the template function of the empty block.
  27412. * @param emptyDecls The number of nodes, local refs, and pipes for the empty block.
  27413. * @param emptyVars The number of bindings for the empty block.
  27414. * @param emptyTagName The name of the empty block container element, if applicable
  27415. * @param emptyAttrsIndex Index of the empty block template attributes in the `consts` array.
  27416. *
  27417. * @codeGenApi
  27418. */
  27419. function ɵɵrepeaterCreate(index, templateFn, decls, vars, tagName, attrsIndex, trackByFn, trackByUsesComponentInstance, emptyTemplateFn, emptyDecls, emptyVars, emptyTagName, emptyAttrsIndex) {
  27420. performanceMarkFeature('NgControlFlow');
  27421. ngDevMode &&
  27422. assertFunction(trackByFn, `A track expression must be a function, was ${typeof trackByFn} instead.`);
  27423. const lView = getLView();
  27424. const tView = getTView();
  27425. const hasEmptyBlock = emptyTemplateFn !== undefined;
  27426. const hostLView = getLView();
  27427. const boundTrackBy = trackByUsesComponentInstance
  27428. ? // We only want to bind when necessary, because it produces a
  27429. // new function. For pure functions it's not necessary.
  27430. trackByFn.bind(hostLView[DECLARATION_COMPONENT_VIEW][CONTEXT])
  27431. : trackByFn;
  27432. const metadata = new RepeaterMetadata(hasEmptyBlock, boundTrackBy);
  27433. hostLView[HEADER_OFFSET + index] = metadata;
  27434. declareTemplate(lView, tView, index + 1, templateFn, decls, vars, tagName, getConstant(tView.consts, attrsIndex));
  27435. if (hasEmptyBlock) {
  27436. ngDevMode &&
  27437. assertDefined(emptyDecls, 'Missing number of declarations for the empty repeater block.');
  27438. ngDevMode &&
  27439. assertDefined(emptyVars, 'Missing number of bindings for the empty repeater block.');
  27440. declareTemplate(lView, tView, index + 2, emptyTemplateFn, emptyDecls, emptyVars, emptyTagName, getConstant(tView.consts, emptyAttrsIndex));
  27441. }
  27442. }
  27443. function isViewExpensiveToRecreate(lView) {
  27444. // assumption: anything more than a text node with a binding is considered "expensive"
  27445. return lView.length - HEADER_OFFSET > 2;
  27446. }
  27447. class OperationsCounter {
  27448. created = 0;
  27449. destroyed = 0;
  27450. reset() {
  27451. this.created = 0;
  27452. this.destroyed = 0;
  27453. }
  27454. recordCreate() {
  27455. this.created++;
  27456. }
  27457. recordDestroy() {
  27458. this.destroyed++;
  27459. }
  27460. /**
  27461. * A method indicating if the entire collection was re-created as part of the reconciliation pass.
  27462. * Used to warn developers about the usage of a tracking function that might result in excessive
  27463. * amount of view creation / destroy operations.
  27464. *
  27465. * @returns boolean value indicating if a live collection was re-created
  27466. */
  27467. wasReCreated(collectionLen) {
  27468. return collectionLen > 0 && this.created === this.destroyed && this.created === collectionLen;
  27469. }
  27470. }
  27471. class LiveCollectionLContainerImpl extends LiveCollection {
  27472. lContainer;
  27473. hostLView;
  27474. templateTNode;
  27475. operationsCounter = ngDevMode ? new OperationsCounter() : undefined;
  27476. /**
  27477. Property indicating if indexes in the repeater context need to be updated following the live
  27478. collection changes. Index updates are necessary if and only if views are inserted / removed in
  27479. the middle of LContainer. Adds and removals at the end don't require index updates.
  27480. */
  27481. needsIndexUpdate = false;
  27482. constructor(lContainer, hostLView, templateTNode) {
  27483. super();
  27484. this.lContainer = lContainer;
  27485. this.hostLView = hostLView;
  27486. this.templateTNode = templateTNode;
  27487. }
  27488. get length() {
  27489. return this.lContainer.length - CONTAINER_HEADER_OFFSET;
  27490. }
  27491. at(index) {
  27492. return this.getLView(index)[CONTEXT].$implicit;
  27493. }
  27494. attach(index, lView) {
  27495. const dehydratedView = lView[HYDRATION];
  27496. this.needsIndexUpdate ||= index !== this.length;
  27497. addLViewToLContainer(this.lContainer, lView, index, shouldAddViewToDom(this.templateTNode, dehydratedView));
  27498. }
  27499. detach(index) {
  27500. this.needsIndexUpdate ||= index !== this.length - 1;
  27501. return detachExistingView(this.lContainer, index);
  27502. }
  27503. create(index, value) {
  27504. const dehydratedView = findMatchingDehydratedView(this.lContainer, this.templateTNode.tView.ssrId);
  27505. const embeddedLView = createAndRenderEmbeddedLView(this.hostLView, this.templateTNode, new RepeaterContext(this.lContainer, value, index), { dehydratedView });
  27506. this.operationsCounter?.recordCreate();
  27507. return embeddedLView;
  27508. }
  27509. destroy(lView) {
  27510. destroyLView(lView[TVIEW], lView);
  27511. this.operationsCounter?.recordDestroy();
  27512. }
  27513. updateValue(index, value) {
  27514. this.getLView(index)[CONTEXT].$implicit = value;
  27515. }
  27516. reset() {
  27517. this.needsIndexUpdate = false;
  27518. this.operationsCounter?.reset();
  27519. }
  27520. updateIndexes() {
  27521. if (this.needsIndexUpdate) {
  27522. for (let i = 0; i < this.length; i++) {
  27523. this.getLView(i)[CONTEXT].$index = i;
  27524. }
  27525. }
  27526. }
  27527. getLView(index) {
  27528. return getExistingLViewFromLContainer(this.lContainer, index);
  27529. }
  27530. }
  27531. /**
  27532. * The repeater instruction does update-time diffing of a provided collection (against the
  27533. * collection seen previously) and maps changes in the collection to views structure (by adding,
  27534. * removing or moving views as needed).
  27535. * @param collection - the collection instance to be checked for changes
  27536. * @codeGenApi
  27537. */
  27538. function ɵɵrepeater(collection) {
  27539. const prevConsumer = setActiveConsumer$1(null);
  27540. const metadataSlotIdx = getSelectedIndex();
  27541. try {
  27542. const hostLView = getLView();
  27543. const hostTView = hostLView[TVIEW];
  27544. const metadata = hostLView[metadataSlotIdx];
  27545. const containerIndex = metadataSlotIdx + 1;
  27546. const lContainer = getLContainer(hostLView, containerIndex);
  27547. if (metadata.liveCollection === undefined) {
  27548. const itemTemplateTNode = getExistingTNode(hostTView, containerIndex);
  27549. metadata.liveCollection = new LiveCollectionLContainerImpl(lContainer, hostLView, itemTemplateTNode);
  27550. }
  27551. else {
  27552. metadata.liveCollection.reset();
  27553. }
  27554. const liveCollection = metadata.liveCollection;
  27555. reconcile(liveCollection, collection, metadata.trackByFn);
  27556. // Warn developers about situations where the entire collection was re-created as part of the
  27557. // reconciliation pass. Note that this warning might be "overreacting" and report cases where
  27558. // the collection re-creation is the intended behavior. Still, the assumption is that most of
  27559. // the time it is undesired.
  27560. if (ngDevMode &&
  27561. metadata.trackByFn === ɵɵrepeaterTrackByIdentity &&
  27562. liveCollection.operationsCounter?.wasReCreated(liveCollection.length) &&
  27563. isViewExpensiveToRecreate(getExistingLViewFromLContainer(lContainer, 0))) {
  27564. const message = formatRuntimeError(-956 /* RuntimeErrorCode.LOOP_TRACK_RECREATE */, `The configured tracking expression (track by identity) caused re-creation of the entire collection of size ${liveCollection.length}. ` +
  27565. 'This is an expensive operation requiring destruction and subsequent creation of DOM nodes, directives, components etc. ' +
  27566. 'Please review the "track expression" and make sure that it uniquely identifies items in a collection.');
  27567. console.warn(message);
  27568. }
  27569. // moves in the container might caused context's index to get out of order, re-adjust if needed
  27570. liveCollection.updateIndexes();
  27571. // handle empty blocks
  27572. if (metadata.hasEmptyBlock) {
  27573. const bindingIndex = nextBindingIndex();
  27574. const isCollectionEmpty = liveCollection.length === 0;
  27575. if (bindingUpdated(hostLView, bindingIndex, isCollectionEmpty)) {
  27576. const emptyTemplateIndex = metadataSlotIdx + 2;
  27577. const lContainerForEmpty = getLContainer(hostLView, emptyTemplateIndex);
  27578. if (isCollectionEmpty) {
  27579. const emptyTemplateTNode = getExistingTNode(hostTView, emptyTemplateIndex);
  27580. const dehydratedView = findMatchingDehydratedView(lContainerForEmpty, emptyTemplateTNode.tView.ssrId);
  27581. const embeddedLView = createAndRenderEmbeddedLView(hostLView, emptyTemplateTNode, undefined, { dehydratedView });
  27582. addLViewToLContainer(lContainerForEmpty, embeddedLView, 0, shouldAddViewToDom(emptyTemplateTNode, dehydratedView));
  27583. }
  27584. else {
  27585. removeLViewFromLContainer(lContainerForEmpty, 0);
  27586. }
  27587. }
  27588. }
  27589. }
  27590. finally {
  27591. setActiveConsumer$1(prevConsumer);
  27592. }
  27593. }
  27594. function getLContainer(lView, index) {
  27595. const lContainer = lView[index];
  27596. ngDevMode && assertLContainer(lContainer);
  27597. return lContainer;
  27598. }
  27599. function detachExistingView(lContainer, index) {
  27600. const existingLView = detachView(lContainer, index);
  27601. ngDevMode && assertLView(existingLView);
  27602. return existingLView;
  27603. }
  27604. function getExistingLViewFromLContainer(lContainer, index) {
  27605. const existingLView = getLViewFromLContainer(lContainer, index);
  27606. ngDevMode && assertLView(existingLView);
  27607. return existingLView;
  27608. }
  27609. function getExistingTNode(tView, index) {
  27610. const tNode = getTNode(tView, index);
  27611. ngDevMode && assertTNode(tNode);
  27612. return tNode;
  27613. }
  27614. /**
  27615. * Create DOM element. The instruction must later be followed by `elementEnd()` call.
  27616. *
  27617. * @param index Index of the element in the LView array
  27618. * @param name Name of the DOM Node
  27619. * @param attrsIndex Index of the element's attributes in the `consts` array.
  27620. * @param localRefsIndex Index of the element's local references in the `consts` array.
  27621. * @returns This function returns itself so that it may be chained.
  27622. *
  27623. * Attributes and localRefs are passed as an array of strings where elements with an even index
  27624. * hold an attribute name and elements with an odd index hold an attribute value, ex.:
  27625. * ['id', 'warning5', 'class', 'alert']
  27626. *
  27627. * @codeGenApi
  27628. */
  27629. function ɵɵelementStart(index, name, attrsIndex, localRefsIndex) {
  27630. const lView = getLView();
  27631. const tView = getTView();
  27632. const adjustedIndex = HEADER_OFFSET + index;
  27633. ngDevMode &&
  27634. assertEqual(getBindingIndex(), tView.bindingStartIndex, 'elements should be created before any bindings');
  27635. ngDevMode && assertIndexInRange(lView, adjustedIndex);
  27636. const renderer = lView[RENDERER];
  27637. const tNode = tView.firstCreatePass
  27638. ? elementStartFirstCreatePass(adjustedIndex, tView, lView, name, findDirectiveDefMatches, getBindingsEnabled(), attrsIndex, localRefsIndex)
  27639. : tView.data[adjustedIndex];
  27640. const native = _locateOrCreateElementNode(tView, lView, tNode, renderer, name, index);
  27641. lView[adjustedIndex] = native;
  27642. const hasDirectives = isDirectiveHost(tNode);
  27643. if (ngDevMode && tView.firstCreatePass) {
  27644. validateElementIsKnown(native, lView, tNode.value, tView.schemas, hasDirectives);
  27645. }
  27646. setCurrentTNode(tNode, true);
  27647. setupStaticAttributes(renderer, native, tNode);
  27648. if (!isDetachedByI18n(tNode) && wasLastNodeCreated()) {
  27649. // In the i18n case, the translation may have removed this element, so only add it if it is not
  27650. // detached. See `TNodeType.Placeholder` and `LFrame.inI18n` for more context.
  27651. appendChild(tView, lView, native, tNode);
  27652. }
  27653. // any immediate children of a component or template container must be pre-emptively
  27654. // monkey-patched with the component view data so that the element can be inspected
  27655. // later on using any element discovery utility methods (see `element_discovery.ts`)
  27656. if (getElementDepthCount() === 0 || hasDirectives) {
  27657. attachPatchData(native, lView);
  27658. }
  27659. increaseElementDepthCount();
  27660. if (hasDirectives) {
  27661. createDirectivesInstances(tView, lView, tNode);
  27662. executeContentQueries(tView, tNode, lView);
  27663. }
  27664. if (localRefsIndex !== null) {
  27665. saveResolvedLocalsInData(lView, tNode);
  27666. }
  27667. return ɵɵelementStart;
  27668. }
  27669. /**
  27670. * Mark the end of the element.
  27671. * @returns This function returns itself so that it may be chained.
  27672. *
  27673. * @codeGenApi
  27674. */
  27675. function ɵɵelementEnd() {
  27676. let currentTNode = getCurrentTNode();
  27677. ngDevMode && assertDefined(currentTNode, 'No parent node to close.');
  27678. if (isCurrentTNodeParent()) {
  27679. setCurrentTNodeAsNotParent();
  27680. }
  27681. else {
  27682. ngDevMode && assertHasParent(getCurrentTNode());
  27683. currentTNode = currentTNode.parent;
  27684. setCurrentTNode(currentTNode, false);
  27685. }
  27686. const tNode = currentTNode;
  27687. ngDevMode && assertTNodeType(tNode, 3 /* TNodeType.AnyRNode */);
  27688. if (isSkipHydrationRootTNode(tNode)) {
  27689. leaveSkipHydrationBlock();
  27690. }
  27691. decreaseElementDepthCount();
  27692. const tView = getTView();
  27693. if (tView.firstCreatePass) {
  27694. elementEndFirstCreatePass(tView, tNode);
  27695. }
  27696. if (tNode.classesWithoutHost != null && hasClassInput(tNode)) {
  27697. setDirectiveInputsWhichShadowsStyling(tView, tNode, getLView(), tNode.classesWithoutHost, true);
  27698. }
  27699. if (tNode.stylesWithoutHost != null && hasStyleInput(tNode)) {
  27700. setDirectiveInputsWhichShadowsStyling(tView, tNode, getLView(), tNode.stylesWithoutHost, false);
  27701. }
  27702. return ɵɵelementEnd;
  27703. }
  27704. /**
  27705. * Creates an empty element using {@link elementStart} and {@link elementEnd}
  27706. *
  27707. * @param index Index of the element in the data array
  27708. * @param name Name of the DOM Node
  27709. * @param attrsIndex Index of the element's attributes in the `consts` array.
  27710. * @param localRefsIndex Index of the element's local references in the `consts` array.
  27711. * @returns This function returns itself so that it may be chained.
  27712. *
  27713. * @codeGenApi
  27714. */
  27715. function ɵɵelement(index, name, attrsIndex, localRefsIndex) {
  27716. ɵɵelementStart(index, name, attrsIndex, localRefsIndex);
  27717. ɵɵelementEnd();
  27718. return ɵɵelement;
  27719. }
  27720. let _locateOrCreateElementNode = (tView, lView, tNode, renderer, name, index) => {
  27721. lastNodeWasCreated(true);
  27722. return createElementNode(renderer, name, getNamespace());
  27723. };
  27724. /**
  27725. * Enables hydration code path (to lookup existing elements in DOM)
  27726. * in addition to the regular creation mode of element nodes.
  27727. */
  27728. function locateOrCreateElementNodeImpl(tView, lView, tNode, renderer, name, index) {
  27729. const hydrationInfo = lView[HYDRATION];
  27730. const isNodeCreationMode = !hydrationInfo ||
  27731. isInSkipHydrationBlock$1() ||
  27732. isDetachedByI18n(tNode) ||
  27733. isDisconnectedNode$1(hydrationInfo, index);
  27734. lastNodeWasCreated(isNodeCreationMode);
  27735. // Regular creation mode.
  27736. if (isNodeCreationMode) {
  27737. return createElementNode(renderer, name, getNamespace());
  27738. }
  27739. // Hydration mode, looking up an existing element in DOM.
  27740. const native = locateNextRNode(hydrationInfo, tView, lView, tNode);
  27741. ngDevMode && validateMatchingNode(native, Node.ELEMENT_NODE, name, lView, tNode);
  27742. ngDevMode && markRNodeAsClaimedByHydration(native);
  27743. // This element might also be an anchor of a view container.
  27744. if (getSerializedContainerViews(hydrationInfo, index)) {
  27745. // Important note: this element acts as an anchor, but it's **not** a part
  27746. // of the embedded view, so we start the segment **after** this element, taking
  27747. // a reference to the next sibling. For example, the following template:
  27748. // `<div #vcrTarget>` is represented in the DOM as `<div></div>...<!--container-->`,
  27749. // so while processing a `<div>` instruction, point to the next sibling as a
  27750. // start of a segment.
  27751. ngDevMode && validateNodeExists(native.nextSibling, lView, tNode);
  27752. setSegmentHead(hydrationInfo, index, native.nextSibling);
  27753. }
  27754. // Checks if the skip hydration attribute is present during hydration so we know to
  27755. // skip attempting to hydrate this block. We check both TNode and RElement for an
  27756. // attribute: the RElement case is needed for i18n cases, when we add it to host
  27757. // elements during the annotation phase (after all internal data structures are setup).
  27758. if (hydrationInfo &&
  27759. (hasSkipHydrationAttrOnTNode(tNode) || hasSkipHydrationAttrOnRElement(native))) {
  27760. if (isComponentHost(tNode)) {
  27761. enterSkipHydrationBlock(tNode);
  27762. // Since this isn't hydratable, we need to empty the node
  27763. // so there's no duplicate content after render
  27764. clearElementContents(native);
  27765. ngDevMode && markRNodeAsSkippedByHydration(native);
  27766. }
  27767. else if (ngDevMode) {
  27768. // If this is not a component host, throw an error.
  27769. // Hydration can be skipped on per-component basis only.
  27770. throw invalidSkipHydrationHost(native);
  27771. }
  27772. }
  27773. return native;
  27774. }
  27775. function enableLocateOrCreateElementNodeImpl() {
  27776. _locateOrCreateElementNode = locateOrCreateElementNodeImpl;
  27777. }
  27778. function elementContainerStartFirstCreatePass(index, tView, lView, attrsIndex, localRefsIndex) {
  27779. ngDevMode && ngDevMode.firstCreatePass++;
  27780. const tViewConsts = tView.consts;
  27781. const attrs = getConstant(tViewConsts, attrsIndex);
  27782. const tNode = getOrCreateTNode(tView, index, 8 /* TNodeType.ElementContainer */, 'ng-container', attrs);
  27783. // While ng-container doesn't necessarily support styling, we use the style context to identify
  27784. // and execute directives on the ng-container.
  27785. if (attrs !== null) {
  27786. computeStaticStyling(tNode, attrs, true);
  27787. }
  27788. const localRefs = getConstant(tViewConsts, localRefsIndex);
  27789. if (getBindingsEnabled()) {
  27790. resolveDirectives(tView, lView, tNode, localRefs, findDirectiveDefMatches);
  27791. }
  27792. // Merge the template attrs last so that they have the highest priority.
  27793. tNode.mergedAttrs = mergeHostAttrs(tNode.mergedAttrs, tNode.attrs);
  27794. if (tView.queries !== null) {
  27795. tView.queries.elementStart(tView, tNode);
  27796. }
  27797. return tNode;
  27798. }
  27799. /**
  27800. * Creates a logical container for other nodes (<ng-container>) backed by a comment node in the DOM.
  27801. * The instruction must later be followed by `elementContainerEnd()` call.
  27802. *
  27803. * @param index Index of the element in the LView array
  27804. * @param attrsIndex Index of the container attributes in the `consts` array.
  27805. * @param localRefsIndex Index of the container's local references in the `consts` array.
  27806. * @returns This function returns itself so that it may be chained.
  27807. *
  27808. * Even if this instruction accepts a set of attributes no actual attribute values are propagated to
  27809. * the DOM (as a comment node can't have attributes). Attributes are here only for directive
  27810. * matching purposes and setting initial inputs of directives.
  27811. *
  27812. * @codeGenApi
  27813. */
  27814. function ɵɵelementContainerStart(index, attrsIndex, localRefsIndex) {
  27815. const lView = getLView();
  27816. const tView = getTView();
  27817. const adjustedIndex = index + HEADER_OFFSET;
  27818. ngDevMode && assertIndexInRange(lView, adjustedIndex);
  27819. ngDevMode &&
  27820. assertEqual(getBindingIndex(), tView.bindingStartIndex, 'element containers should be created before any bindings');
  27821. const tNode = tView.firstCreatePass
  27822. ? elementContainerStartFirstCreatePass(adjustedIndex, tView, lView, attrsIndex, localRefsIndex)
  27823. : tView.data[adjustedIndex];
  27824. setCurrentTNode(tNode, true);
  27825. const comment = _locateOrCreateElementContainerNode(tView, lView, tNode, index);
  27826. lView[adjustedIndex] = comment;
  27827. if (wasLastNodeCreated()) {
  27828. appendChild(tView, lView, comment, tNode);
  27829. }
  27830. attachPatchData(comment, lView);
  27831. if (isDirectiveHost(tNode)) {
  27832. createDirectivesInstances(tView, lView, tNode);
  27833. executeContentQueries(tView, tNode, lView);
  27834. }
  27835. if (localRefsIndex != null) {
  27836. saveResolvedLocalsInData(lView, tNode);
  27837. }
  27838. return ɵɵelementContainerStart;
  27839. }
  27840. /**
  27841. * Mark the end of the <ng-container>.
  27842. * @returns This function returns itself so that it may be chained.
  27843. *
  27844. * @codeGenApi
  27845. */
  27846. function ɵɵelementContainerEnd() {
  27847. let currentTNode = getCurrentTNode();
  27848. const tView = getTView();
  27849. if (isCurrentTNodeParent()) {
  27850. setCurrentTNodeAsNotParent();
  27851. }
  27852. else {
  27853. ngDevMode && assertHasParent(currentTNode);
  27854. currentTNode = currentTNode.parent;
  27855. setCurrentTNode(currentTNode, false);
  27856. }
  27857. ngDevMode && assertTNodeType(currentTNode, 8 /* TNodeType.ElementContainer */);
  27858. if (tView.firstCreatePass) {
  27859. registerPostOrderHooks(tView, currentTNode);
  27860. if (isContentQueryHost(currentTNode)) {
  27861. tView.queries.elementEnd(currentTNode);
  27862. }
  27863. }
  27864. return ɵɵelementContainerEnd;
  27865. }
  27866. /**
  27867. * Creates an empty logical container using {@link elementContainerStart}
  27868. * and {@link elementContainerEnd}
  27869. *
  27870. * @param index Index of the element in the LView array
  27871. * @param attrsIndex Index of the container attributes in the `consts` array.
  27872. * @param localRefsIndex Index of the container's local references in the `consts` array.
  27873. * @returns This function returns itself so that it may be chained.
  27874. *
  27875. * @codeGenApi
  27876. */
  27877. function ɵɵelementContainer(index, attrsIndex, localRefsIndex) {
  27878. ɵɵelementContainerStart(index, attrsIndex, localRefsIndex);
  27879. ɵɵelementContainerEnd();
  27880. return ɵɵelementContainer;
  27881. }
  27882. let _locateOrCreateElementContainerNode = (tView, lView, tNode, index) => {
  27883. lastNodeWasCreated(true);
  27884. return createCommentNode(lView[RENDERER], ngDevMode ? 'ng-container' : '');
  27885. };
  27886. /**
  27887. * Enables hydration code path (to lookup existing elements in DOM)
  27888. * in addition to the regular creation mode of comment nodes that
  27889. * represent <ng-container>'s anchor.
  27890. */
  27891. function locateOrCreateElementContainerNode(tView, lView, tNode, index) {
  27892. let comment;
  27893. const hydrationInfo = lView[HYDRATION];
  27894. const isNodeCreationMode = !hydrationInfo ||
  27895. isInSkipHydrationBlock$1() ||
  27896. isDisconnectedNode$1(hydrationInfo, index) ||
  27897. isDetachedByI18n(tNode);
  27898. lastNodeWasCreated(isNodeCreationMode);
  27899. // Regular creation mode.
  27900. if (isNodeCreationMode) {
  27901. return createCommentNode(lView[RENDERER], ngDevMode ? 'ng-container' : '');
  27902. }
  27903. // Hydration mode, looking up existing elements in DOM.
  27904. const currentRNode = locateNextRNode(hydrationInfo, tView, lView, tNode);
  27905. ngDevMode && validateNodeExists(currentRNode, lView, tNode);
  27906. const ngContainerSize = getNgContainerSize(hydrationInfo, index);
  27907. ngDevMode &&
  27908. assertNumber(ngContainerSize, 'Unexpected state: hydrating an <ng-container>, ' + 'but no hydration info is available.');
  27909. setSegmentHead(hydrationInfo, index, currentRNode);
  27910. comment = siblingAfter(ngContainerSize, currentRNode);
  27911. if (ngDevMode) {
  27912. validateMatchingNode(comment, Node.COMMENT_NODE, null, lView, tNode);
  27913. markRNodeAsClaimedByHydration(comment);
  27914. }
  27915. return comment;
  27916. }
  27917. function enableLocateOrCreateElementContainerNodeImpl() {
  27918. _locateOrCreateElementContainerNode = locateOrCreateElementContainerNode;
  27919. }
  27920. /**
  27921. * Returns the current OpaqueViewState instance.
  27922. *
  27923. * Used in conjunction with the restoreView() instruction to save a snapshot
  27924. * of the current view and restore it when listeners are invoked. This allows
  27925. * walking the declaration view tree in listeners to get vars from parent views.
  27926. *
  27927. * @codeGenApi
  27928. */
  27929. function ɵɵgetCurrentView() {
  27930. return getLView();
  27931. }
  27932. /**
  27933. * Update a property on a host element. Only applies to native node properties, not inputs.
  27934. *
  27935. * Operates on the element selected by index via the {@link select} instruction.
  27936. *
  27937. * @param propName Name of property. Because it is going to DOM, this is not subject to
  27938. * renaming as part of minification.
  27939. * @param value New value to write.
  27940. * @param sanitizer An optional function used to sanitize the value.
  27941. * @returns This function returns itself so that it may be chained
  27942. * (e.g. `property('name', ctx.name)('title', ctx.title)`)
  27943. *
  27944. * @codeGenApi
  27945. */
  27946. function ɵɵhostProperty(propName, value, sanitizer) {
  27947. const lView = getLView();
  27948. const bindingIndex = nextBindingIndex();
  27949. if (bindingUpdated(lView, bindingIndex, value)) {
  27950. const tView = getTView();
  27951. const tNode = getSelectedTNode();
  27952. elementPropertyInternal(tView, tNode, lView, propName, value, lView[RENDERER], sanitizer, true);
  27953. ngDevMode && storePropertyBindingMetadata(tView.data, tNode, propName, bindingIndex);
  27954. }
  27955. return ɵɵhostProperty;
  27956. }
  27957. /**
  27958. * Updates a synthetic host binding (e.g. `[@foo]`) on a component or directive.
  27959. *
  27960. * This instruction is for compatibility purposes and is designed to ensure that a
  27961. * synthetic host binding (e.g. `@HostBinding('@foo')`) properly gets rendered in
  27962. * the component's renderer. Normally all host bindings are evaluated with the parent
  27963. * component's renderer, but, in the case of animation @triggers, they need to be
  27964. * evaluated with the sub component's renderer (because that's where the animation
  27965. * triggers are defined).
  27966. *
  27967. * Do not use this instruction as a replacement for `elementProperty`. This instruction
  27968. * only exists to ensure compatibility with the ViewEngine's host binding behavior.
  27969. *
  27970. * @param index The index of the element to update in the data array
  27971. * @param propName Name of property. Because it is going to DOM, this is not subject to
  27972. * renaming as part of minification.
  27973. * @param value New value to write.
  27974. * @param sanitizer An optional function used to sanitize the value.
  27975. *
  27976. * @codeGenApi
  27977. */
  27978. function ɵɵsyntheticHostProperty(propName, value, sanitizer) {
  27979. const lView = getLView();
  27980. const bindingIndex = nextBindingIndex();
  27981. if (bindingUpdated(lView, bindingIndex, value)) {
  27982. const tView = getTView();
  27983. const tNode = getSelectedTNode();
  27984. const currentDef = getCurrentDirectiveDef(tView.data);
  27985. const renderer = loadComponentRenderer(currentDef, tNode, lView);
  27986. elementPropertyInternal(tView, tNode, lView, propName, value, renderer, sanitizer, true);
  27987. ngDevMode && storePropertyBindingMetadata(tView.data, tNode, propName, bindingIndex);
  27988. }
  27989. return ɵɵsyntheticHostProperty;
  27990. }
  27991. // THIS CODE IS GENERATED - DO NOT MODIFY.
  27992. const u = undefined;
  27993. function plural(val) {
  27994. const i = Math.floor(Math.abs(val)), v = val.toString().replace(/^[^.]*\.?/, '').length;
  27995. if (i === 1 && v === 0)
  27996. return 1;
  27997. return 5;
  27998. }
  27999. var localeEn = ["en", [["a", "p"], ["AM", "PM"], u], [["AM", "PM"], u, u], [["S", "M", "T", "W", "T", "F", "S"], ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"]], u, [["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"], ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]], u, [["B", "A"], ["BC", "AD"], ["Before Christ", "Anno Domini"]], 0, [6, 0], ["M/d/yy", "MMM d, y", "MMMM d, y", "EEEE, MMMM d, y"], ["h:mm a", "h:mm:ss a", "h:mm:ss a z", "h:mm:ss a zzzz"], ["{1}, {0}", u, "{1} 'at' {0}", u], [".", ",", ";", "%", "+", "-", "E", "×", "‰", "∞", "NaN", ":"], ["#,##0.###", "#,##0%", "¤#,##0.00", "#E0"], "USD", "$", "US Dollar", {}, "ltr", plural];
  28000. /**
  28001. * This const is used to store the locale data registered with `registerLocaleData`
  28002. */
  28003. let LOCALE_DATA = {};
  28004. /**
  28005. * Register locale data to be used internally by Angular. See the
  28006. * ["I18n guide"](guide/i18n/format-data-locale) to know how to import additional locale
  28007. * data.
  28008. *
  28009. * The signature `registerLocaleData(data: any, extraData?: any)` is deprecated since v5.1
  28010. */
  28011. function registerLocaleData(data, localeId, extraData) {
  28012. if (typeof localeId !== 'string') {
  28013. extraData = localeId;
  28014. localeId = data[LocaleDataIndex.LocaleId];
  28015. }
  28016. localeId = localeId.toLowerCase().replace(/_/g, '-');
  28017. LOCALE_DATA[localeId] = data;
  28018. if (extraData) {
  28019. LOCALE_DATA[localeId][LocaleDataIndex.ExtraData] = extraData;
  28020. }
  28021. }
  28022. /**
  28023. * Finds the locale data for a given locale.
  28024. *
  28025. * @param locale The locale code.
  28026. * @returns The locale data.
  28027. * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
  28028. */
  28029. function findLocaleData(locale) {
  28030. const normalizedLocale = normalizeLocale(locale);
  28031. let match = getLocaleData(normalizedLocale);
  28032. if (match) {
  28033. return match;
  28034. }
  28035. // let's try to find a parent locale
  28036. const parentLocale = normalizedLocale.split('-')[0];
  28037. match = getLocaleData(parentLocale);
  28038. if (match) {
  28039. return match;
  28040. }
  28041. if (parentLocale === 'en') {
  28042. return localeEn;
  28043. }
  28044. throw new RuntimeError(701 /* RuntimeErrorCode.MISSING_LOCALE_DATA */, ngDevMode && `Missing locale data for the locale "${locale}".`);
  28045. }
  28046. /**
  28047. * Retrieves the default currency code for the given locale.
  28048. *
  28049. * The default is defined as the first currency which is still in use.
  28050. *
  28051. * @param locale The code of the locale whose currency code we want.
  28052. * @returns The code of the default currency for the given locale.
  28053. *
  28054. */
  28055. function getLocaleCurrencyCode(locale) {
  28056. const data = findLocaleData(locale);
  28057. return data[LocaleDataIndex.CurrencyCode] || null;
  28058. }
  28059. /**
  28060. * Retrieves the plural function used by ICU expressions to determine the plural case to use
  28061. * for a given locale.
  28062. * @param locale A locale code for the locale format rules to use.
  28063. * @returns The plural function for the locale.
  28064. * @see {@link NgPlural}
  28065. * @see [Internationalization (i18n) Guide](guide/i18n)
  28066. */
  28067. function getLocalePluralCase(locale) {
  28068. const data = findLocaleData(locale);
  28069. return data[LocaleDataIndex.PluralCase];
  28070. }
  28071. /**
  28072. * Helper function to get the given `normalizedLocale` from `LOCALE_DATA`
  28073. * or from the global `ng.common.locale`.
  28074. */
  28075. function getLocaleData(normalizedLocale) {
  28076. if (!(normalizedLocale in LOCALE_DATA)) {
  28077. LOCALE_DATA[normalizedLocale] =
  28078. _global.ng &&
  28079. _global.ng.common &&
  28080. _global.ng.common.locales &&
  28081. _global.ng.common.locales[normalizedLocale];
  28082. }
  28083. return LOCALE_DATA[normalizedLocale];
  28084. }
  28085. /**
  28086. * Helper function to remove all the locale data from `LOCALE_DATA`.
  28087. */
  28088. function unregisterAllLocaleData() {
  28089. LOCALE_DATA = {};
  28090. }
  28091. /**
  28092. * Index of each type of locale data from the locale data array
  28093. */
  28094. var LocaleDataIndex;
  28095. (function (LocaleDataIndex) {
  28096. LocaleDataIndex[LocaleDataIndex["LocaleId"] = 0] = "LocaleId";
  28097. LocaleDataIndex[LocaleDataIndex["DayPeriodsFormat"] = 1] = "DayPeriodsFormat";
  28098. LocaleDataIndex[LocaleDataIndex["DayPeriodsStandalone"] = 2] = "DayPeriodsStandalone";
  28099. LocaleDataIndex[LocaleDataIndex["DaysFormat"] = 3] = "DaysFormat";
  28100. LocaleDataIndex[LocaleDataIndex["DaysStandalone"] = 4] = "DaysStandalone";
  28101. LocaleDataIndex[LocaleDataIndex["MonthsFormat"] = 5] = "MonthsFormat";
  28102. LocaleDataIndex[LocaleDataIndex["MonthsStandalone"] = 6] = "MonthsStandalone";
  28103. LocaleDataIndex[LocaleDataIndex["Eras"] = 7] = "Eras";
  28104. LocaleDataIndex[LocaleDataIndex["FirstDayOfWeek"] = 8] = "FirstDayOfWeek";
  28105. LocaleDataIndex[LocaleDataIndex["WeekendRange"] = 9] = "WeekendRange";
  28106. LocaleDataIndex[LocaleDataIndex["DateFormat"] = 10] = "DateFormat";
  28107. LocaleDataIndex[LocaleDataIndex["TimeFormat"] = 11] = "TimeFormat";
  28108. LocaleDataIndex[LocaleDataIndex["DateTimeFormat"] = 12] = "DateTimeFormat";
  28109. LocaleDataIndex[LocaleDataIndex["NumberSymbols"] = 13] = "NumberSymbols";
  28110. LocaleDataIndex[LocaleDataIndex["NumberFormats"] = 14] = "NumberFormats";
  28111. LocaleDataIndex[LocaleDataIndex["CurrencyCode"] = 15] = "CurrencyCode";
  28112. LocaleDataIndex[LocaleDataIndex["CurrencySymbol"] = 16] = "CurrencySymbol";
  28113. LocaleDataIndex[LocaleDataIndex["CurrencyName"] = 17] = "CurrencyName";
  28114. LocaleDataIndex[LocaleDataIndex["Currencies"] = 18] = "Currencies";
  28115. LocaleDataIndex[LocaleDataIndex["Directionality"] = 19] = "Directionality";
  28116. LocaleDataIndex[LocaleDataIndex["PluralCase"] = 20] = "PluralCase";
  28117. LocaleDataIndex[LocaleDataIndex["ExtraData"] = 21] = "ExtraData";
  28118. })(LocaleDataIndex || (LocaleDataIndex = {}));
  28119. /**
  28120. * Returns the canonical form of a locale name - lowercase with `_` replaced with `-`.
  28121. */
  28122. function normalizeLocale(locale) {
  28123. return locale.toLowerCase().replace(/_/g, '-');
  28124. }
  28125. const pluralMapping = ['zero', 'one', 'two', 'few', 'many'];
  28126. /**
  28127. * Returns the plural case based on the locale
  28128. */
  28129. function getPluralCase(value, locale) {
  28130. const plural = getLocalePluralCase(locale)(parseInt(value, 10));
  28131. const result = pluralMapping[plural];
  28132. return result !== undefined ? result : 'other';
  28133. }
  28134. /**
  28135. * The locale id that the application is using by default (for translations and ICU expressions).
  28136. */
  28137. const DEFAULT_LOCALE_ID = 'en-US';
  28138. /**
  28139. * USD currency code that the application uses by default for CurrencyPipe when no
  28140. * DEFAULT_CURRENCY_CODE is provided.
  28141. */
  28142. const USD_CURRENCY_CODE = 'USD';
  28143. /**
  28144. * Marks that the next string is an element name.
  28145. *
  28146. * See `I18nMutateOpCodes` documentation.
  28147. */
  28148. const ELEMENT_MARKER = {
  28149. marker: 'element',
  28150. };
  28151. /**
  28152. * Marks that the next string is comment text need for ICU.
  28153. *
  28154. * See `I18nMutateOpCodes` documentation.
  28155. */
  28156. const ICU_MARKER = {
  28157. marker: 'ICU',
  28158. };
  28159. /**
  28160. * See `I18nCreateOpCodes`
  28161. */
  28162. var I18nCreateOpCode;
  28163. (function (I18nCreateOpCode) {
  28164. /**
  28165. * Number of bits to shift index so that it can be combined with the `APPEND_EAGERLY` and
  28166. * `COMMENT`.
  28167. */
  28168. I18nCreateOpCode[I18nCreateOpCode["SHIFT"] = 2] = "SHIFT";
  28169. /**
  28170. * Should the node be appended to parent immediately after creation.
  28171. */
  28172. I18nCreateOpCode[I18nCreateOpCode["APPEND_EAGERLY"] = 1] = "APPEND_EAGERLY";
  28173. /**
  28174. * If set the node should be comment (rather than a text) node.
  28175. */
  28176. I18nCreateOpCode[I18nCreateOpCode["COMMENT"] = 2] = "COMMENT";
  28177. })(I18nCreateOpCode || (I18nCreateOpCode = {}));
  28178. /**
  28179. * The locale id that the application is currently using (for translations and ICU expressions).
  28180. * This is the ivy version of `LOCALE_ID` that was defined as an injection token for the view engine
  28181. * but is now defined as a global value.
  28182. */
  28183. let LOCALE_ID$1 = DEFAULT_LOCALE_ID;
  28184. /**
  28185. * Sets the locale id that will be used for translations and ICU expressions.
  28186. * This is the ivy version of `LOCALE_ID` that was defined as an injection token for the view engine
  28187. * but is now defined as a global value.
  28188. *
  28189. * @param localeId
  28190. */
  28191. function setLocaleId(localeId) {
  28192. ngDevMode && assertDefined(localeId, `Expected localeId to be defined`);
  28193. if (typeof localeId === 'string') {
  28194. LOCALE_ID$1 = localeId.toLowerCase().replace(/_/g, '-');
  28195. }
  28196. }
  28197. /**
  28198. * Gets the locale id that will be used for translations and ICU expressions.
  28199. * This is the ivy version of `LOCALE_ID` that was defined as an injection token for the view engine
  28200. * but is now defined as a global value.
  28201. */
  28202. function getLocaleId() {
  28203. return LOCALE_ID$1;
  28204. }
  28205. /**
  28206. * Keep track of which input bindings in `ɵɵi18nExp` have changed.
  28207. *
  28208. * This is used to efficiently update expressions in i18n only when the corresponding input has
  28209. * changed.
  28210. *
  28211. * 1) Each bit represents which of the `ɵɵi18nExp` has changed.
  28212. * 2) There are 32 bits allowed in JS.
  28213. * 3) Bit 32 is special as it is shared for all changes past 32. (In other words if you have more
  28214. * than 32 `ɵɵi18nExp` then all changes past 32nd `ɵɵi18nExp` will be mapped to same bit. This means
  28215. * that we may end up changing more than we need to. But i18n expressions with 32 bindings is rare
  28216. * so in practice it should not be an issue.)
  28217. */
  28218. let changeMask = 0b0;
  28219. /**
  28220. * Keeps track of which bit needs to be updated in `changeMask`
  28221. *
  28222. * This value gets incremented on every call to `ɵɵi18nExp`
  28223. */
  28224. let changeMaskCounter = 0;
  28225. /**
  28226. * Keep track of which input bindings in `ɵɵi18nExp` have changed.
  28227. *
  28228. * `setMaskBit` gets invoked by each call to `ɵɵi18nExp`.
  28229. *
  28230. * @param hasChange did `ɵɵi18nExp` detect a change.
  28231. */
  28232. function setMaskBit(hasChange) {
  28233. if (hasChange) {
  28234. changeMask = changeMask | (1 << Math.min(changeMaskCounter, 31));
  28235. }
  28236. changeMaskCounter++;
  28237. }
  28238. function applyI18n(tView, lView, index) {
  28239. if (changeMaskCounter > 0) {
  28240. ngDevMode && assertDefined(tView, `tView should be defined`);
  28241. const tI18n = tView.data[index];
  28242. // When `index` points to an `ɵɵi18nAttributes` then we have an array otherwise `TI18n`
  28243. const updateOpCodes = Array.isArray(tI18n)
  28244. ? tI18n
  28245. : tI18n.update;
  28246. const bindingsStartIndex = getBindingIndex() - changeMaskCounter - 1;
  28247. applyUpdateOpCodes(tView, lView, updateOpCodes, bindingsStartIndex, changeMask);
  28248. }
  28249. // Reset changeMask & maskBit to default for the next update cycle
  28250. changeMask = 0b0;
  28251. changeMaskCounter = 0;
  28252. }
  28253. function createNodeWithoutHydration(lView, textOrName, nodeType) {
  28254. const renderer = lView[RENDERER];
  28255. switch (nodeType) {
  28256. case Node.COMMENT_NODE:
  28257. return createCommentNode(renderer, textOrName);
  28258. case Node.TEXT_NODE:
  28259. return createTextNode(renderer, textOrName);
  28260. case Node.ELEMENT_NODE:
  28261. return createElementNode(renderer, textOrName, null);
  28262. }
  28263. }
  28264. let _locateOrCreateNode = (lView, index, textOrName, nodeType) => {
  28265. lastNodeWasCreated(true);
  28266. return createNodeWithoutHydration(lView, textOrName, nodeType);
  28267. };
  28268. function locateOrCreateNodeImpl(lView, index, textOrName, nodeType) {
  28269. const hydrationInfo = lView[HYDRATION];
  28270. const noOffsetIndex = index - HEADER_OFFSET;
  28271. const isNodeCreationMode = !isI18nHydrationSupportEnabled() ||
  28272. !hydrationInfo ||
  28273. isInSkipHydrationBlock$1() ||
  28274. isDisconnectedNode$1(hydrationInfo, noOffsetIndex);
  28275. lastNodeWasCreated(isNodeCreationMode);
  28276. if (isNodeCreationMode) {
  28277. return createNodeWithoutHydration(lView, textOrName, nodeType);
  28278. }
  28279. const native = locateI18nRNodeByIndex(hydrationInfo, noOffsetIndex);
  28280. // TODO: Improve error handling
  28281. //
  28282. // Other hydration paths use validateMatchingNode() in order to provide
  28283. // detailed information in development mode about the expected DOM.
  28284. // However, not every node in an i18n block has a TNode. Instead, we
  28285. // need to be able to use the AST to generate a similar message.
  28286. ngDevMode && assertDefined(native, 'expected native element');
  28287. ngDevMode && assertEqual(native.nodeType, nodeType, 'expected matching nodeType');
  28288. ngDevMode &&
  28289. nodeType === Node.ELEMENT_NODE &&
  28290. assertEqual(native.tagName.toLowerCase(), textOrName.toLowerCase(), 'expecting matching tagName');
  28291. ngDevMode && markRNodeAsClaimedByHydration(native);
  28292. return native;
  28293. }
  28294. function enableLocateOrCreateI18nNodeImpl() {
  28295. _locateOrCreateNode = locateOrCreateNodeImpl;
  28296. }
  28297. /**
  28298. * Apply `I18nCreateOpCodes` op-codes as stored in `TI18n.create`.
  28299. *
  28300. * Creates text (and comment) nodes which are internationalized.
  28301. *
  28302. * @param lView Current lView
  28303. * @param createOpCodes Set of op-codes to apply
  28304. * @param parentRNode Parent node (so that direct children can be added eagerly) or `null` if it is
  28305. * a root node.
  28306. * @param insertInFrontOf DOM node that should be used as an anchor.
  28307. */
  28308. function applyCreateOpCodes(lView, createOpCodes, parentRNode, insertInFrontOf) {
  28309. const renderer = lView[RENDERER];
  28310. for (let i = 0; i < createOpCodes.length; i++) {
  28311. const opCode = createOpCodes[i++];
  28312. const text = createOpCodes[i];
  28313. const isComment = (opCode & I18nCreateOpCode.COMMENT) === I18nCreateOpCode.COMMENT;
  28314. const appendNow = (opCode & I18nCreateOpCode.APPEND_EAGERLY) === I18nCreateOpCode.APPEND_EAGERLY;
  28315. const index = opCode >>> I18nCreateOpCode.SHIFT;
  28316. let rNode = lView[index];
  28317. let lastNodeWasCreated = false;
  28318. if (rNode === null) {
  28319. // We only create new DOM nodes if they don't already exist: If ICU switches case back to a
  28320. // case which was already instantiated, no need to create new DOM nodes.
  28321. rNode = lView[index] = _locateOrCreateNode(lView, index, text, isComment ? Node.COMMENT_NODE : Node.TEXT_NODE);
  28322. lastNodeWasCreated = wasLastNodeCreated();
  28323. }
  28324. if (appendNow && parentRNode !== null && lastNodeWasCreated) {
  28325. nativeInsertBefore(renderer, parentRNode, rNode, insertInFrontOf, false);
  28326. }
  28327. }
  28328. }
  28329. /**
  28330. * Apply `I18nMutateOpCodes` OpCodes.
  28331. *
  28332. * @param tView Current `TView`
  28333. * @param mutableOpCodes Mutable OpCodes to process
  28334. * @param lView Current `LView`
  28335. * @param anchorRNode place where the i18n node should be inserted.
  28336. */
  28337. function applyMutableOpCodes(tView, mutableOpCodes, lView, anchorRNode) {
  28338. ngDevMode && assertDomNode(anchorRNode);
  28339. const renderer = lView[RENDERER];
  28340. // `rootIdx` represents the node into which all inserts happen.
  28341. let rootIdx = null;
  28342. // `rootRNode` represents the real node into which we insert. This can be different from
  28343. // `lView[rootIdx]` if we have projection.
  28344. // - null we don't have a parent (as can be the case in when we are inserting into a root of
  28345. // LView which has no parent.)
  28346. // - `RElement` The element representing the root after taking projection into account.
  28347. let rootRNode;
  28348. for (let i = 0; i < mutableOpCodes.length; i++) {
  28349. const opCode = mutableOpCodes[i];
  28350. if (typeof opCode == 'string') {
  28351. const textNodeIndex = mutableOpCodes[++i];
  28352. if (lView[textNodeIndex] === null) {
  28353. ngDevMode && ngDevMode.rendererCreateTextNode++;
  28354. ngDevMode && assertIndexInRange(lView, textNodeIndex);
  28355. lView[textNodeIndex] = _locateOrCreateNode(lView, textNodeIndex, opCode, Node.TEXT_NODE);
  28356. }
  28357. }
  28358. else if (typeof opCode == 'number') {
  28359. switch (opCode & 1 /* IcuCreateOpCode.MASK_INSTRUCTION */) {
  28360. case 0 /* IcuCreateOpCode.AppendChild */:
  28361. const parentIdx = getParentFromIcuCreateOpCode(opCode);
  28362. if (rootIdx === null) {
  28363. // The first operation should save the `rootIdx` because the first operation
  28364. // must insert into the root. (Only subsequent operations can insert into a dynamic
  28365. // parent)
  28366. rootIdx = parentIdx;
  28367. rootRNode = renderer.parentNode(anchorRNode);
  28368. }
  28369. let insertInFrontOf;
  28370. let parentRNode;
  28371. if (parentIdx === rootIdx) {
  28372. insertInFrontOf = anchorRNode;
  28373. parentRNode = rootRNode;
  28374. }
  28375. else {
  28376. insertInFrontOf = null;
  28377. parentRNode = unwrapRNode(lView[parentIdx]);
  28378. }
  28379. // FIXME(misko): Refactor with `processI18nText`
  28380. if (parentRNode !== null) {
  28381. // This can happen if the `LView` we are adding to is not attached to a parent `LView`.
  28382. // In such a case there is no "root" we can attach to. This is fine, as we still need to
  28383. // create the elements. When the `LView` gets later added to a parent these "root" nodes
  28384. // get picked up and added.
  28385. ngDevMode && assertDomNode(parentRNode);
  28386. const refIdx = getRefFromIcuCreateOpCode(opCode);
  28387. ngDevMode && assertGreaterThan(refIdx, HEADER_OFFSET, 'Missing ref');
  28388. // `unwrapRNode` is not needed here as all of these point to RNodes as part of the i18n
  28389. // which can't have components.
  28390. const child = lView[refIdx];
  28391. ngDevMode && assertDomNode(child);
  28392. nativeInsertBefore(renderer, parentRNode, child, insertInFrontOf, false);
  28393. const tIcu = getTIcu(tView, refIdx);
  28394. if (tIcu !== null && typeof tIcu === 'object') {
  28395. // If we just added a comment node which has ICU then that ICU may have already been
  28396. // rendered and therefore we need to re-add it here.
  28397. ngDevMode && assertTIcu(tIcu);
  28398. const caseIndex = getCurrentICUCaseIndex(tIcu, lView);
  28399. if (caseIndex !== null) {
  28400. applyMutableOpCodes(tView, tIcu.create[caseIndex], lView, lView[tIcu.anchorIdx]);
  28401. }
  28402. }
  28403. }
  28404. break;
  28405. case 1 /* IcuCreateOpCode.Attr */:
  28406. const elementNodeIndex = opCode >>> 1 /* IcuCreateOpCode.SHIFT_REF */;
  28407. const attrName = mutableOpCodes[++i];
  28408. const attrValue = mutableOpCodes[++i];
  28409. // This code is used for ICU expressions only, since we don't support
  28410. // directives/components in ICUs, we don't need to worry about inputs here
  28411. setElementAttribute(renderer, getNativeByIndex(elementNodeIndex, lView), null, null, attrName, attrValue, null);
  28412. break;
  28413. default:
  28414. if (ngDevMode) {
  28415. throw new RuntimeError(700 /* RuntimeErrorCode.INVALID_I18N_STRUCTURE */, `Unable to determine the type of mutate operation for "${opCode}"`);
  28416. }
  28417. }
  28418. }
  28419. else {
  28420. switch (opCode) {
  28421. case ICU_MARKER:
  28422. const commentValue = mutableOpCodes[++i];
  28423. const commentNodeIndex = mutableOpCodes[++i];
  28424. if (lView[commentNodeIndex] === null) {
  28425. ngDevMode &&
  28426. assertEqual(typeof commentValue, 'string', `Expected "${commentValue}" to be a comment node value`);
  28427. ngDevMode && ngDevMode.rendererCreateComment++;
  28428. ngDevMode && assertIndexInExpandoRange(lView, commentNodeIndex);
  28429. const commentRNode = (lView[commentNodeIndex] = _locateOrCreateNode(lView, commentNodeIndex, commentValue, Node.COMMENT_NODE));
  28430. // FIXME(misko): Attaching patch data is only needed for the root (Also add tests)
  28431. attachPatchData(commentRNode, lView);
  28432. }
  28433. break;
  28434. case ELEMENT_MARKER:
  28435. const tagName = mutableOpCodes[++i];
  28436. const elementNodeIndex = mutableOpCodes[++i];
  28437. if (lView[elementNodeIndex] === null) {
  28438. ngDevMode &&
  28439. assertEqual(typeof tagName, 'string', `Expected "${tagName}" to be an element node tag name`);
  28440. ngDevMode && ngDevMode.rendererCreateElement++;
  28441. ngDevMode && assertIndexInExpandoRange(lView, elementNodeIndex);
  28442. const elementRNode = (lView[elementNodeIndex] = _locateOrCreateNode(lView, elementNodeIndex, tagName, Node.ELEMENT_NODE));
  28443. // FIXME(misko): Attaching patch data is only needed for the root (Also add tests)
  28444. attachPatchData(elementRNode, lView);
  28445. }
  28446. break;
  28447. default:
  28448. ngDevMode &&
  28449. throwError(`Unable to determine the type of mutate operation for "${opCode}"`);
  28450. }
  28451. }
  28452. }
  28453. }
  28454. /**
  28455. * Apply `I18nUpdateOpCodes` OpCodes
  28456. *
  28457. * @param tView Current `TView`
  28458. * @param lView Current `LView`
  28459. * @param updateOpCodes OpCodes to process
  28460. * @param bindingsStartIndex Location of the first `ɵɵi18nApply`
  28461. * @param changeMask Each bit corresponds to a `ɵɵi18nExp` (Counting backwards from
  28462. * `bindingsStartIndex`)
  28463. */
  28464. function applyUpdateOpCodes(tView, lView, updateOpCodes, bindingsStartIndex, changeMask) {
  28465. for (let i = 0; i < updateOpCodes.length; i++) {
  28466. // bit code to check if we should apply the next update
  28467. const checkBit = updateOpCodes[i];
  28468. // Number of opCodes to skip until next set of update codes
  28469. const skipCodes = updateOpCodes[++i];
  28470. if (checkBit & changeMask) {
  28471. // The value has been updated since last checked
  28472. let value = '';
  28473. for (let j = i + 1; j <= i + skipCodes; j++) {
  28474. const opCode = updateOpCodes[j];
  28475. if (typeof opCode == 'string') {
  28476. value += opCode;
  28477. }
  28478. else if (typeof opCode == 'number') {
  28479. if (opCode < 0) {
  28480. // Negative opCode represent `i18nExp` values offset.
  28481. value += renderStringify(lView[bindingsStartIndex - opCode]);
  28482. }
  28483. else {
  28484. const nodeIndex = opCode >>> 2 /* I18nUpdateOpCode.SHIFT_REF */;
  28485. switch (opCode & 3 /* I18nUpdateOpCode.MASK_OPCODE */) {
  28486. case 1 /* I18nUpdateOpCode.Attr */:
  28487. const propName = updateOpCodes[++j];
  28488. const sanitizeFn = updateOpCodes[++j];
  28489. const tNodeOrTagName = tView.data[nodeIndex];
  28490. ngDevMode && assertDefined(tNodeOrTagName, 'Experting TNode or string');
  28491. if (typeof tNodeOrTagName === 'string') {
  28492. // IF we don't have a `TNode`, then we are an element in ICU (as ICU content does
  28493. // not have TNode), in which case we know that there are no directives, and hence
  28494. // we use attribute setting.
  28495. setElementAttribute(lView[RENDERER], lView[nodeIndex], null, tNodeOrTagName, propName, value, sanitizeFn);
  28496. }
  28497. else {
  28498. elementPropertyInternal(tView, tNodeOrTagName, lView, propName, value, lView[RENDERER], sanitizeFn, false);
  28499. }
  28500. break;
  28501. case 0 /* I18nUpdateOpCode.Text */:
  28502. const rText = lView[nodeIndex];
  28503. rText !== null && updateTextNode(lView[RENDERER], rText, value);
  28504. break;
  28505. case 2 /* I18nUpdateOpCode.IcuSwitch */:
  28506. applyIcuSwitchCase(tView, getTIcu(tView, nodeIndex), lView, value);
  28507. break;
  28508. case 3 /* I18nUpdateOpCode.IcuUpdate */:
  28509. applyIcuUpdateCase(tView, getTIcu(tView, nodeIndex), bindingsStartIndex, lView);
  28510. break;
  28511. }
  28512. }
  28513. }
  28514. }
  28515. }
  28516. else {
  28517. const opCode = updateOpCodes[i + 1];
  28518. if (opCode > 0 && (opCode & 3 /* I18nUpdateOpCode.MASK_OPCODE */) === 3 /* I18nUpdateOpCode.IcuUpdate */) {
  28519. // Special case for the `icuUpdateCase`. It could be that the mask did not match, but
  28520. // we still need to execute `icuUpdateCase` because the case has changed recently due to
  28521. // previous `icuSwitchCase` instruction. (`icuSwitchCase` and `icuUpdateCase` always come in
  28522. // pairs.)
  28523. const nodeIndex = opCode >>> 2 /* I18nUpdateOpCode.SHIFT_REF */;
  28524. const tIcu = getTIcu(tView, nodeIndex);
  28525. const currentIndex = lView[tIcu.currentCaseLViewIndex];
  28526. if (currentIndex < 0) {
  28527. applyIcuUpdateCase(tView, tIcu, bindingsStartIndex, lView);
  28528. }
  28529. }
  28530. }
  28531. i += skipCodes;
  28532. }
  28533. }
  28534. /**
  28535. * Apply OpCodes associated with updating an existing ICU.
  28536. *
  28537. * @param tView Current `TView`
  28538. * @param tIcu Current `TIcu`
  28539. * @param bindingsStartIndex Location of the first `ɵɵi18nApply`
  28540. * @param lView Current `LView`
  28541. */
  28542. function applyIcuUpdateCase(tView, tIcu, bindingsStartIndex, lView) {
  28543. ngDevMode && assertIndexInRange(lView, tIcu.currentCaseLViewIndex);
  28544. let activeCaseIndex = lView[tIcu.currentCaseLViewIndex];
  28545. if (activeCaseIndex !== null) {
  28546. let mask = changeMask;
  28547. if (activeCaseIndex < 0) {
  28548. // Clear the flag.
  28549. // Negative number means that the ICU was freshly created and we need to force the update.
  28550. activeCaseIndex = lView[tIcu.currentCaseLViewIndex] = ~activeCaseIndex;
  28551. // -1 is same as all bits on, which simulates creation since it marks all bits dirty
  28552. mask = -1;
  28553. }
  28554. applyUpdateOpCodes(tView, lView, tIcu.update[activeCaseIndex], bindingsStartIndex, mask);
  28555. }
  28556. }
  28557. /**
  28558. * Apply OpCodes associated with switching a case on ICU.
  28559. *
  28560. * This involves tearing down existing case and than building up a new case.
  28561. *
  28562. * @param tView Current `TView`
  28563. * @param tIcu Current `TIcu`
  28564. * @param lView Current `LView`
  28565. * @param value Value of the case to update to.
  28566. */
  28567. function applyIcuSwitchCase(tView, tIcu, lView, value) {
  28568. // Rebuild a new case for this ICU
  28569. const caseIndex = getCaseIndex(tIcu, value);
  28570. let activeCaseIndex = getCurrentICUCaseIndex(tIcu, lView);
  28571. if (activeCaseIndex !== caseIndex) {
  28572. applyIcuSwitchCaseRemove(tView, tIcu, lView);
  28573. lView[tIcu.currentCaseLViewIndex] = caseIndex === null ? null : ~caseIndex;
  28574. if (caseIndex !== null) {
  28575. // Add the nodes for the new case
  28576. const anchorRNode = lView[tIcu.anchorIdx];
  28577. if (anchorRNode) {
  28578. ngDevMode && assertDomNode(anchorRNode);
  28579. applyMutableOpCodes(tView, tIcu.create[caseIndex], lView, anchorRNode);
  28580. }
  28581. claimDehydratedIcuCase(lView, tIcu.anchorIdx, caseIndex);
  28582. }
  28583. }
  28584. }
  28585. /**
  28586. * Apply OpCodes associated with tearing ICU case.
  28587. *
  28588. * This involves tearing down existing case and than building up a new case.
  28589. *
  28590. * @param tView Current `TView`
  28591. * @param tIcu Current `TIcu`
  28592. * @param lView Current `LView`
  28593. */
  28594. function applyIcuSwitchCaseRemove(tView, tIcu, lView) {
  28595. let activeCaseIndex = getCurrentICUCaseIndex(tIcu, lView);
  28596. if (activeCaseIndex !== null) {
  28597. const removeCodes = tIcu.remove[activeCaseIndex];
  28598. for (let i = 0; i < removeCodes.length; i++) {
  28599. const nodeOrIcuIndex = removeCodes[i];
  28600. if (nodeOrIcuIndex > 0) {
  28601. // Positive numbers are `RNode`s.
  28602. const rNode = getNativeByIndex(nodeOrIcuIndex, lView);
  28603. rNode !== null && nativeRemoveNode(lView[RENDERER], rNode);
  28604. }
  28605. else {
  28606. // Negative numbers are ICUs
  28607. applyIcuSwitchCaseRemove(tView, getTIcu(tView, ~nodeOrIcuIndex), lView);
  28608. }
  28609. }
  28610. }
  28611. }
  28612. /**
  28613. * Returns the index of the current case of an ICU expression depending on the main binding value
  28614. *
  28615. * @param icuExpression
  28616. * @param bindingValue The value of the main binding used by this ICU expression
  28617. */
  28618. function getCaseIndex(icuExpression, bindingValue) {
  28619. let index = icuExpression.cases.indexOf(bindingValue);
  28620. if (index === -1) {
  28621. switch (icuExpression.type) {
  28622. case 1 /* IcuType.plural */: {
  28623. const resolvedCase = getPluralCase(bindingValue, getLocaleId());
  28624. index = icuExpression.cases.indexOf(resolvedCase);
  28625. if (index === -1 && resolvedCase !== 'other') {
  28626. index = icuExpression.cases.indexOf('other');
  28627. }
  28628. break;
  28629. }
  28630. case 0 /* IcuType.select */: {
  28631. index = icuExpression.cases.indexOf('other');
  28632. break;
  28633. }
  28634. }
  28635. }
  28636. return index === -1 ? null : index;
  28637. }
  28638. /**
  28639. * Converts `I18nCreateOpCodes` array into a human readable format.
  28640. *
  28641. * This function is attached to the `I18nCreateOpCodes.debug` property if `ngDevMode` is enabled.
  28642. * This function provides a human readable view of the opcodes. This is useful when debugging the
  28643. * application as well as writing more readable tests.
  28644. *
  28645. * @param this `I18nCreateOpCodes` if attached as a method.
  28646. * @param opcodes `I18nCreateOpCodes` if invoked as a function.
  28647. */
  28648. function i18nCreateOpCodesToString(opcodes) {
  28649. const createOpCodes = opcodes || (Array.isArray(this) ? this : []);
  28650. let lines = [];
  28651. for (let i = 0; i < createOpCodes.length; i++) {
  28652. const opCode = createOpCodes[i++];
  28653. const text = createOpCodes[i];
  28654. const isComment = (opCode & I18nCreateOpCode.COMMENT) === I18nCreateOpCode.COMMENT;
  28655. const appendNow = (opCode & I18nCreateOpCode.APPEND_EAGERLY) === I18nCreateOpCode.APPEND_EAGERLY;
  28656. const index = opCode >>> I18nCreateOpCode.SHIFT;
  28657. lines.push(`lView[${index}] = document.${isComment ? 'createComment' : 'createText'}(${JSON.stringify(text)});`);
  28658. if (appendNow) {
  28659. lines.push(`parent.appendChild(lView[${index}]);`);
  28660. }
  28661. }
  28662. return lines;
  28663. }
  28664. /**
  28665. * Converts `I18nUpdateOpCodes` array into a human readable format.
  28666. *
  28667. * This function is attached to the `I18nUpdateOpCodes.debug` property if `ngDevMode` is enabled.
  28668. * This function provides a human readable view of the opcodes. This is useful when debugging the
  28669. * application as well as writing more readable tests.
  28670. *
  28671. * @param this `I18nUpdateOpCodes` if attached as a method.
  28672. * @param opcodes `I18nUpdateOpCodes` if invoked as a function.
  28673. */
  28674. function i18nUpdateOpCodesToString(opcodes) {
  28675. const parser = new OpCodeParser(opcodes || (Array.isArray(this) ? this : []));
  28676. let lines = [];
  28677. function consumeOpCode(value) {
  28678. const ref = value >>> 2 /* I18nUpdateOpCode.SHIFT_REF */;
  28679. const opCode = value & 3 /* I18nUpdateOpCode.MASK_OPCODE */;
  28680. switch (opCode) {
  28681. case 0 /* I18nUpdateOpCode.Text */:
  28682. return `(lView[${ref}] as Text).textContent = $$$`;
  28683. case 1 /* I18nUpdateOpCode.Attr */:
  28684. const attrName = parser.consumeString();
  28685. const sanitizationFn = parser.consumeFunction();
  28686. const value = sanitizationFn ? `(${sanitizationFn})($$$)` : '$$$';
  28687. return `(lView[${ref}] as Element).setAttribute('${attrName}', ${value})`;
  28688. case 2 /* I18nUpdateOpCode.IcuSwitch */:
  28689. return `icuSwitchCase(${ref}, $$$)`;
  28690. case 3 /* I18nUpdateOpCode.IcuUpdate */:
  28691. return `icuUpdateCase(${ref})`;
  28692. }
  28693. throw new Error('unexpected OpCode');
  28694. }
  28695. while (parser.hasMore()) {
  28696. let mask = parser.consumeNumber();
  28697. let size = parser.consumeNumber();
  28698. const end = parser.i + size;
  28699. const statements = [];
  28700. let statement = '';
  28701. while (parser.i < end) {
  28702. let value = parser.consumeNumberOrString();
  28703. if (typeof value === 'string') {
  28704. statement += value;
  28705. }
  28706. else if (value < 0) {
  28707. // Negative numbers are ref indexes
  28708. // Here `i` refers to current binding index. It is to signify that the value is relative,
  28709. // rather than absolute.
  28710. statement += '${lView[i' + value + ']}';
  28711. }
  28712. else {
  28713. // Positive numbers are operations.
  28714. const opCodeText = consumeOpCode(value);
  28715. statements.push(opCodeText.replace('$$$', '`' + statement + '`') + ';');
  28716. statement = '';
  28717. }
  28718. }
  28719. lines.push(`if (mask & 0b${mask.toString(2)}) { ${statements.join(' ')} }`);
  28720. }
  28721. return lines;
  28722. }
  28723. /**
  28724. * Converts `I18nCreateOpCodes` array into a human readable format.
  28725. *
  28726. * This function is attached to the `I18nCreateOpCodes.debug` if `ngDevMode` is enabled. This
  28727. * function provides a human readable view of the opcodes. This is useful when debugging the
  28728. * application as well as writing more readable tests.
  28729. *
  28730. * @param this `I18nCreateOpCodes` if attached as a method.
  28731. * @param opcodes `I18nCreateOpCodes` if invoked as a function.
  28732. */
  28733. function icuCreateOpCodesToString(opcodes) {
  28734. const parser = new OpCodeParser(opcodes || (Array.isArray(this) ? this : []));
  28735. let lines = [];
  28736. function consumeOpCode(opCode) {
  28737. const parent = getParentFromIcuCreateOpCode(opCode);
  28738. const ref = getRefFromIcuCreateOpCode(opCode);
  28739. switch (getInstructionFromIcuCreateOpCode(opCode)) {
  28740. case 0 /* IcuCreateOpCode.AppendChild */:
  28741. return `(lView[${parent}] as Element).appendChild(lView[${lastRef}])`;
  28742. case 1 /* IcuCreateOpCode.Attr */:
  28743. return `(lView[${ref}] as Element).setAttribute("${parser.consumeString()}", "${parser.consumeString()}")`;
  28744. }
  28745. throw new Error('Unexpected OpCode: ' + getInstructionFromIcuCreateOpCode(opCode));
  28746. }
  28747. let lastRef = -1;
  28748. while (parser.hasMore()) {
  28749. let value = parser.consumeNumberStringOrMarker();
  28750. if (value === ICU_MARKER) {
  28751. const text = parser.consumeString();
  28752. lastRef = parser.consumeNumber();
  28753. lines.push(`lView[${lastRef}] = document.createComment("${text}")`);
  28754. }
  28755. else if (value === ELEMENT_MARKER) {
  28756. const text = parser.consumeString();
  28757. lastRef = parser.consumeNumber();
  28758. lines.push(`lView[${lastRef}] = document.createElement("${text}")`);
  28759. }
  28760. else if (typeof value === 'string') {
  28761. lastRef = parser.consumeNumber();
  28762. lines.push(`lView[${lastRef}] = document.createTextNode("${value}")`);
  28763. }
  28764. else if (typeof value === 'number') {
  28765. const line = consumeOpCode(value);
  28766. line && lines.push(line);
  28767. }
  28768. else {
  28769. throw new Error('Unexpected value');
  28770. }
  28771. }
  28772. return lines;
  28773. }
  28774. /**
  28775. * Converts `I18nRemoveOpCodes` array into a human readable format.
  28776. *
  28777. * This function is attached to the `I18nRemoveOpCodes.debug` if `ngDevMode` is enabled. This
  28778. * function provides a human readable view of the opcodes. This is useful when debugging the
  28779. * application as well as writing more readable tests.
  28780. *
  28781. * @param this `I18nRemoveOpCodes` if attached as a method.
  28782. * @param opcodes `I18nRemoveOpCodes` if invoked as a function.
  28783. */
  28784. function i18nRemoveOpCodesToString(opcodes) {
  28785. const removeCodes = opcodes || (Array.isArray(this) ? this : []);
  28786. let lines = [];
  28787. for (let i = 0; i < removeCodes.length; i++) {
  28788. const nodeOrIcuIndex = removeCodes[i];
  28789. if (nodeOrIcuIndex > 0) {
  28790. // Positive numbers are `RNode`s.
  28791. lines.push(`remove(lView[${nodeOrIcuIndex}])`);
  28792. }
  28793. else {
  28794. // Negative numbers are ICUs
  28795. lines.push(`removeNestedICU(${~nodeOrIcuIndex})`);
  28796. }
  28797. }
  28798. return lines;
  28799. }
  28800. class OpCodeParser {
  28801. i = 0;
  28802. codes;
  28803. constructor(codes) {
  28804. this.codes = codes;
  28805. }
  28806. hasMore() {
  28807. return this.i < this.codes.length;
  28808. }
  28809. consumeNumber() {
  28810. let value = this.codes[this.i++];
  28811. assertNumber(value, 'expecting number in OpCode');
  28812. return value;
  28813. }
  28814. consumeString() {
  28815. let value = this.codes[this.i++];
  28816. assertString(value, 'expecting string in OpCode');
  28817. return value;
  28818. }
  28819. consumeFunction() {
  28820. let value = this.codes[this.i++];
  28821. if (value === null || typeof value === 'function') {
  28822. return value;
  28823. }
  28824. throw new Error('expecting function in OpCode');
  28825. }
  28826. consumeNumberOrString() {
  28827. let value = this.codes[this.i++];
  28828. if (typeof value === 'string') {
  28829. return value;
  28830. }
  28831. assertNumber(value, 'expecting number or string in OpCode');
  28832. return value;
  28833. }
  28834. consumeNumberStringOrMarker() {
  28835. let value = this.codes[this.i++];
  28836. if (typeof value === 'string' ||
  28837. typeof value === 'number' ||
  28838. value == ICU_MARKER ||
  28839. value == ELEMENT_MARKER) {
  28840. return value;
  28841. }
  28842. assertNumber(value, 'expecting number, string, ICU_MARKER or ELEMENT_MARKER in OpCode');
  28843. return value;
  28844. }
  28845. }
  28846. const BINDING_REGEXP = /�(\d+):?\d*�/gi;
  28847. const ICU_REGEXP = /({\s*�\d+:?\d*�\s*,\s*\S{6}\s*,[\s\S]*})/gi;
  28848. const NESTED_ICU = /�(\d+)�/;
  28849. const ICU_BLOCK_REGEXP = /^\s*(�\d+:?\d*�)\s*,\s*(select|plural)\s*,/;
  28850. const MARKER = `�`;
  28851. const SUBTEMPLATE_REGEXP = /�\/?\*(\d+:\d+)�/gi;
  28852. const PH_REGEXP = /�(\/?[#*]\d+):?\d*�/gi;
  28853. /**
  28854. * Angular uses the special entity &ngsp; as a placeholder for non-removable space.
  28855. * It's replaced by the 0xE500 PUA (Private Use Areas) unicode character and later on replaced by a
  28856. * space.
  28857. * We are re-implementing the same idea since translations might contain this special character.
  28858. */
  28859. const NGSP_UNICODE_REGEXP = /\uE500/g;
  28860. function replaceNgsp(value) {
  28861. return value.replace(NGSP_UNICODE_REGEXP, ' ');
  28862. }
  28863. /**
  28864. * Patch a `debug` property getter on top of the existing object.
  28865. *
  28866. * NOTE: always call this method with `ngDevMode && attachDebugObject(...)`
  28867. *
  28868. * @param obj Object to patch
  28869. * @param debugGetter Getter returning a value to patch
  28870. */
  28871. function attachDebugGetter(obj, debugGetter) {
  28872. if (ngDevMode) {
  28873. Object.defineProperty(obj, 'debug', { get: debugGetter, enumerable: false });
  28874. }
  28875. else {
  28876. throw new Error('This method should be guarded with `ngDevMode` so that it can be tree shaken in production!');
  28877. }
  28878. }
  28879. /**
  28880. * Create dynamic nodes from i18n translation block.
  28881. *
  28882. * - Text nodes are created synchronously
  28883. * - TNodes are linked into tree lazily
  28884. *
  28885. * @param tView Current `TView`
  28886. * @parentTNodeIndex index to the parent TNode of this i18n block
  28887. * @param lView Current `LView`
  28888. * @param index Index of `ɵɵi18nStart` instruction.
  28889. * @param message Message to translate.
  28890. * @param subTemplateIndex Index into the sub template of message translation. (ie in case of
  28891. * `ngIf`) (-1 otherwise)
  28892. */
  28893. function i18nStartFirstCreatePass(tView, parentTNodeIndex, lView, index, message, subTemplateIndex) {
  28894. const rootTNode = getCurrentParentTNode();
  28895. const createOpCodes = [];
  28896. const updateOpCodes = [];
  28897. const existingTNodeStack = [[]];
  28898. const astStack = [[]];
  28899. if (ngDevMode) {
  28900. attachDebugGetter(createOpCodes, i18nCreateOpCodesToString);
  28901. attachDebugGetter(updateOpCodes, i18nUpdateOpCodesToString);
  28902. }
  28903. message = getTranslationForTemplate(message, subTemplateIndex);
  28904. const msgParts = replaceNgsp(message).split(PH_REGEXP);
  28905. for (let i = 0; i < msgParts.length; i++) {
  28906. let value = msgParts[i];
  28907. if ((i & 1) === 0) {
  28908. // Even indexes are text (including bindings & ICU expressions)
  28909. const parts = i18nParseTextIntoPartsAndICU(value);
  28910. for (let j = 0; j < parts.length; j++) {
  28911. let part = parts[j];
  28912. if ((j & 1) === 0) {
  28913. // `j` is odd therefore `part` is string
  28914. const text = part;
  28915. ngDevMode && assertString(text, 'Parsed ICU part should be string');
  28916. if (text !== '') {
  28917. i18nStartFirstCreatePassProcessTextNode(astStack[0], tView, rootTNode, existingTNodeStack[0], createOpCodes, updateOpCodes, lView, text);
  28918. }
  28919. }
  28920. else {
  28921. // `j` is Even therefor `part` is an `ICUExpression`
  28922. const icuExpression = part;
  28923. // Verify that ICU expression has the right shape. Translations might contain invalid
  28924. // constructions (while original messages were correct), so ICU parsing at runtime may
  28925. // not succeed (thus `icuExpression` remains a string).
  28926. // Note: we intentionally retain the error here by not using `ngDevMode`, because
  28927. // the value can change based on the locale and users aren't guaranteed to hit
  28928. // an invalid string while they're developing.
  28929. if (typeof icuExpression !== 'object') {
  28930. throw new Error(`Unable to parse ICU expression in "${message}" message.`);
  28931. }
  28932. const icuContainerTNode = createTNodeAndAddOpCode(tView, rootTNode, existingTNodeStack[0], lView, createOpCodes, ngDevMode ? `ICU ${index}:${icuExpression.mainBinding}` : '', true);
  28933. const icuNodeIndex = icuContainerTNode.index;
  28934. ngDevMode &&
  28935. assertGreaterThanOrEqual(icuNodeIndex, HEADER_OFFSET, 'Index must be in absolute LView offset');
  28936. icuStart(astStack[0], tView, lView, updateOpCodes, parentTNodeIndex, icuExpression, icuNodeIndex);
  28937. }
  28938. }
  28939. }
  28940. else {
  28941. // Odd indexes are placeholders (elements and sub-templates)
  28942. // At this point value is something like: '/#1:2' (originally coming from '�/#1:2�')
  28943. const isClosing = value.charCodeAt(0) === 47 /* CharCode.SLASH */;
  28944. const type = value.charCodeAt(isClosing ? 1 : 0);
  28945. ngDevMode && assertOneOf(type, 42 /* CharCode.STAR */, 35 /* CharCode.HASH */);
  28946. const index = HEADER_OFFSET + Number.parseInt(value.substring(isClosing ? 2 : 1));
  28947. if (isClosing) {
  28948. existingTNodeStack.shift();
  28949. astStack.shift();
  28950. setCurrentTNode(getCurrentParentTNode(), false);
  28951. }
  28952. else {
  28953. const tNode = createTNodePlaceholder(tView, existingTNodeStack[0], index);
  28954. existingTNodeStack.unshift([]);
  28955. setCurrentTNode(tNode, true);
  28956. const placeholderNode = {
  28957. kind: 2 /* I18nNodeKind.PLACEHOLDER */,
  28958. index,
  28959. children: [],
  28960. type: type === 35 /* CharCode.HASH */ ? 0 /* I18nPlaceholderType.ELEMENT */ : 1 /* I18nPlaceholderType.SUBTEMPLATE */,
  28961. };
  28962. astStack[0].push(placeholderNode);
  28963. astStack.unshift(placeholderNode.children);
  28964. }
  28965. }
  28966. }
  28967. tView.data[index] = {
  28968. create: createOpCodes,
  28969. update: updateOpCodes,
  28970. ast: astStack[0],
  28971. parentTNodeIndex,
  28972. };
  28973. }
  28974. /**
  28975. * Allocate space in i18n Range add create OpCode instruction to create a text or comment node.
  28976. *
  28977. * @param tView Current `TView` needed to allocate space in i18n range.
  28978. * @param rootTNode Root `TNode` of the i18n block. This node determines if the new TNode will be
  28979. * added as part of the `i18nStart` instruction or as part of the `TNode.insertBeforeIndex`.
  28980. * @param existingTNodes internal state for `addTNodeAndUpdateInsertBeforeIndex`.
  28981. * @param lView Current `LView` needed to allocate space in i18n range.
  28982. * @param createOpCodes Array storing `I18nCreateOpCodes` where new opCodes will be added.
  28983. * @param text Text to be added when the `Text` or `Comment` node will be created.
  28984. * @param isICU true if a `Comment` node for ICU (instead of `Text`) node should be created.
  28985. */
  28986. function createTNodeAndAddOpCode(tView, rootTNode, existingTNodes, lView, createOpCodes, text, isICU) {
  28987. const i18nNodeIdx = allocExpando(tView, lView, 1, null);
  28988. let opCode = i18nNodeIdx << I18nCreateOpCode.SHIFT;
  28989. let parentTNode = getCurrentParentTNode();
  28990. if (rootTNode === parentTNode) {
  28991. // FIXME(misko): A null `parentTNode` should represent when we fall of the `LView` boundary.
  28992. // (there is no parent), but in some circumstances (because we are inconsistent about how we set
  28993. // `previousOrParentTNode`) it could point to `rootTNode` So this is a work around.
  28994. parentTNode = null;
  28995. }
  28996. if (parentTNode === null) {
  28997. // If we don't have a parent that means that we can eagerly add nodes.
  28998. // If we have a parent than these nodes can't be added now (as the parent has not been created
  28999. // yet) and instead the `parentTNode` is responsible for adding it. See
  29000. // `TNode.insertBeforeIndex`
  29001. opCode |= I18nCreateOpCode.APPEND_EAGERLY;
  29002. }
  29003. if (isICU) {
  29004. opCode |= I18nCreateOpCode.COMMENT;
  29005. ensureIcuContainerVisitorLoaded(loadIcuContainerVisitor);
  29006. }
  29007. createOpCodes.push(opCode, text === null ? '' : text);
  29008. // We store `{{?}}` so that when looking at debug `TNodeType.template` we can see where the
  29009. // bindings are.
  29010. const tNode = createTNodeAtIndex(tView, i18nNodeIdx, isICU ? 32 /* TNodeType.Icu */ : 1 /* TNodeType.Text */, text === null ? (ngDevMode ? '{{?}}' : '') : text, null);
  29011. addTNodeAndUpdateInsertBeforeIndex(existingTNodes, tNode);
  29012. const tNodeIdx = tNode.index;
  29013. setCurrentTNode(tNode, false /* Text nodes are self closing */);
  29014. if (parentTNode !== null && rootTNode !== parentTNode) {
  29015. // We are a child of deeper node (rather than a direct child of `i18nStart` instruction.)
  29016. // We have to make sure to add ourselves to the parent.
  29017. setTNodeInsertBeforeIndex(parentTNode, tNodeIdx);
  29018. }
  29019. return tNode;
  29020. }
  29021. /**
  29022. * Processes text node in i18n block.
  29023. *
  29024. * Text nodes can have:
  29025. * - Create instruction in `createOpCodes` for creating the text node.
  29026. * - Allocate spec for text node in i18n range of `LView`
  29027. * - If contains binding:
  29028. * - bindings => allocate space in i18n range of `LView` to store the binding value.
  29029. * - populate `updateOpCodes` with update instructions.
  29030. *
  29031. * @param tView Current `TView`
  29032. * @param rootTNode Root `TNode` of the i18n block. This node determines if the new TNode will
  29033. * be added as part of the `i18nStart` instruction or as part of the
  29034. * `TNode.insertBeforeIndex`.
  29035. * @param existingTNodes internal state for `addTNodeAndUpdateInsertBeforeIndex`.
  29036. * @param createOpCodes Location where the creation OpCodes will be stored.
  29037. * @param lView Current `LView`
  29038. * @param text The translated text (which may contain binding)
  29039. */
  29040. function i18nStartFirstCreatePassProcessTextNode(ast, tView, rootTNode, existingTNodes, createOpCodes, updateOpCodes, lView, text) {
  29041. const hasBinding = text.match(BINDING_REGEXP);
  29042. const tNode = createTNodeAndAddOpCode(tView, rootTNode, existingTNodes, lView, createOpCodes, hasBinding ? null : text, false);
  29043. const index = tNode.index;
  29044. if (hasBinding) {
  29045. generateBindingUpdateOpCodes(updateOpCodes, text, index, null, 0, null);
  29046. }
  29047. ast.push({ kind: 0 /* I18nNodeKind.TEXT */, index });
  29048. }
  29049. /**
  29050. * See `i18nAttributes` above.
  29051. */
  29052. function i18nAttributesFirstPass(tView, index, values) {
  29053. const previousElement = getCurrentTNode();
  29054. const previousElementIndex = previousElement.index;
  29055. const updateOpCodes = [];
  29056. if (ngDevMode) {
  29057. attachDebugGetter(updateOpCodes, i18nUpdateOpCodesToString);
  29058. }
  29059. if (tView.firstCreatePass && tView.data[index] === null) {
  29060. for (let i = 0; i < values.length; i += 2) {
  29061. const attrName = values[i];
  29062. const message = values[i + 1];
  29063. if (message !== '') {
  29064. // Check if attribute value contains an ICU and throw an error if that's the case.
  29065. // ICUs in element attributes are not supported.
  29066. // Note: we intentionally retain the error here by not using `ngDevMode`, because
  29067. // the `value` can change based on the locale and users aren't guaranteed to hit
  29068. // an invalid string while they're developing.
  29069. if (ICU_REGEXP.test(message)) {
  29070. throw new Error(`ICU expressions are not supported in attributes. Message: "${message}".`);
  29071. }
  29072. // i18n attributes that hit this code path are guaranteed to have bindings, because
  29073. // the compiler treats static i18n attributes as regular attribute bindings.
  29074. // Since this may not be the first i18n attribute on this element we need to pass in how
  29075. // many previous bindings there have already been.
  29076. generateBindingUpdateOpCodes(updateOpCodes, message, previousElementIndex, attrName, countBindings(updateOpCodes), null);
  29077. }
  29078. }
  29079. tView.data[index] = updateOpCodes;
  29080. }
  29081. }
  29082. /**
  29083. * Generate the OpCodes to update the bindings of a string.
  29084. *
  29085. * @param updateOpCodes Place where the update opcodes will be stored.
  29086. * @param str The string containing the bindings.
  29087. * @param destinationNode Index of the destination node which will receive the binding.
  29088. * @param attrName Name of the attribute, if the string belongs to an attribute.
  29089. * @param sanitizeFn Sanitization function used to sanitize the string after update, if necessary.
  29090. * @param bindingStart The lView index of the next expression that can be bound via an opCode.
  29091. * @returns The mask value for these bindings
  29092. */
  29093. function generateBindingUpdateOpCodes(updateOpCodes, str, destinationNode, attrName, bindingStart, sanitizeFn) {
  29094. ngDevMode &&
  29095. assertGreaterThanOrEqual(destinationNode, HEADER_OFFSET, 'Index must be in absolute LView offset');
  29096. const maskIndex = updateOpCodes.length; // Location of mask
  29097. const sizeIndex = maskIndex + 1; // location of size for skipping
  29098. updateOpCodes.push(null, null); // Alloc space for mask and size
  29099. const startIndex = maskIndex + 2; // location of first allocation.
  29100. if (ngDevMode) {
  29101. attachDebugGetter(updateOpCodes, i18nUpdateOpCodesToString);
  29102. }
  29103. const textParts = str.split(BINDING_REGEXP);
  29104. let mask = 0;
  29105. for (let j = 0; j < textParts.length; j++) {
  29106. const textValue = textParts[j];
  29107. if (j & 1) {
  29108. // Odd indexes are bindings
  29109. const bindingIndex = bindingStart + parseInt(textValue, 10);
  29110. updateOpCodes.push(-1 - bindingIndex);
  29111. mask = mask | toMaskBit(bindingIndex);
  29112. }
  29113. else if (textValue !== '') {
  29114. // Even indexes are text
  29115. updateOpCodes.push(textValue);
  29116. }
  29117. }
  29118. updateOpCodes.push((destinationNode << 2 /* I18nUpdateOpCode.SHIFT_REF */) |
  29119. (attrName ? 1 /* I18nUpdateOpCode.Attr */ : 0 /* I18nUpdateOpCode.Text */));
  29120. if (attrName) {
  29121. updateOpCodes.push(attrName, sanitizeFn);
  29122. }
  29123. updateOpCodes[maskIndex] = mask;
  29124. updateOpCodes[sizeIndex] = updateOpCodes.length - startIndex;
  29125. return mask;
  29126. }
  29127. /**
  29128. * Count the number of bindings in the given `opCodes`.
  29129. *
  29130. * It could be possible to speed this up, by passing the number of bindings found back from
  29131. * `generateBindingUpdateOpCodes()` to `i18nAttributesFirstPass()` but this would then require more
  29132. * complexity in the code and/or transient objects to be created.
  29133. *
  29134. * Since this function is only called once when the template is instantiated, is trivial in the
  29135. * first instance (since `opCodes` will be an empty array), and it is not common for elements to
  29136. * contain multiple i18n bound attributes, it seems like this is a reasonable compromise.
  29137. */
  29138. function countBindings(opCodes) {
  29139. let count = 0;
  29140. for (let i = 0; i < opCodes.length; i++) {
  29141. const opCode = opCodes[i];
  29142. // Bindings are negative numbers.
  29143. if (typeof opCode === 'number' && opCode < 0) {
  29144. count++;
  29145. }
  29146. }
  29147. return count;
  29148. }
  29149. /**
  29150. * Convert binding index to mask bit.
  29151. *
  29152. * Each index represents a single bit on the bit-mask. Because bit-mask only has 32 bits, we make
  29153. * the 32nd bit share all masks for all bindings higher than 32. Since it is extremely rare to
  29154. * have more than 32 bindings this will be hit very rarely. The downside of hitting this corner
  29155. * case is that we will execute binding code more often than necessary. (penalty of performance)
  29156. */
  29157. function toMaskBit(bindingIndex) {
  29158. return 1 << Math.min(bindingIndex, 31);
  29159. }
  29160. /**
  29161. * Removes everything inside the sub-templates of a message.
  29162. */
  29163. function removeInnerTemplateTranslation(message) {
  29164. let match;
  29165. let res = '';
  29166. let index = 0;
  29167. let inTemplate = false;
  29168. let tagMatched;
  29169. while ((match = SUBTEMPLATE_REGEXP.exec(message)) !== null) {
  29170. if (!inTemplate) {
  29171. res += message.substring(index, match.index + match[0].length);
  29172. tagMatched = match[1];
  29173. inTemplate = true;
  29174. }
  29175. else {
  29176. if (match[0] === `${MARKER}/*${tagMatched}${MARKER}`) {
  29177. index = match.index;
  29178. inTemplate = false;
  29179. }
  29180. }
  29181. }
  29182. ngDevMode &&
  29183. assertEqual(inTemplate, false, `Tag mismatch: unable to find the end of the sub-template in the translation "${message}"`);
  29184. res += message.slice(index);
  29185. return res;
  29186. }
  29187. /**
  29188. * Extracts a part of a message and removes the rest.
  29189. *
  29190. * This method is used for extracting a part of the message associated with a template. A
  29191. * translated message can span multiple templates.
  29192. *
  29193. * Example:
  29194. * ```html
  29195. * <div i18n>Translate <span *ngIf>me</span>!</div>
  29196. * ```
  29197. *
  29198. * @param message The message to crop
  29199. * @param subTemplateIndex Index of the sub-template to extract. If undefined it returns the
  29200. * external template and removes all sub-templates.
  29201. */
  29202. function getTranslationForTemplate(message, subTemplateIndex) {
  29203. if (isRootTemplateMessage(subTemplateIndex)) {
  29204. // We want the root template message, ignore all sub-templates
  29205. return removeInnerTemplateTranslation(message);
  29206. }
  29207. else {
  29208. // We want a specific sub-template
  29209. const start = message.indexOf(`:${subTemplateIndex}${MARKER}`) + 2 + subTemplateIndex.toString().length;
  29210. const end = message.search(new RegExp(`${MARKER}\\/\\*\\d+:${subTemplateIndex}${MARKER}`));
  29211. return removeInnerTemplateTranslation(message.substring(start, end));
  29212. }
  29213. }
  29214. /**
  29215. * Generate the OpCodes for ICU expressions.
  29216. *
  29217. * @param icuExpression
  29218. * @param index Index where the anchor is stored and an optional `TIcuContainerNode`
  29219. * - `lView[anchorIdx]` points to a `Comment` node representing the anchor for the ICU.
  29220. * - `tView.data[anchorIdx]` points to the `TIcuContainerNode` if ICU is root (`null` otherwise)
  29221. */
  29222. function icuStart(ast, tView, lView, updateOpCodes, parentIdx, icuExpression, anchorIdx) {
  29223. ngDevMode && assertDefined(icuExpression, 'ICU expression must be defined');
  29224. let bindingMask = 0;
  29225. const tIcu = {
  29226. type: icuExpression.type,
  29227. currentCaseLViewIndex: allocExpando(tView, lView, 1, null),
  29228. anchorIdx,
  29229. cases: [],
  29230. create: [],
  29231. remove: [],
  29232. update: [],
  29233. };
  29234. addUpdateIcuSwitch(updateOpCodes, icuExpression, anchorIdx);
  29235. setTIcu(tView, anchorIdx, tIcu);
  29236. const values = icuExpression.values;
  29237. const cases = [];
  29238. for (let i = 0; i < values.length; i++) {
  29239. // Each value is an array of strings & other ICU expressions
  29240. const valueArr = values[i];
  29241. const nestedIcus = [];
  29242. for (let j = 0; j < valueArr.length; j++) {
  29243. const value = valueArr[j];
  29244. if (typeof value !== 'string') {
  29245. // It is an nested ICU expression
  29246. const icuIndex = nestedIcus.push(value) - 1;
  29247. // Replace nested ICU expression by a comment node
  29248. valueArr[j] = `<!--�${icuIndex}�-->`;
  29249. }
  29250. }
  29251. const caseAst = [];
  29252. cases.push(caseAst);
  29253. bindingMask =
  29254. parseIcuCase(caseAst, tView, tIcu, lView, updateOpCodes, parentIdx, icuExpression.cases[i], valueArr.join(''), nestedIcus) | bindingMask;
  29255. }
  29256. if (bindingMask) {
  29257. addUpdateIcuUpdate(updateOpCodes, bindingMask, anchorIdx);
  29258. }
  29259. ast.push({
  29260. kind: 3 /* I18nNodeKind.ICU */,
  29261. index: anchorIdx,
  29262. cases,
  29263. currentCaseLViewIndex: tIcu.currentCaseLViewIndex,
  29264. });
  29265. }
  29266. /**
  29267. * Parses text containing an ICU expression and produces a JSON object for it.
  29268. * Original code from closure library, modified for Angular.
  29269. *
  29270. * @param pattern Text containing an ICU expression that needs to be parsed.
  29271. *
  29272. */
  29273. function parseICUBlock(pattern) {
  29274. const cases = [];
  29275. const values = [];
  29276. let icuType = 1 /* IcuType.plural */;
  29277. let mainBinding = 0;
  29278. pattern = pattern.replace(ICU_BLOCK_REGEXP, function (str, binding, type) {
  29279. if (type === 'select') {
  29280. icuType = 0 /* IcuType.select */;
  29281. }
  29282. else {
  29283. icuType = 1 /* IcuType.plural */;
  29284. }
  29285. mainBinding = parseInt(binding.slice(1), 10);
  29286. return '';
  29287. });
  29288. const parts = i18nParseTextIntoPartsAndICU(pattern);
  29289. // Looking for (key block)+ sequence. One of the keys has to be "other".
  29290. for (let pos = 0; pos < parts.length;) {
  29291. let key = parts[pos++].trim();
  29292. if (icuType === 1 /* IcuType.plural */) {
  29293. // Key can be "=x", we just want "x"
  29294. key = key.replace(/\s*(?:=)?(\w+)\s*/, '$1');
  29295. }
  29296. if (key.length) {
  29297. cases.push(key);
  29298. }
  29299. const blocks = i18nParseTextIntoPartsAndICU(parts[pos++]);
  29300. if (cases.length > values.length) {
  29301. values.push(blocks);
  29302. }
  29303. }
  29304. // TODO(ocombe): support ICU expressions in attributes, see #21615
  29305. return { type: icuType, mainBinding: mainBinding, cases, values };
  29306. }
  29307. /**
  29308. * Breaks pattern into strings and top level {...} blocks.
  29309. * Can be used to break a message into text and ICU expressions, or to break an ICU expression
  29310. * into keys and cases. Original code from closure library, modified for Angular.
  29311. *
  29312. * @param pattern (sub)Pattern to be broken.
  29313. * @returns An `Array<string|IcuExpression>` where:
  29314. * - odd positions: `string` => text between ICU expressions
  29315. * - even positions: `ICUExpression` => ICU expression parsed into `ICUExpression` record.
  29316. */
  29317. function i18nParseTextIntoPartsAndICU(pattern) {
  29318. if (!pattern) {
  29319. return [];
  29320. }
  29321. let prevPos = 0;
  29322. const braceStack = [];
  29323. const results = [];
  29324. const braces = /[{}]/g;
  29325. // lastIndex doesn't get set to 0 so we have to.
  29326. braces.lastIndex = 0;
  29327. let match;
  29328. while ((match = braces.exec(pattern))) {
  29329. const pos = match.index;
  29330. if (match[0] == '}') {
  29331. braceStack.pop();
  29332. if (braceStack.length == 0) {
  29333. // End of the block.
  29334. const block = pattern.substring(prevPos, pos);
  29335. if (ICU_BLOCK_REGEXP.test(block)) {
  29336. results.push(parseICUBlock(block));
  29337. }
  29338. else {
  29339. results.push(block);
  29340. }
  29341. prevPos = pos + 1;
  29342. }
  29343. }
  29344. else {
  29345. if (braceStack.length == 0) {
  29346. const substring = pattern.substring(prevPos, pos);
  29347. results.push(substring);
  29348. prevPos = pos + 1;
  29349. }
  29350. braceStack.push('{');
  29351. }
  29352. }
  29353. const substring = pattern.substring(prevPos);
  29354. results.push(substring);
  29355. return results;
  29356. }
  29357. /**
  29358. * Parses a node, its children and its siblings, and generates the mutate & update OpCodes.
  29359. *
  29360. */
  29361. function parseIcuCase(ast, tView, tIcu, lView, updateOpCodes, parentIdx, caseName, unsafeCaseHtml, nestedIcus) {
  29362. const create = [];
  29363. const remove = [];
  29364. const update = [];
  29365. if (ngDevMode) {
  29366. attachDebugGetter(create, icuCreateOpCodesToString);
  29367. attachDebugGetter(remove, i18nRemoveOpCodesToString);
  29368. attachDebugGetter(update, i18nUpdateOpCodesToString);
  29369. }
  29370. tIcu.cases.push(caseName);
  29371. tIcu.create.push(create);
  29372. tIcu.remove.push(remove);
  29373. tIcu.update.push(update);
  29374. const inertBodyHelper = getInertBodyHelper(getDocument());
  29375. const inertBodyElement = inertBodyHelper.getInertBodyElement(unsafeCaseHtml);
  29376. ngDevMode && assertDefined(inertBodyElement, 'Unable to generate inert body element');
  29377. const inertRootNode = getTemplateContent(inertBodyElement) || inertBodyElement;
  29378. if (inertRootNode) {
  29379. return walkIcuTree(ast, tView, tIcu, lView, updateOpCodes, create, remove, update, inertRootNode, parentIdx, nestedIcus, 0);
  29380. }
  29381. else {
  29382. return 0;
  29383. }
  29384. }
  29385. function walkIcuTree(ast, tView, tIcu, lView, sharedUpdateOpCodes, create, remove, update, parentNode, parentIdx, nestedIcus, depth) {
  29386. let bindingMask = 0;
  29387. let currentNode = parentNode.firstChild;
  29388. while (currentNode) {
  29389. const newIndex = allocExpando(tView, lView, 1, null);
  29390. switch (currentNode.nodeType) {
  29391. case Node.ELEMENT_NODE:
  29392. const element = currentNode;
  29393. const tagName = element.tagName.toLowerCase();
  29394. if (VALID_ELEMENTS.hasOwnProperty(tagName)) {
  29395. addCreateNodeAndAppend(create, ELEMENT_MARKER, tagName, parentIdx, newIndex);
  29396. tView.data[newIndex] = tagName;
  29397. const elAttrs = element.attributes;
  29398. for (let i = 0; i < elAttrs.length; i++) {
  29399. const attr = elAttrs.item(i);
  29400. const lowerAttrName = attr.name.toLowerCase();
  29401. const hasBinding = !!attr.value.match(BINDING_REGEXP);
  29402. // we assume the input string is safe, unless it's using a binding
  29403. if (hasBinding) {
  29404. if (VALID_ATTRS.hasOwnProperty(lowerAttrName)) {
  29405. if (URI_ATTRS[lowerAttrName]) {
  29406. generateBindingUpdateOpCodes(update, attr.value, newIndex, attr.name, 0, _sanitizeUrl);
  29407. }
  29408. else {
  29409. generateBindingUpdateOpCodes(update, attr.value, newIndex, attr.name, 0, null);
  29410. }
  29411. }
  29412. else {
  29413. ngDevMode &&
  29414. console.warn(`WARNING: ignoring unsafe attribute value ` +
  29415. `${lowerAttrName} on element ${tagName} ` +
  29416. `(see ${XSS_SECURITY_URL})`);
  29417. }
  29418. }
  29419. else {
  29420. addCreateAttribute(create, newIndex, attr);
  29421. }
  29422. }
  29423. const elementNode = {
  29424. kind: 1 /* I18nNodeKind.ELEMENT */,
  29425. index: newIndex,
  29426. children: [],
  29427. };
  29428. ast.push(elementNode);
  29429. // Parse the children of this node (if any)
  29430. bindingMask =
  29431. walkIcuTree(elementNode.children, tView, tIcu, lView, sharedUpdateOpCodes, create, remove, update, currentNode, newIndex, nestedIcus, depth + 1) | bindingMask;
  29432. addRemoveNode(remove, newIndex, depth);
  29433. }
  29434. break;
  29435. case Node.TEXT_NODE:
  29436. const value = currentNode.textContent || '';
  29437. const hasBinding = value.match(BINDING_REGEXP);
  29438. addCreateNodeAndAppend(create, null, hasBinding ? '' : value, parentIdx, newIndex);
  29439. addRemoveNode(remove, newIndex, depth);
  29440. if (hasBinding) {
  29441. bindingMask =
  29442. generateBindingUpdateOpCodes(update, value, newIndex, null, 0, null) | bindingMask;
  29443. }
  29444. ast.push({
  29445. kind: 0 /* I18nNodeKind.TEXT */,
  29446. index: newIndex,
  29447. });
  29448. break;
  29449. case Node.COMMENT_NODE:
  29450. // Check if the comment node is a placeholder for a nested ICU
  29451. const isNestedIcu = NESTED_ICU.exec(currentNode.textContent || '');
  29452. if (isNestedIcu) {
  29453. const nestedIcuIndex = parseInt(isNestedIcu[1], 10);
  29454. const icuExpression = nestedIcus[nestedIcuIndex];
  29455. // Create the comment node that will anchor the ICU expression
  29456. addCreateNodeAndAppend(create, ICU_MARKER, ngDevMode ? `nested ICU ${nestedIcuIndex}` : '', parentIdx, newIndex);
  29457. icuStart(ast, tView, lView, sharedUpdateOpCodes, parentIdx, icuExpression, newIndex);
  29458. addRemoveNestedIcu(remove, newIndex, depth);
  29459. }
  29460. break;
  29461. }
  29462. currentNode = currentNode.nextSibling;
  29463. }
  29464. return bindingMask;
  29465. }
  29466. function addRemoveNode(remove, index, depth) {
  29467. if (depth === 0) {
  29468. remove.push(index);
  29469. }
  29470. }
  29471. function addRemoveNestedIcu(remove, index, depth) {
  29472. if (depth === 0) {
  29473. remove.push(~index); // remove ICU at `index`
  29474. remove.push(index); // remove ICU comment at `index`
  29475. }
  29476. }
  29477. function addUpdateIcuSwitch(update, icuExpression, index) {
  29478. update.push(toMaskBit(icuExpression.mainBinding), 2, -1 - icuExpression.mainBinding, (index << 2 /* I18nUpdateOpCode.SHIFT_REF */) | 2 /* I18nUpdateOpCode.IcuSwitch */);
  29479. }
  29480. function addUpdateIcuUpdate(update, bindingMask, index) {
  29481. update.push(bindingMask, 1, (index << 2 /* I18nUpdateOpCode.SHIFT_REF */) | 3 /* I18nUpdateOpCode.IcuUpdate */);
  29482. }
  29483. function addCreateNodeAndAppend(create, marker, text, appendToParentIdx, createAtIdx) {
  29484. if (marker !== null) {
  29485. create.push(marker);
  29486. }
  29487. create.push(text, createAtIdx, icuCreateOpCode(0 /* IcuCreateOpCode.AppendChild */, appendToParentIdx, createAtIdx));
  29488. }
  29489. function addCreateAttribute(create, newIndex, attr) {
  29490. create.push((newIndex << 1 /* IcuCreateOpCode.SHIFT_REF */) | 1 /* IcuCreateOpCode.Attr */, attr.name, attr.value);
  29491. }
  29492. // i18nPostprocess consts
  29493. const ROOT_TEMPLATE_ID = 0;
  29494. const PP_MULTI_VALUE_PLACEHOLDERS_REGEXP = /\[(�.+?�?)\]/;
  29495. const PP_PLACEHOLDERS_REGEXP = /\[(�.+?�?)\]|(�\/?\*\d+:\d+�)/g;
  29496. const PP_ICU_VARS_REGEXP = /({\s*)(VAR_(PLURAL|SELECT)(_\d+)?)(\s*,)/g;
  29497. const PP_ICU_PLACEHOLDERS_REGEXP = /{([A-Z0-9_]+)}/g;
  29498. const PP_ICUS_REGEXP = /�I18N_EXP_(ICU(_\d+)?)�/g;
  29499. const PP_CLOSE_TEMPLATE_REGEXP = /\/\*/;
  29500. const PP_TEMPLATE_ID_REGEXP = /\d+\:(\d+)/;
  29501. /**
  29502. * Handles message string post-processing for internationalization.
  29503. *
  29504. * Handles message string post-processing by transforming it from intermediate
  29505. * format (that might contain some markers that we need to replace) to the final
  29506. * form, consumable by i18nStart instruction. Post processing steps include:
  29507. *
  29508. * 1. Resolve all multi-value cases (like [�*1:1��#2:1�|�#4:1�|�5�])
  29509. * 2. Replace all ICU vars (like "VAR_PLURAL")
  29510. * 3. Replace all placeholders used inside ICUs in a form of {PLACEHOLDER}
  29511. * 4. Replace all ICU references with corresponding values (like �ICU_EXP_ICU_1�)
  29512. * in case multiple ICUs have the same placeholder name
  29513. *
  29514. * @param message Raw translation string for post processing
  29515. * @param replacements Set of replacements that should be applied
  29516. *
  29517. * @returns Transformed string that can be consumed by i18nStart instruction
  29518. *
  29519. * @codeGenApi
  29520. */
  29521. function i18nPostprocess(message, replacements = {}) {
  29522. /**
  29523. * Step 1: resolve all multi-value placeholders like [�#5�|�*1:1��#2:1�|�#4:1�]
  29524. *
  29525. * Note: due to the way we process nested templates (BFS), multi-value placeholders are typically
  29526. * grouped by templates, for example: [�#5�|�#6�|�#1:1�|�#3:2�] where �#5� and �#6� belong to root
  29527. * template, �#1:1� belong to nested template with index 1 and �#1:2� - nested template with index
  29528. * 3. However in real templates the order might be different: i.e. �#1:1� and/or �#3:2� may go in
  29529. * front of �#6�. The post processing step restores the right order by keeping track of the
  29530. * template id stack and looks for placeholders that belong to the currently active template.
  29531. */
  29532. let result = message;
  29533. if (PP_MULTI_VALUE_PLACEHOLDERS_REGEXP.test(message)) {
  29534. const matches = {};
  29535. const templateIdsStack = [ROOT_TEMPLATE_ID];
  29536. result = result.replace(PP_PLACEHOLDERS_REGEXP, (m, phs, tmpl) => {
  29537. const content = phs || tmpl;
  29538. const placeholders = matches[content] || [];
  29539. if (!placeholders.length) {
  29540. content.split('|').forEach((placeholder) => {
  29541. const match = placeholder.match(PP_TEMPLATE_ID_REGEXP);
  29542. const templateId = match ? parseInt(match[1], 10) : ROOT_TEMPLATE_ID;
  29543. const isCloseTemplateTag = PP_CLOSE_TEMPLATE_REGEXP.test(placeholder);
  29544. placeholders.push([templateId, isCloseTemplateTag, placeholder]);
  29545. });
  29546. matches[content] = placeholders;
  29547. }
  29548. if (!placeholders.length) {
  29549. throw new Error(`i18n postprocess: unmatched placeholder - ${content}`);
  29550. }
  29551. const currentTemplateId = templateIdsStack[templateIdsStack.length - 1];
  29552. let idx = 0;
  29553. // find placeholder index that matches current template id
  29554. for (let i = 0; i < placeholders.length; i++) {
  29555. if (placeholders[i][0] === currentTemplateId) {
  29556. idx = i;
  29557. break;
  29558. }
  29559. }
  29560. // update template id stack based on the current tag extracted
  29561. const [templateId, isCloseTemplateTag, placeholder] = placeholders[idx];
  29562. if (isCloseTemplateTag) {
  29563. templateIdsStack.pop();
  29564. }
  29565. else if (currentTemplateId !== templateId) {
  29566. templateIdsStack.push(templateId);
  29567. }
  29568. // remove processed tag from the list
  29569. placeholders.splice(idx, 1);
  29570. return placeholder;
  29571. });
  29572. }
  29573. // return current result if no replacements specified
  29574. if (!Object.keys(replacements).length) {
  29575. return result;
  29576. }
  29577. /**
  29578. * Step 2: replace all ICU vars (like "VAR_PLURAL")
  29579. */
  29580. result = result.replace(PP_ICU_VARS_REGEXP, (match, start, key, _type, _idx, end) => {
  29581. return replacements.hasOwnProperty(key) ? `${start}${replacements[key]}${end}` : match;
  29582. });
  29583. /**
  29584. * Step 3: replace all placeholders used inside ICUs in a form of {PLACEHOLDER}
  29585. */
  29586. result = result.replace(PP_ICU_PLACEHOLDERS_REGEXP, (match, key) => {
  29587. return replacements.hasOwnProperty(key) ? replacements[key] : match;
  29588. });
  29589. /**
  29590. * Step 4: replace all ICU references with corresponding values (like �ICU_EXP_ICU_1�) in case
  29591. * multiple ICUs have the same placeholder name
  29592. */
  29593. result = result.replace(PP_ICUS_REGEXP, (match, key) => {
  29594. if (replacements.hasOwnProperty(key)) {
  29595. const list = replacements[key];
  29596. if (!list.length) {
  29597. throw new Error(`i18n postprocess: unmatched ICU - ${match} with key: ${key}`);
  29598. }
  29599. return list.shift();
  29600. }
  29601. return match;
  29602. });
  29603. return result;
  29604. }
  29605. /**
  29606. * Marks a block of text as translatable.
  29607. *
  29608. * The instructions `i18nStart` and `i18nEnd` mark the translation block in the template.
  29609. * The translation `message` is the value which is locale specific. The translation string may
  29610. * contain placeholders which associate inner elements and sub-templates within the translation.
  29611. *
  29612. * The translation `message` placeholders are:
  29613. * - `�{index}(:{block})�`: *Binding Placeholder*: Marks a location where an expression will be
  29614. * interpolated into. The placeholder `index` points to the expression binding index. An optional
  29615. * `block` that matches the sub-template in which it was declared.
  29616. * - `�#{index}(:{block})�`/`�/#{index}(:{block})�`: *Element Placeholder*: Marks the beginning
  29617. * and end of DOM element that were embedded in the original translation block. The placeholder
  29618. * `index` points to the element index in the template instructions set. An optional `block` that
  29619. * matches the sub-template in which it was declared.
  29620. * - `�*{index}:{block}�`/`�/*{index}:{block}�`: *Sub-template Placeholder*: Sub-templates must be
  29621. * split up and translated separately in each angular template function. The `index` points to the
  29622. * `template` instruction index. A `block` that matches the sub-template in which it was declared.
  29623. *
  29624. * @param index A unique index of the translation in the static block.
  29625. * @param messageIndex An index of the translation message from the `def.consts` array.
  29626. * @param subTemplateIndex Optional sub-template index in the `message`.
  29627. *
  29628. * @codeGenApi
  29629. */
  29630. function ɵɵi18nStart(index, messageIndex, subTemplateIndex = -1) {
  29631. const tView = getTView();
  29632. const lView = getLView();
  29633. const adjustedIndex = HEADER_OFFSET + index;
  29634. ngDevMode && assertDefined(tView, `tView should be defined`);
  29635. const message = getConstant(tView.consts, messageIndex);
  29636. const parentTNode = getCurrentParentTNode();
  29637. if (tView.firstCreatePass) {
  29638. i18nStartFirstCreatePass(tView, parentTNode === null ? 0 : parentTNode.index, lView, adjustedIndex, message, subTemplateIndex);
  29639. }
  29640. // Set a flag that this LView has i18n blocks.
  29641. // The flag is later used to determine whether this component should
  29642. // be hydrated (currently hydration is not supported for i18n blocks).
  29643. if (tView.type === 2 /* TViewType.Embedded */) {
  29644. // Annotate host component's LView (not embedded view's LView),
  29645. // since hydration can be skipped on per-component basis only.
  29646. const componentLView = lView[DECLARATION_COMPONENT_VIEW];
  29647. componentLView[FLAGS] |= 32 /* LViewFlags.HasI18n */;
  29648. }
  29649. else {
  29650. lView[FLAGS] |= 32 /* LViewFlags.HasI18n */;
  29651. }
  29652. const tI18n = tView.data[adjustedIndex];
  29653. const sameViewParentTNode = parentTNode === lView[T_HOST] ? null : parentTNode;
  29654. const parentRNode = getClosestRElement(tView, sameViewParentTNode, lView);
  29655. // If `parentTNode` is an `ElementContainer` than it has `<!--ng-container--->`.
  29656. // When we do inserts we have to make sure to insert in front of `<!--ng-container--->`.
  29657. const insertInFrontOf = parentTNode && parentTNode.type & 8 /* TNodeType.ElementContainer */ ? lView[parentTNode.index] : null;
  29658. prepareI18nBlockForHydration(lView, adjustedIndex, parentTNode, subTemplateIndex);
  29659. applyCreateOpCodes(lView, tI18n.create, parentRNode, insertInFrontOf);
  29660. setInI18nBlock(true);
  29661. }
  29662. /**
  29663. * Translates a translation block marked by `i18nStart` and `i18nEnd`. It inserts the text/ICU nodes
  29664. * into the render tree, moves the placeholder nodes and removes the deleted nodes.
  29665. *
  29666. * @codeGenApi
  29667. */
  29668. function ɵɵi18nEnd() {
  29669. setInI18nBlock(false);
  29670. }
  29671. /**
  29672. *
  29673. * Use this instruction to create a translation block that doesn't contain any placeholder.
  29674. * It calls both {@link i18nStart} and {@link i18nEnd} in one instruction.
  29675. *
  29676. * The translation `message` is the value which is locale specific. The translation string may
  29677. * contain placeholders which associate inner elements and sub-templates within the translation.
  29678. *
  29679. * The translation `message` placeholders are:
  29680. * - `�{index}(:{block})�`: *Binding Placeholder*: Marks a location where an expression will be
  29681. * interpolated into. The placeholder `index` points to the expression binding index. An optional
  29682. * `block` that matches the sub-template in which it was declared.
  29683. * - `�#{index}(:{block})�`/`�/#{index}(:{block})�`: *Element Placeholder*: Marks the beginning
  29684. * and end of DOM element that were embedded in the original translation block. The placeholder
  29685. * `index` points to the element index in the template instructions set. An optional `block` that
  29686. * matches the sub-template in which it was declared.
  29687. * - `�*{index}:{block}�`/`�/*{index}:{block}�`: *Sub-template Placeholder*: Sub-templates must be
  29688. * split up and translated separately in each angular template function. The `index` points to the
  29689. * `template` instruction index. A `block` that matches the sub-template in which it was declared.
  29690. *
  29691. * @param index A unique index of the translation in the static block.
  29692. * @param messageIndex An index of the translation message from the `def.consts` array.
  29693. * @param subTemplateIndex Optional sub-template index in the `message`.
  29694. *
  29695. * @codeGenApi
  29696. */
  29697. function ɵɵi18n(index, messageIndex, subTemplateIndex) {
  29698. ɵɵi18nStart(index, messageIndex, subTemplateIndex);
  29699. ɵɵi18nEnd();
  29700. }
  29701. /**
  29702. * Marks a list of attributes as translatable.
  29703. *
  29704. * @param index A unique index in the static block
  29705. * @param values
  29706. *
  29707. * @codeGenApi
  29708. */
  29709. function ɵɵi18nAttributes(index, attrsIndex) {
  29710. const tView = getTView();
  29711. ngDevMode && assertDefined(tView, `tView should be defined`);
  29712. const attrs = getConstant(tView.consts, attrsIndex);
  29713. i18nAttributesFirstPass(tView, index + HEADER_OFFSET, attrs);
  29714. }
  29715. /**
  29716. * Stores the values of the bindings during each update cycle in order to determine if we need to
  29717. * update the translated nodes.
  29718. *
  29719. * @param value The binding's value
  29720. * @returns This function returns itself so that it may be chained
  29721. * (e.g. `i18nExp(ctx.name)(ctx.title)`)
  29722. *
  29723. * @codeGenApi
  29724. */
  29725. function ɵɵi18nExp(value) {
  29726. const lView = getLView();
  29727. setMaskBit(bindingUpdated(lView, nextBindingIndex(), value));
  29728. return ɵɵi18nExp;
  29729. }
  29730. /**
  29731. * Updates a translation block or an i18n attribute when the bindings have changed.
  29732. *
  29733. * @param index Index of either {@link i18nStart} (translation block) or {@link i18nAttributes}
  29734. * (i18n attribute) on which it should update the content.
  29735. *
  29736. * @codeGenApi
  29737. */
  29738. function ɵɵi18nApply(index) {
  29739. applyI18n(getTView(), getLView(), index + HEADER_OFFSET);
  29740. }
  29741. /**
  29742. * Handles message string post-processing for internationalization.
  29743. *
  29744. * Handles message string post-processing by transforming it from intermediate
  29745. * format (that might contain some markers that we need to replace) to the final
  29746. * form, consumable by i18nStart instruction. Post processing steps include:
  29747. *
  29748. * 1. Resolve all multi-value cases (like [�*1:1��#2:1�|�#4:1�|�5�])
  29749. * 2. Replace all ICU vars (like "VAR_PLURAL")
  29750. * 3. Replace all placeholders used inside ICUs in a form of {PLACEHOLDER}
  29751. * 4. Replace all ICU references with corresponding values (like �ICU_EXP_ICU_1�)
  29752. * in case multiple ICUs have the same placeholder name
  29753. *
  29754. * @param message Raw translation string for post processing
  29755. * @param replacements Set of replacements that should be applied
  29756. *
  29757. * @returns Transformed string that can be consumed by i18nStart instruction
  29758. *
  29759. * @codeGenApi
  29760. */
  29761. function ɵɵi18nPostprocess(message, replacements = {}) {
  29762. return i18nPostprocess(message, replacements);
  29763. }
  29764. /**
  29765. * Wraps an event listener with a function that marks ancestors dirty and prevents default behavior,
  29766. * if applicable.
  29767. *
  29768. * @param tNode The TNode associated with this listener
  29769. * @param lView The LView that contains this listener
  29770. * @param listenerFn The listener function to call
  29771. * @param wrapWithPreventDefault Whether or not to prevent default behavior
  29772. * (the procedural renderer does this already, so in those cases, we should skip)
  29773. */
  29774. function wrapListener(tNode, lView, context, listenerFn) {
  29775. // Note: we are performing most of the work in the listener function itself
  29776. // to optimize listener registration.
  29777. return function wrapListenerIn_markDirtyAndPreventDefault(e) {
  29778. // Ivy uses `Function` as a special token that allows us to unwrap the function
  29779. // so that it can be invoked programmatically by `DebugNode.triggerEventHandler`.
  29780. if (e === Function) {
  29781. return listenerFn;
  29782. }
  29783. // In order to be backwards compatible with View Engine, events on component host nodes
  29784. // must also mark the component view itself dirty (i.e. the view that it owns).
  29785. const startView = isComponentHost(tNode) ? getComponentLViewByIndex(tNode.index, lView) : lView;
  29786. markViewDirty(startView, 5 /* NotificationSource.Listener */);
  29787. let result = executeListenerWithErrorHandling(lView, context, listenerFn, e);
  29788. // A just-invoked listener function might have coalesced listeners so we need to check for
  29789. // their presence and invoke as needed.
  29790. let nextListenerFn = wrapListenerIn_markDirtyAndPreventDefault.__ngNextListenerFn__;
  29791. while (nextListenerFn) {
  29792. // We should prevent default if any of the listeners explicitly return false
  29793. result = executeListenerWithErrorHandling(lView, context, nextListenerFn, e) && result;
  29794. nextListenerFn = nextListenerFn.__ngNextListenerFn__;
  29795. }
  29796. return result;
  29797. };
  29798. }
  29799. function executeListenerWithErrorHandling(lView, context, listenerFn, e) {
  29800. const prevConsumer = setActiveConsumer(null);
  29801. try {
  29802. profiler(6 /* ProfilerEvent.OutputStart */, context, listenerFn);
  29803. // Only explicitly returning false from a listener should preventDefault
  29804. return listenerFn(e) !== false;
  29805. }
  29806. catch (error) {
  29807. // TODO(atscott): This should report to the application error handler, not the ErrorHandler on LView injector
  29808. handleError(lView, error);
  29809. return false;
  29810. }
  29811. finally {
  29812. profiler(7 /* ProfilerEvent.OutputEnd */, context, listenerFn);
  29813. setActiveConsumer(prevConsumer);
  29814. }
  29815. }
  29816. /** Handles an error thrown in an LView. */
  29817. function handleError(lView, error) {
  29818. const injector = lView[INJECTOR];
  29819. const errorHandler = injector ? injector.get(ErrorHandler, null) : null;
  29820. errorHandler && errorHandler.handleError(error);
  29821. }
  29822. function listenToOutput(tNode, tView, lView, index, lookupName, eventName, listenerFn, lCleanup, tCleanup) {
  29823. ngDevMode && assertIndexInRange(lView, index);
  29824. const instance = lView[index];
  29825. const def = tView.data[index];
  29826. const propertyName = def.outputs[lookupName];
  29827. const output = instance[propertyName];
  29828. if (ngDevMode && !isOutputSubscribable(output)) {
  29829. throw new Error(`@Output ${propertyName} not initialized in '${instance.constructor.name}'.`);
  29830. }
  29831. const subscription = output.subscribe(listenerFn);
  29832. const idx = lCleanup.length;
  29833. lCleanup.push(listenerFn, subscription);
  29834. tCleanup && tCleanup.push(eventName, tNode.index, idx, -(idx + 1));
  29835. }
  29836. /**
  29837. * Whether the given value represents a subscribable output.
  29838. *
  29839. * For example, an `EventEmitter, a `Subject`, an `Observable` or an
  29840. * `OutputEmitter`.
  29841. */
  29842. function isOutputSubscribable(value) {
  29843. return (value != null && typeof value.subscribe === 'function');
  29844. }
  29845. /**
  29846. * Contains a reference to a function that disables event replay feature
  29847. * for server-side rendered applications. This function is overridden with
  29848. * an actual implementation when the event replay feature is enabled via
  29849. * `withEventReplay()` call.
  29850. */
  29851. let stashEventListener = (el, eventName, listenerFn) => { };
  29852. function setStashFn(fn) {
  29853. stashEventListener = fn;
  29854. }
  29855. /**
  29856. * Adds an event listener to the current node.
  29857. *
  29858. * If an output exists on one of the node's directives, it also subscribes to the output
  29859. * and saves the subscription for later cleanup.
  29860. *
  29861. * @param eventName Name of the event
  29862. * @param listenerFn The function to be called when event emits
  29863. * @param useCapture Whether or not to use capture in event listener - this argument is a reminder
  29864. * from the Renderer3 infrastructure and should be removed from the instruction arguments
  29865. * @param eventTargetResolver Function that returns global target information in case this listener
  29866. * should be attached to a global object like window, document or body
  29867. *
  29868. * @codeGenApi
  29869. */
  29870. function ɵɵlistener(eventName, listenerFn, useCapture, eventTargetResolver) {
  29871. const lView = getLView();
  29872. const tView = getTView();
  29873. const tNode = getCurrentTNode();
  29874. listenerInternal(tView, lView, lView[RENDERER], tNode, eventName, listenerFn, eventTargetResolver);
  29875. return ɵɵlistener;
  29876. }
  29877. /**
  29878. * Registers a synthetic host listener (e.g. `(@foo.start)`) on a component or directive.
  29879. *
  29880. * This instruction is for compatibility purposes and is designed to ensure that a
  29881. * synthetic host listener (e.g. `@HostListener('@foo.start')`) properly gets rendered
  29882. * in the component's renderer. Normally all host listeners are evaluated with the
  29883. * parent component's renderer, but, in the case of animation @triggers, they need
  29884. * to be evaluated with the sub component's renderer (because that's where the
  29885. * animation triggers are defined).
  29886. *
  29887. * Do not use this instruction as a replacement for `listener`. This instruction
  29888. * only exists to ensure compatibility with the ViewEngine's host binding behavior.
  29889. *
  29890. * @param eventName Name of the event
  29891. * @param listenerFn The function to be called when event emits
  29892. * @param useCapture Whether or not to use capture in event listener
  29893. * @param eventTargetResolver Function that returns global target information in case this listener
  29894. * should be attached to a global object like window, document or body
  29895. *
  29896. * @codeGenApi
  29897. */
  29898. function ɵɵsyntheticHostListener(eventName, listenerFn) {
  29899. const tNode = getCurrentTNode();
  29900. const lView = getLView();
  29901. const tView = getTView();
  29902. const currentDef = getCurrentDirectiveDef(tView.data);
  29903. const renderer = loadComponentRenderer(currentDef, tNode, lView);
  29904. listenerInternal(tView, lView, renderer, tNode, eventName, listenerFn);
  29905. return ɵɵsyntheticHostListener;
  29906. }
  29907. /**
  29908. * A utility function that checks if a given element has already an event handler registered for an
  29909. * event with a specified name. The TView.cleanup data structure is used to find out which events
  29910. * are registered for a given element.
  29911. */
  29912. function findExistingListener(tView, lView, eventName, tNodeIdx) {
  29913. const tCleanup = tView.cleanup;
  29914. if (tCleanup != null) {
  29915. for (let i = 0; i < tCleanup.length - 1; i += 2) {
  29916. const cleanupEventName = tCleanup[i];
  29917. if (cleanupEventName === eventName && tCleanup[i + 1] === tNodeIdx) {
  29918. // We have found a matching event name on the same node but it might not have been
  29919. // registered yet, so we must explicitly verify entries in the LView cleanup data
  29920. // structures.
  29921. const lCleanup = lView[CLEANUP];
  29922. const listenerIdxInLCleanup = tCleanup[i + 2];
  29923. return lCleanup.length > listenerIdxInLCleanup ? lCleanup[listenerIdxInLCleanup] : null;
  29924. }
  29925. // TView.cleanup can have a mix of 4-elements entries (for event handler cleanups) or
  29926. // 2-element entries (for directive and queries destroy hooks). As such we can encounter
  29927. // blocks of 4 or 2 items in the tView.cleanup and this is why we iterate over 2 elements
  29928. // first and jump another 2 elements if we detect listeners cleanup (4 elements). Also check
  29929. // documentation of TView.cleanup for more details of this data structure layout.
  29930. if (typeof cleanupEventName === 'string') {
  29931. i += 2;
  29932. }
  29933. }
  29934. }
  29935. return null;
  29936. }
  29937. function listenerInternal(tView, lView, renderer, tNode, eventName, listenerFn, eventTargetResolver) {
  29938. const isTNodeDirectiveHost = isDirectiveHost(tNode);
  29939. const firstCreatePass = tView.firstCreatePass;
  29940. const tCleanup = firstCreatePass ? getOrCreateTViewCleanup(tView) : null;
  29941. const context = lView[CONTEXT];
  29942. // When the ɵɵlistener instruction was generated and is executed we know that there is either a
  29943. // native listener or a directive output on this element. As such we we know that we will have to
  29944. // register a listener and store its cleanup function on LView.
  29945. const lCleanup = getOrCreateLViewCleanup(lView);
  29946. ngDevMode && assertTNodeType(tNode, 3 /* TNodeType.AnyRNode */ | 12 /* TNodeType.AnyContainer */);
  29947. let processOutputs = true;
  29948. // Adding a native event listener is applicable when:
  29949. // - The corresponding TNode represents a DOM element.
  29950. // - The event target has a resolver (usually resulting in a global object,
  29951. // such as `window` or `document`).
  29952. if (tNode.type & 3 /* TNodeType.AnyRNode */ || eventTargetResolver) {
  29953. const native = getNativeByTNode(tNode, lView);
  29954. const target = eventTargetResolver ? eventTargetResolver(native) : native;
  29955. const lCleanupIndex = lCleanup.length;
  29956. const idxOrTargetGetter = eventTargetResolver
  29957. ? (_lView) => eventTargetResolver(unwrapRNode(_lView[tNode.index]))
  29958. : tNode.index;
  29959. // In order to match current behavior, native DOM event listeners must be added for all
  29960. // events (including outputs).
  29961. // There might be cases where multiple directives on the same element try to register an event
  29962. // handler function for the same event. In this situation we want to avoid registration of
  29963. // several native listeners as each registration would be intercepted by NgZone and
  29964. // trigger change detection. This would mean that a single user action would result in several
  29965. // change detections being invoked. To avoid this situation we want to have only one call to
  29966. // native handler registration (for the same element and same type of event).
  29967. //
  29968. // In order to have just one native event handler in presence of multiple handler functions,
  29969. // we just register a first handler function as a native event listener and then chain
  29970. // (coalesce) other handler functions on top of the first native handler function.
  29971. let existingListener = null;
  29972. // Please note that the coalescing described here doesn't happen for events specifying an
  29973. // alternative target (ex. (document:click)) - this is to keep backward compatibility with the
  29974. // view engine.
  29975. // Also, we don't have to search for existing listeners is there are no directives
  29976. // matching on a given node as we can't register multiple event handlers for the same event in
  29977. // a template (this would mean having duplicate attributes).
  29978. if (!eventTargetResolver && isTNodeDirectiveHost) {
  29979. existingListener = findExistingListener(tView, lView, eventName, tNode.index);
  29980. }
  29981. if (existingListener !== null) {
  29982. // Attach a new listener to coalesced listeners list, maintaining the order in which
  29983. // listeners are registered. For performance reasons, we keep a reference to the last
  29984. // listener in that list (in `__ngLastListenerFn__` field), so we can avoid going through
  29985. // the entire set each time we need to add a new listener.
  29986. const lastListenerFn = existingListener.__ngLastListenerFn__ || existingListener;
  29987. lastListenerFn.__ngNextListenerFn__ = listenerFn;
  29988. existingListener.__ngLastListenerFn__ = listenerFn;
  29989. processOutputs = false;
  29990. }
  29991. else {
  29992. listenerFn = wrapListener(tNode, lView, context, listenerFn);
  29993. stashEventListener(target, eventName, listenerFn);
  29994. const cleanupFn = renderer.listen(target, eventName, listenerFn);
  29995. ngDevMode && ngDevMode.rendererAddEventListener++;
  29996. lCleanup.push(listenerFn, cleanupFn);
  29997. tCleanup && tCleanup.push(eventName, idxOrTargetGetter, lCleanupIndex, lCleanupIndex + 1);
  29998. }
  29999. }
  30000. else {
  30001. // Even if there is no native listener to add, we still need to wrap the listener so that OnPush
  30002. // ancestors are marked dirty when an event occurs.
  30003. listenerFn = wrapListener(tNode, lView, context, listenerFn);
  30004. }
  30005. if (processOutputs) {
  30006. const outputConfig = tNode.outputs?.[eventName];
  30007. const hostDirectiveOutputConfig = tNode.hostDirectiveOutputs?.[eventName];
  30008. if (hostDirectiveOutputConfig && hostDirectiveOutputConfig.length) {
  30009. for (let i = 0; i < hostDirectiveOutputConfig.length; i += 2) {
  30010. const index = hostDirectiveOutputConfig[i];
  30011. const lookupName = hostDirectiveOutputConfig[i + 1];
  30012. listenToOutput(tNode, tView, lView, index, lookupName, eventName, listenerFn, lCleanup, tCleanup);
  30013. }
  30014. }
  30015. if (outputConfig && outputConfig.length) {
  30016. for (const index of outputConfig) {
  30017. listenToOutput(tNode, tView, lView, index, eventName, eventName, listenerFn, lCleanup, tCleanup);
  30018. }
  30019. }
  30020. }
  30021. }
  30022. /**
  30023. * Retrieves a context at the level specified and saves it as the global, contextViewData.
  30024. * Will get the next level up if level is not specified.
  30025. *
  30026. * This is used to save contexts of parent views so they can be bound in embedded views, or
  30027. * in conjunction with reference() to bind a ref from a parent view.
  30028. *
  30029. * @param level The relative level of the view from which to grab context compared to contextVewData
  30030. * @returns context
  30031. *
  30032. * @codeGenApi
  30033. */
  30034. function ɵɵnextContext(level = 1) {
  30035. return nextContextImpl(level);
  30036. }
  30037. /**
  30038. * Checks a given node against matching projection slots and returns the
  30039. * determined slot index. Returns "null" if no slot matched the given node.
  30040. *
  30041. * This function takes into account the parsed ngProjectAs selector from the
  30042. * node's attributes. If present, it will check whether the ngProjectAs selector
  30043. * matches any of the projection slot selectors.
  30044. */
  30045. function matchingProjectionSlotIndex(tNode, projectionSlots) {
  30046. let wildcardNgContentIndex = null;
  30047. const ngProjectAsAttrVal = getProjectAsAttrValue(tNode);
  30048. for (let i = 0; i < projectionSlots.length; i++) {
  30049. const slotValue = projectionSlots[i];
  30050. // The last wildcard projection slot should match all nodes which aren't matching
  30051. // any selector. This is necessary to be backwards compatible with view engine.
  30052. if (slotValue === '*') {
  30053. wildcardNgContentIndex = i;
  30054. continue;
  30055. }
  30056. // If we ran into an `ngProjectAs` attribute, we should match its parsed selector
  30057. // to the list of selectors, otherwise we fall back to matching against the node.
  30058. if (ngProjectAsAttrVal === null
  30059. ? isNodeMatchingSelectorList(tNode, slotValue, /* isProjectionMode */ true)
  30060. : isSelectorInSelectorList(ngProjectAsAttrVal, slotValue)) {
  30061. return i; // first matching selector "captures" a given node
  30062. }
  30063. }
  30064. return wildcardNgContentIndex;
  30065. }
  30066. /**
  30067. * Instruction to distribute projectable nodes among <ng-content> occurrences in a given template.
  30068. * It takes all the selectors from the entire component's template and decides where
  30069. * each projected node belongs (it re-distributes nodes among "buckets" where each "bucket" is
  30070. * backed by a selector).
  30071. *
  30072. * This function requires CSS selectors to be provided in 2 forms: parsed (by a compiler) and text,
  30073. * un-parsed form.
  30074. *
  30075. * The parsed form is needed for efficient matching of a node against a given CSS selector.
  30076. * The un-parsed, textual form is needed for support of the ngProjectAs attribute.
  30077. *
  30078. * Having a CSS selector in 2 different formats is not ideal, but alternatives have even more
  30079. * drawbacks:
  30080. * - having only a textual form would require runtime parsing of CSS selectors;
  30081. * - we can't have only a parsed as we can't re-construct textual form from it (as entered by a
  30082. * template author).
  30083. *
  30084. * @param projectionSlots? A collection of projection slots. A projection slot can be based
  30085. * on a parsed CSS selectors or set to the wildcard selector ("*") in order to match
  30086. * all nodes which do not match any selector. If not specified, a single wildcard
  30087. * selector projection slot will be defined.
  30088. *
  30089. * @codeGenApi
  30090. */
  30091. function ɵɵprojectionDef(projectionSlots) {
  30092. const componentNode = getLView()[DECLARATION_COMPONENT_VIEW][T_HOST];
  30093. if (!componentNode.projection) {
  30094. // If no explicit projection slots are defined, fall back to a single
  30095. // projection slot with the wildcard selector.
  30096. const numProjectionSlots = projectionSlots ? projectionSlots.length : 1;
  30097. const projectionHeads = (componentNode.projection = newArray(numProjectionSlots, null));
  30098. const tails = projectionHeads.slice();
  30099. let componentChild = componentNode.child;
  30100. while (componentChild !== null) {
  30101. // Do not project let declarations so they don't occupy a slot.
  30102. if (componentChild.type !== 128 /* TNodeType.LetDeclaration */) {
  30103. const slotIndex = projectionSlots
  30104. ? matchingProjectionSlotIndex(componentChild, projectionSlots)
  30105. : 0;
  30106. if (slotIndex !== null) {
  30107. if (tails[slotIndex]) {
  30108. tails[slotIndex].projectionNext = componentChild;
  30109. }
  30110. else {
  30111. projectionHeads[slotIndex] = componentChild;
  30112. }
  30113. tails[slotIndex] = componentChild;
  30114. }
  30115. }
  30116. componentChild = componentChild.next;
  30117. }
  30118. }
  30119. }
  30120. /**
  30121. * Inserts previously re-distributed projected nodes. This instruction must be preceded by a call
  30122. * to the projectionDef instruction.
  30123. *
  30124. * @param nodeIndex Index of the projection node.
  30125. * @param selectorIndex Index of the slot selector.
  30126. * - 0 when the selector is `*` (or unspecified as this is the default value),
  30127. * - 1 based index of the selector from the {@link projectionDef}
  30128. * @param attrs Static attributes set on the `ng-content` node.
  30129. * @param fallbackTemplateFn Template function with fallback content.
  30130. * Will be rendered if the slot is empty at runtime.
  30131. * @param fallbackDecls Number of declarations in the fallback template.
  30132. * @param fallbackVars Number of variables in the fallback template.
  30133. *
  30134. * @codeGenApi
  30135. */
  30136. function ɵɵprojection(nodeIndex, selectorIndex = 0, attrs, fallbackTemplateFn, fallbackDecls, fallbackVars) {
  30137. const lView = getLView();
  30138. const tView = getTView();
  30139. const fallbackIndex = fallbackTemplateFn ? nodeIndex + 1 : null;
  30140. // Fallback content needs to be declared no matter whether the slot is empty since different
  30141. // instances of the component may or may not insert it. Also it needs to be declare *before*
  30142. // the projection node in order to work correctly with hydration.
  30143. if (fallbackIndex !== null) {
  30144. declareTemplate(lView, tView, fallbackIndex, fallbackTemplateFn, fallbackDecls, fallbackVars, null, attrs);
  30145. }
  30146. const tProjectionNode = getOrCreateTNode(tView, HEADER_OFFSET + nodeIndex, 16 /* TNodeType.Projection */, null, attrs || null);
  30147. // We can't use viewData[HOST_NODE] because projection nodes can be nested in embedded views.
  30148. if (tProjectionNode.projection === null) {
  30149. tProjectionNode.projection = selectorIndex;
  30150. }
  30151. // `<ng-content>` has no content. Even if there's fallback
  30152. // content, the fallback is shown next to it.
  30153. setCurrentTNodeAsNotParent();
  30154. const hydrationInfo = lView[HYDRATION];
  30155. const isNodeCreationMode = !hydrationInfo || isInSkipHydrationBlock$1();
  30156. const componentHostNode = lView[DECLARATION_COMPONENT_VIEW][T_HOST];
  30157. const isEmpty = componentHostNode.projection[tProjectionNode.projection] === null;
  30158. if (isEmpty && fallbackIndex !== null) {
  30159. insertFallbackContent(lView, tView, fallbackIndex);
  30160. }
  30161. else if (isNodeCreationMode && !isDetachedByI18n(tProjectionNode)) {
  30162. // re-distribution of projectable nodes is stored on a component's view level
  30163. applyProjection(tView, lView, tProjectionNode);
  30164. }
  30165. }
  30166. /** Inserts the fallback content of a projection slot. Assumes there's no projected content. */
  30167. function insertFallbackContent(lView, tView, fallbackIndex) {
  30168. const adjustedIndex = HEADER_OFFSET + fallbackIndex;
  30169. const fallbackTNode = tView.data[adjustedIndex];
  30170. const fallbackLContainer = lView[adjustedIndex];
  30171. ngDevMode && assertTNode(fallbackTNode);
  30172. ngDevMode && assertLContainer(fallbackLContainer);
  30173. const dehydratedView = findMatchingDehydratedView(fallbackLContainer, fallbackTNode.tView.ssrId);
  30174. const fallbackLView = createAndRenderEmbeddedLView(lView, fallbackTNode, undefined, {
  30175. dehydratedView,
  30176. });
  30177. addLViewToLContainer(fallbackLContainer, fallbackLView, 0, shouldAddViewToDom(fallbackTNode, dehydratedView));
  30178. }
  30179. /**
  30180. *
  30181. * Update an interpolated property on an element with a lone bound value
  30182. *
  30183. * Used when the value passed to a property has 1 interpolated value in it, an no additional text
  30184. * surrounds that interpolated value:
  30185. *
  30186. * ```html
  30187. * <div title="{{v0}}"></div>
  30188. * ```
  30189. *
  30190. * Its compiled representation is::
  30191. *
  30192. * ```ts
  30193. * ɵɵpropertyInterpolate('title', v0);
  30194. * ```
  30195. *
  30196. * If the property name also exists as an input property on one of the element's directives,
  30197. * the component property will be set instead of the element property. This check must
  30198. * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
  30199. *
  30200. * @param propName The name of the property to update
  30201. * @param prefix Static value used for concatenation only.
  30202. * @param v0 Value checked for change.
  30203. * @param suffix Static value used for concatenation only.
  30204. * @param sanitizer An optional sanitizer function
  30205. * @returns itself, so that it may be chained.
  30206. * @codeGenApi
  30207. */
  30208. function ɵɵpropertyInterpolate(propName, v0, sanitizer) {
  30209. ɵɵpropertyInterpolate1(propName, '', v0, '', sanitizer);
  30210. return ɵɵpropertyInterpolate;
  30211. }
  30212. /**
  30213. *
  30214. * Update an interpolated property on an element with single bound value surrounded by text.
  30215. *
  30216. * Used when the value passed to a property has 1 interpolated value in it:
  30217. *
  30218. * ```html
  30219. * <div title="prefix{{v0}}suffix"></div>
  30220. * ```
  30221. *
  30222. * Its compiled representation is::
  30223. *
  30224. * ```ts
  30225. * ɵɵpropertyInterpolate1('title', 'prefix', v0, 'suffix');
  30226. * ```
  30227. *
  30228. * If the property name also exists as an input property on one of the element's directives,
  30229. * the component property will be set instead of the element property. This check must
  30230. * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
  30231. *
  30232. * @param propName The name of the property to update
  30233. * @param prefix Static value used for concatenation only.
  30234. * @param v0 Value checked for change.
  30235. * @param suffix Static value used for concatenation only.
  30236. * @param sanitizer An optional sanitizer function
  30237. * @returns itself, so that it may be chained.
  30238. * @codeGenApi
  30239. */
  30240. function ɵɵpropertyInterpolate1(propName, prefix, v0, suffix, sanitizer) {
  30241. const lView = getLView();
  30242. const interpolatedValue = interpolation1(lView, prefix, v0, suffix);
  30243. if (interpolatedValue !== NO_CHANGE) {
  30244. const tView = getTView();
  30245. const tNode = getSelectedTNode();
  30246. elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
  30247. ngDevMode &&
  30248. storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 1, prefix, suffix);
  30249. }
  30250. return ɵɵpropertyInterpolate1;
  30251. }
  30252. /**
  30253. *
  30254. * Update an interpolated property on an element with 2 bound values surrounded by text.
  30255. *
  30256. * Used when the value passed to a property has 2 interpolated values in it:
  30257. *
  30258. * ```html
  30259. * <div title="prefix{{v0}}-{{v1}}suffix"></div>
  30260. * ```
  30261. *
  30262. * Its compiled representation is::
  30263. *
  30264. * ```ts
  30265. * ɵɵpropertyInterpolate2('title', 'prefix', v0, '-', v1, 'suffix');
  30266. * ```
  30267. *
  30268. * If the property name also exists as an input property on one of the element's directives,
  30269. * the component property will be set instead of the element property. This check must
  30270. * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
  30271. *
  30272. * @param propName The name of the property to update
  30273. * @param prefix Static value used for concatenation only.
  30274. * @param v0 Value checked for change.
  30275. * @param i0 Static value used for concatenation only.
  30276. * @param v1 Value checked for change.
  30277. * @param suffix Static value used for concatenation only.
  30278. * @param sanitizer An optional sanitizer function
  30279. * @returns itself, so that it may be chained.
  30280. * @codeGenApi
  30281. */
  30282. function ɵɵpropertyInterpolate2(propName, prefix, v0, i0, v1, suffix, sanitizer) {
  30283. const lView = getLView();
  30284. const interpolatedValue = interpolation2(lView, prefix, v0, i0, v1, suffix);
  30285. if (interpolatedValue !== NO_CHANGE) {
  30286. const tView = getTView();
  30287. const tNode = getSelectedTNode();
  30288. elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
  30289. ngDevMode &&
  30290. storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 2, prefix, i0, suffix);
  30291. }
  30292. return ɵɵpropertyInterpolate2;
  30293. }
  30294. /**
  30295. *
  30296. * Update an interpolated property on an element with 3 bound values surrounded by text.
  30297. *
  30298. * Used when the value passed to a property has 3 interpolated values in it:
  30299. *
  30300. * ```html
  30301. * <div title="prefix{{v0}}-{{v1}}-{{v2}}suffix"></div>
  30302. * ```
  30303. *
  30304. * Its compiled representation is::
  30305. *
  30306. * ```ts
  30307. * ɵɵpropertyInterpolate3(
  30308. * 'title', 'prefix', v0, '-', v1, '-', v2, 'suffix');
  30309. * ```
  30310. *
  30311. * If the property name also exists as an input property on one of the element's directives,
  30312. * the component property will be set instead of the element property. This check must
  30313. * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
  30314. *
  30315. * @param propName The name of the property to update
  30316. * @param prefix Static value used for concatenation only.
  30317. * @param v0 Value checked for change.
  30318. * @param i0 Static value used for concatenation only.
  30319. * @param v1 Value checked for change.
  30320. * @param i1 Static value used for concatenation only.
  30321. * @param v2 Value checked for change.
  30322. * @param suffix Static value used for concatenation only.
  30323. * @param sanitizer An optional sanitizer function
  30324. * @returns itself, so that it may be chained.
  30325. * @codeGenApi
  30326. */
  30327. function ɵɵpropertyInterpolate3(propName, prefix, v0, i0, v1, i1, v2, suffix, sanitizer) {
  30328. const lView = getLView();
  30329. const interpolatedValue = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix);
  30330. if (interpolatedValue !== NO_CHANGE) {
  30331. const tView = getTView();
  30332. const tNode = getSelectedTNode();
  30333. elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
  30334. ngDevMode &&
  30335. storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 3, prefix, i0, i1, suffix);
  30336. }
  30337. return ɵɵpropertyInterpolate3;
  30338. }
  30339. /**
  30340. *
  30341. * Update an interpolated property on an element with 4 bound values surrounded by text.
  30342. *
  30343. * Used when the value passed to a property has 4 interpolated values in it:
  30344. *
  30345. * ```html
  30346. * <div title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}suffix"></div>
  30347. * ```
  30348. *
  30349. * Its compiled representation is::
  30350. *
  30351. * ```ts
  30352. * ɵɵpropertyInterpolate4(
  30353. * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, 'suffix');
  30354. * ```
  30355. *
  30356. * If the property name also exists as an input property on one of the element's directives,
  30357. * the component property will be set instead of the element property. This check must
  30358. * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
  30359. *
  30360. * @param propName The name of the property to update
  30361. * @param prefix Static value used for concatenation only.
  30362. * @param v0 Value checked for change.
  30363. * @param i0 Static value used for concatenation only.
  30364. * @param v1 Value checked for change.
  30365. * @param i1 Static value used for concatenation only.
  30366. * @param v2 Value checked for change.
  30367. * @param i2 Static value used for concatenation only.
  30368. * @param v3 Value checked for change.
  30369. * @param suffix Static value used for concatenation only.
  30370. * @param sanitizer An optional sanitizer function
  30371. * @returns itself, so that it may be chained.
  30372. * @codeGenApi
  30373. */
  30374. function ɵɵpropertyInterpolate4(propName, prefix, v0, i0, v1, i1, v2, i2, v3, suffix, sanitizer) {
  30375. const lView = getLView();
  30376. const interpolatedValue = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix);
  30377. if (interpolatedValue !== NO_CHANGE) {
  30378. const tView = getTView();
  30379. const tNode = getSelectedTNode();
  30380. elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
  30381. ngDevMode &&
  30382. storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 4, prefix, i0, i1, i2, suffix);
  30383. }
  30384. return ɵɵpropertyInterpolate4;
  30385. }
  30386. /**
  30387. *
  30388. * Update an interpolated property on an element with 5 bound values surrounded by text.
  30389. *
  30390. * Used when the value passed to a property has 5 interpolated values in it:
  30391. *
  30392. * ```html
  30393. * <div title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}suffix"></div>
  30394. * ```
  30395. *
  30396. * Its compiled representation is::
  30397. *
  30398. * ```ts
  30399. * ɵɵpropertyInterpolate5(
  30400. * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, 'suffix');
  30401. * ```
  30402. *
  30403. * If the property name also exists as an input property on one of the element's directives,
  30404. * the component property will be set instead of the element property. This check must
  30405. * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
  30406. *
  30407. * @param propName The name of the property to update
  30408. * @param prefix Static value used for concatenation only.
  30409. * @param v0 Value checked for change.
  30410. * @param i0 Static value used for concatenation only.
  30411. * @param v1 Value checked for change.
  30412. * @param i1 Static value used for concatenation only.
  30413. * @param v2 Value checked for change.
  30414. * @param i2 Static value used for concatenation only.
  30415. * @param v3 Value checked for change.
  30416. * @param i3 Static value used for concatenation only.
  30417. * @param v4 Value checked for change.
  30418. * @param suffix Static value used for concatenation only.
  30419. * @param sanitizer An optional sanitizer function
  30420. * @returns itself, so that it may be chained.
  30421. * @codeGenApi
  30422. */
  30423. function ɵɵpropertyInterpolate5(propName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix, sanitizer) {
  30424. const lView = getLView();
  30425. const interpolatedValue = interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix);
  30426. if (interpolatedValue !== NO_CHANGE) {
  30427. const tView = getTView();
  30428. const tNode = getSelectedTNode();
  30429. elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
  30430. ngDevMode &&
  30431. storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 5, prefix, i0, i1, i2, i3, suffix);
  30432. }
  30433. return ɵɵpropertyInterpolate5;
  30434. }
  30435. /**
  30436. *
  30437. * Update an interpolated property on an element with 6 bound values surrounded by text.
  30438. *
  30439. * Used when the value passed to a property has 6 interpolated values in it:
  30440. *
  30441. * ```html
  30442. * <div title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}suffix"></div>
  30443. * ```
  30444. *
  30445. * Its compiled representation is::
  30446. *
  30447. * ```ts
  30448. * ɵɵpropertyInterpolate6(
  30449. * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, 'suffix');
  30450. * ```
  30451. *
  30452. * If the property name also exists as an input property on one of the element's directives,
  30453. * the component property will be set instead of the element property. This check must
  30454. * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
  30455. *
  30456. * @param propName The name of the property to update
  30457. * @param prefix Static value used for concatenation only.
  30458. * @param v0 Value checked for change.
  30459. * @param i0 Static value used for concatenation only.
  30460. * @param v1 Value checked for change.
  30461. * @param i1 Static value used for concatenation only.
  30462. * @param v2 Value checked for change.
  30463. * @param i2 Static value used for concatenation only.
  30464. * @param v3 Value checked for change.
  30465. * @param i3 Static value used for concatenation only.
  30466. * @param v4 Value checked for change.
  30467. * @param i4 Static value used for concatenation only.
  30468. * @param v5 Value checked for change.
  30469. * @param suffix Static value used for concatenation only.
  30470. * @param sanitizer An optional sanitizer function
  30471. * @returns itself, so that it may be chained.
  30472. * @codeGenApi
  30473. */
  30474. function ɵɵpropertyInterpolate6(propName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix, sanitizer) {
  30475. const lView = getLView();
  30476. const interpolatedValue = interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix);
  30477. if (interpolatedValue !== NO_CHANGE) {
  30478. const tView = getTView();
  30479. const tNode = getSelectedTNode();
  30480. elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
  30481. ngDevMode &&
  30482. storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 6, prefix, i0, i1, i2, i3, i4, suffix);
  30483. }
  30484. return ɵɵpropertyInterpolate6;
  30485. }
  30486. /**
  30487. *
  30488. * Update an interpolated property on an element with 7 bound values surrounded by text.
  30489. *
  30490. * Used when the value passed to a property has 7 interpolated values in it:
  30491. *
  30492. * ```html
  30493. * <div title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}suffix"></div>
  30494. * ```
  30495. *
  30496. * Its compiled representation is::
  30497. *
  30498. * ```ts
  30499. * ɵɵpropertyInterpolate7(
  30500. * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, 'suffix');
  30501. * ```
  30502. *
  30503. * If the property name also exists as an input property on one of the element's directives,
  30504. * the component property will be set instead of the element property. This check must
  30505. * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
  30506. *
  30507. * @param propName The name of the property to update
  30508. * @param prefix Static value used for concatenation only.
  30509. * @param v0 Value checked for change.
  30510. * @param i0 Static value used for concatenation only.
  30511. * @param v1 Value checked for change.
  30512. * @param i1 Static value used for concatenation only.
  30513. * @param v2 Value checked for change.
  30514. * @param i2 Static value used for concatenation only.
  30515. * @param v3 Value checked for change.
  30516. * @param i3 Static value used for concatenation only.
  30517. * @param v4 Value checked for change.
  30518. * @param i4 Static value used for concatenation only.
  30519. * @param v5 Value checked for change.
  30520. * @param i5 Static value used for concatenation only.
  30521. * @param v6 Value checked for change.
  30522. * @param suffix Static value used for concatenation only.
  30523. * @param sanitizer An optional sanitizer function
  30524. * @returns itself, so that it may be chained.
  30525. * @codeGenApi
  30526. */
  30527. function ɵɵpropertyInterpolate7(propName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix, sanitizer) {
  30528. const lView = getLView();
  30529. const interpolatedValue = interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix);
  30530. if (interpolatedValue !== NO_CHANGE) {
  30531. const tView = getTView();
  30532. const tNode = getSelectedTNode();
  30533. elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
  30534. ngDevMode &&
  30535. storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 7, prefix, i0, i1, i2, i3, i4, i5, suffix);
  30536. }
  30537. return ɵɵpropertyInterpolate7;
  30538. }
  30539. /**
  30540. *
  30541. * Update an interpolated property on an element with 8 bound values surrounded by text.
  30542. *
  30543. * Used when the value passed to a property has 8 interpolated values in it:
  30544. *
  30545. * ```html
  30546. * <div title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}suffix"></div>
  30547. * ```
  30548. *
  30549. * Its compiled representation is::
  30550. *
  30551. * ```ts
  30552. * ɵɵpropertyInterpolate8(
  30553. * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, 'suffix');
  30554. * ```
  30555. *
  30556. * If the property name also exists as an input property on one of the element's directives,
  30557. * the component property will be set instead of the element property. This check must
  30558. * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
  30559. *
  30560. * @param propName The name of the property to update
  30561. * @param prefix Static value used for concatenation only.
  30562. * @param v0 Value checked for change.
  30563. * @param i0 Static value used for concatenation only.
  30564. * @param v1 Value checked for change.
  30565. * @param i1 Static value used for concatenation only.
  30566. * @param v2 Value checked for change.
  30567. * @param i2 Static value used for concatenation only.
  30568. * @param v3 Value checked for change.
  30569. * @param i3 Static value used for concatenation only.
  30570. * @param v4 Value checked for change.
  30571. * @param i4 Static value used for concatenation only.
  30572. * @param v5 Value checked for change.
  30573. * @param i5 Static value used for concatenation only.
  30574. * @param v6 Value checked for change.
  30575. * @param i6 Static value used for concatenation only.
  30576. * @param v7 Value checked for change.
  30577. * @param suffix Static value used for concatenation only.
  30578. * @param sanitizer An optional sanitizer function
  30579. * @returns itself, so that it may be chained.
  30580. * @codeGenApi
  30581. */
  30582. function ɵɵpropertyInterpolate8(propName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix, sanitizer) {
  30583. const lView = getLView();
  30584. const interpolatedValue = interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix);
  30585. if (interpolatedValue !== NO_CHANGE) {
  30586. const tView = getTView();
  30587. const tNode = getSelectedTNode();
  30588. elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
  30589. ngDevMode &&
  30590. storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 8, prefix, i0, i1, i2, i3, i4, i5, i6, suffix);
  30591. }
  30592. return ɵɵpropertyInterpolate8;
  30593. }
  30594. /**
  30595. * Update an interpolated property on an element with 9 or more bound values surrounded by text.
  30596. *
  30597. * Used when the number of interpolated values exceeds 8.
  30598. *
  30599. * ```html
  30600. * <div
  30601. * title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}-{{v8}}-{{v9}}suffix"></div>
  30602. * ```
  30603. *
  30604. * Its compiled representation is::
  30605. *
  30606. * ```ts
  30607. * ɵɵpropertyInterpolateV(
  30608. * 'title', ['prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, '-', v9,
  30609. * 'suffix']);
  30610. * ```
  30611. *
  30612. * If the property name also exists as an input property on one of the element's directives,
  30613. * the component property will be set instead of the element property. This check must
  30614. * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
  30615. *
  30616. * @param propName The name of the property to update.
  30617. * @param values The collection of values and the strings in between those values, beginning with a
  30618. * string prefix and ending with a string suffix.
  30619. * (e.g. `['prefix', value0, '-', value1, '-', value2, ..., value99, 'suffix']`)
  30620. * @param sanitizer An optional sanitizer function
  30621. * @returns itself, so that it may be chained.
  30622. * @codeGenApi
  30623. */
  30624. function ɵɵpropertyInterpolateV(propName, values, sanitizer) {
  30625. const lView = getLView();
  30626. const interpolatedValue = interpolationV(lView, values);
  30627. if (interpolatedValue !== NO_CHANGE) {
  30628. const tView = getTView();
  30629. const tNode = getSelectedTNode();
  30630. elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
  30631. if (ngDevMode) {
  30632. const interpolationInBetween = [values[0]]; // prefix
  30633. for (let i = 2; i < values.length; i += 2) {
  30634. interpolationInBetween.push(values[i]);
  30635. }
  30636. storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - interpolationInBetween.length + 1, ...interpolationInBetween);
  30637. }
  30638. }
  30639. return ɵɵpropertyInterpolateV;
  30640. }
  30641. /**
  30642. * Registers a QueryList, associated with a content query, for later refresh (part of a view
  30643. * refresh).
  30644. *
  30645. * @param directiveIndex Current directive index
  30646. * @param predicate The type for which the query will search
  30647. * @param flags Flags associated with the query
  30648. * @param read What to save in the query
  30649. * @returns QueryList<T>
  30650. *
  30651. * @codeGenApi
  30652. */
  30653. function ɵɵcontentQuery(directiveIndex, predicate, flags, read) {
  30654. createContentQuery(directiveIndex, predicate, flags, read);
  30655. }
  30656. /**
  30657. * Creates a new view query by initializing internal data structures.
  30658. *
  30659. * @param predicate The type for which the query will search
  30660. * @param flags Flags associated with the query
  30661. * @param read What to save in the query
  30662. *
  30663. * @codeGenApi
  30664. */
  30665. function ɵɵviewQuery(predicate, flags, read) {
  30666. createViewQuery(predicate, flags, read);
  30667. }
  30668. /**
  30669. * Refreshes a query by combining matches from all active views and removing matches from deleted
  30670. * views.
  30671. *
  30672. * @returns `true` if a query got dirty during change detection or if this is a static query
  30673. * resolving in creation mode, `false` otherwise.
  30674. *
  30675. * @codeGenApi
  30676. */
  30677. function ɵɵqueryRefresh(queryList) {
  30678. const lView = getLView();
  30679. const tView = getTView();
  30680. const queryIndex = getCurrentQueryIndex();
  30681. setCurrentQueryIndex(queryIndex + 1);
  30682. const tQuery = getTQuery(tView, queryIndex);
  30683. if (queryList.dirty &&
  30684. isCreationMode(lView) ===
  30685. ((tQuery.metadata.flags & 2 /* QueryFlags.isStatic */) === 2 /* QueryFlags.isStatic */)) {
  30686. if (tQuery.matches === null) {
  30687. queryList.reset([]);
  30688. }
  30689. else {
  30690. const result = getQueryResults(lView, queryIndex);
  30691. queryList.reset(result, unwrapElementRef);
  30692. queryList.notifyOnChanges();
  30693. }
  30694. return true;
  30695. }
  30696. return false;
  30697. }
  30698. /**
  30699. * Loads a QueryList corresponding to the current view or content query.
  30700. *
  30701. * @codeGenApi
  30702. */
  30703. function ɵɵloadQuery() {
  30704. return loadQueryInternal(getLView(), getCurrentQueryIndex());
  30705. }
  30706. /**
  30707. * Creates a new content query and binds it to a signal created by an authoring function.
  30708. *
  30709. * @param directiveIndex Current directive index
  30710. * @param target The target signal to which the query should be bound
  30711. * @param predicate The type for which the query will search
  30712. * @param flags Flags associated with the query
  30713. * @param read What to save in the query
  30714. *
  30715. * @codeGenApi
  30716. */
  30717. function ɵɵcontentQuerySignal(directiveIndex, target, predicate, flags, read) {
  30718. bindQueryToSignal(target, createContentQuery(directiveIndex, predicate, flags, read));
  30719. }
  30720. /**
  30721. * Creates a new view query by initializing internal data structures and binding a new query to the
  30722. * target signal.
  30723. *
  30724. * @param target The target signal to assign the query results to.
  30725. * @param predicate The type or label that should match a given query
  30726. * @param flags Flags associated with the query
  30727. * @param read What to save in the query
  30728. *
  30729. * @codeGenApi
  30730. */
  30731. function ɵɵviewQuerySignal(target, predicate, flags, read) {
  30732. bindQueryToSignal(target, createViewQuery(predicate, flags, read));
  30733. }
  30734. /**
  30735. * Advances the current query index by a specified offset.
  30736. *
  30737. * Adjusting the current query index is necessary in cases where a given directive has a mix of
  30738. * zone-based and signal-based queries. The signal-based queries don't require tracking of the
  30739. * current index (those are refreshed on demand and not during change detection) so this instruction
  30740. * is only necessary for backward-compatibility.
  30741. *
  30742. * @param index offset to apply to the current query index (defaults to 1)
  30743. *
  30744. * @codeGenApi
  30745. */
  30746. function ɵɵqueryAdvance(indexOffset = 1) {
  30747. setCurrentQueryIndex(getCurrentQueryIndex() + indexOffset);
  30748. }
  30749. /** Store a value in the `data` at a given `index`. */
  30750. function store(tView, lView, index, value) {
  30751. // We don't store any static data for local variables, so the first time
  30752. // we see the template, we should store as null to avoid a sparse array
  30753. if (index >= tView.data.length) {
  30754. tView.data[index] = null;
  30755. tView.blueprint[index] = null;
  30756. }
  30757. lView[index] = value;
  30758. }
  30759. /**
  30760. * Retrieves a local reference from the current contextViewData.
  30761. *
  30762. * If the reference to retrieve is in a parent view, this instruction is used in conjunction
  30763. * with a nextContext() call, which walks up the tree and updates the contextViewData instance.
  30764. *
  30765. * @param index The index of the local ref in contextViewData.
  30766. *
  30767. * @codeGenApi
  30768. */
  30769. function ɵɵreference(index) {
  30770. const contextLView = getContextLView();
  30771. return load(contextLView, HEADER_OFFSET + index);
  30772. }
  30773. /**
  30774. *
  30775. * Update an interpolated style on an element with single bound value surrounded by text.
  30776. *
  30777. * Used when the value passed to a property has 1 interpolated value in it:
  30778. *
  30779. * ```html
  30780. * <div style="key: {{v0}}suffix"></div>
  30781. * ```
  30782. *
  30783. * Its compiled representation is:
  30784. *
  30785. * ```ts
  30786. * ɵɵstyleMapInterpolate1('key: ', v0, 'suffix');
  30787. * ```
  30788. *
  30789. * @param prefix Static value used for concatenation only.
  30790. * @param v0 Value checked for change.
  30791. * @param suffix Static value used for concatenation only.
  30792. * @codeGenApi
  30793. */
  30794. function ɵɵstyleMapInterpolate1(prefix, v0, suffix) {
  30795. const lView = getLView();
  30796. const interpolatedValue = interpolation1(lView, prefix, v0, suffix);
  30797. ɵɵstyleMap(interpolatedValue);
  30798. }
  30799. /**
  30800. *
  30801. * Update an interpolated style on an element with 2 bound values surrounded by text.
  30802. *
  30803. * Used when the value passed to a property has 2 interpolated values in it:
  30804. *
  30805. * ```html
  30806. * <div style="key: {{v0}}; key1: {{v1}}suffix"></div>
  30807. * ```
  30808. *
  30809. * Its compiled representation is:
  30810. *
  30811. * ```ts
  30812. * ɵɵstyleMapInterpolate2('key: ', v0, '; key1: ', v1, 'suffix');
  30813. * ```
  30814. *
  30815. * @param prefix Static value used for concatenation only.
  30816. * @param v0 Value checked for change.
  30817. * @param i0 Static value used for concatenation only.
  30818. * @param v1 Value checked for change.
  30819. * @param suffix Static value used for concatenation only.
  30820. * @codeGenApi
  30821. */
  30822. function ɵɵstyleMapInterpolate2(prefix, v0, i0, v1, suffix) {
  30823. const lView = getLView();
  30824. const interpolatedValue = interpolation2(lView, prefix, v0, i0, v1, suffix);
  30825. ɵɵstyleMap(interpolatedValue);
  30826. }
  30827. /**
  30828. *
  30829. * Update an interpolated style on an element with 3 bound values surrounded by text.
  30830. *
  30831. * Used when the value passed to a property has 3 interpolated values in it:
  30832. *
  30833. * ```html
  30834. * <div style="key: {{v0}}; key2: {{v1}}; key2: {{v2}}suffix"></div>
  30835. * ```
  30836. *
  30837. * Its compiled representation is:
  30838. *
  30839. * ```ts
  30840. * ɵɵstyleMapInterpolate3(
  30841. * 'key: ', v0, '; key1: ', v1, '; key2: ', v2, 'suffix');
  30842. * ```
  30843. *
  30844. * @param prefix Static value used for concatenation only.
  30845. * @param v0 Value checked for change.
  30846. * @param i0 Static value used for concatenation only.
  30847. * @param v1 Value checked for change.
  30848. * @param i1 Static value used for concatenation only.
  30849. * @param v2 Value checked for change.
  30850. * @param suffix Static value used for concatenation only.
  30851. * @codeGenApi
  30852. */
  30853. function ɵɵstyleMapInterpolate3(prefix, v0, i0, v1, i1, v2, suffix) {
  30854. const lView = getLView();
  30855. const interpolatedValue = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix);
  30856. ɵɵstyleMap(interpolatedValue);
  30857. }
  30858. /**
  30859. *
  30860. * Update an interpolated style on an element with 4 bound values surrounded by text.
  30861. *
  30862. * Used when the value passed to a property has 4 interpolated values in it:
  30863. *
  30864. * ```html
  30865. * <div style="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}suffix"></div>
  30866. * ```
  30867. *
  30868. * Its compiled representation is:
  30869. *
  30870. * ```ts
  30871. * ɵɵstyleMapInterpolate4(
  30872. * 'key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, 'suffix');
  30873. * ```
  30874. *
  30875. * @param prefix Static value used for concatenation only.
  30876. * @param v0 Value checked for change.
  30877. * @param i0 Static value used for concatenation only.
  30878. * @param v1 Value checked for change.
  30879. * @param i1 Static value used for concatenation only.
  30880. * @param v2 Value checked for change.
  30881. * @param i2 Static value used for concatenation only.
  30882. * @param v3 Value checked for change.
  30883. * @param suffix Static value used for concatenation only.
  30884. * @codeGenApi
  30885. */
  30886. function ɵɵstyleMapInterpolate4(prefix, v0, i0, v1, i1, v2, i2, v3, suffix) {
  30887. const lView = getLView();
  30888. const interpolatedValue = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix);
  30889. ɵɵstyleMap(interpolatedValue);
  30890. }
  30891. /**
  30892. *
  30893. * Update an interpolated style on an element with 5 bound values surrounded by text.
  30894. *
  30895. * Used when the value passed to a property has 5 interpolated values in it:
  30896. *
  30897. * ```html
  30898. * <div style="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}; key4: {{v4}}suffix"></div>
  30899. * ```
  30900. *
  30901. * Its compiled representation is:
  30902. *
  30903. * ```ts
  30904. * ɵɵstyleMapInterpolate5(
  30905. * 'key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, '; key4: ', v4, 'suffix');
  30906. * ```
  30907. *
  30908. * @param prefix Static value used for concatenation only.
  30909. * @param v0 Value checked for change.
  30910. * @param i0 Static value used for concatenation only.
  30911. * @param v1 Value checked for change.
  30912. * @param i1 Static value used for concatenation only.
  30913. * @param v2 Value checked for change.
  30914. * @param i2 Static value used for concatenation only.
  30915. * @param v3 Value checked for change.
  30916. * @param i3 Static value used for concatenation only.
  30917. * @param v4 Value checked for change.
  30918. * @param suffix Static value used for concatenation only.
  30919. * @codeGenApi
  30920. */
  30921. function ɵɵstyleMapInterpolate5(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix) {
  30922. const lView = getLView();
  30923. const interpolatedValue = interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix);
  30924. ɵɵstyleMap(interpolatedValue);
  30925. }
  30926. /**
  30927. *
  30928. * Update an interpolated style on an element with 6 bound values surrounded by text.
  30929. *
  30930. * Used when the value passed to a property has 6 interpolated values in it:
  30931. *
  30932. * ```html
  30933. * <div style="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}; key4: {{v4}};
  30934. * key5: {{v5}}suffix"></div>
  30935. * ```
  30936. *
  30937. * Its compiled representation is:
  30938. *
  30939. * ```ts
  30940. * ɵɵstyleMapInterpolate6(
  30941. * 'key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, '; key4: ', v4, '; key5: ', v5,
  30942. * 'suffix');
  30943. * ```
  30944. *
  30945. * @param prefix Static value used for concatenation only.
  30946. * @param v0 Value checked for change.
  30947. * @param i0 Static value used for concatenation only.
  30948. * @param v1 Value checked for change.
  30949. * @param i1 Static value used for concatenation only.
  30950. * @param v2 Value checked for change.
  30951. * @param i2 Static value used for concatenation only.
  30952. * @param v3 Value checked for change.
  30953. * @param i3 Static value used for concatenation only.
  30954. * @param v4 Value checked for change.
  30955. * @param i4 Static value used for concatenation only.
  30956. * @param v5 Value checked for change.
  30957. * @param suffix Static value used for concatenation only.
  30958. * @codeGenApi
  30959. */
  30960. function ɵɵstyleMapInterpolate6(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix) {
  30961. const lView = getLView();
  30962. const interpolatedValue = interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix);
  30963. ɵɵstyleMap(interpolatedValue);
  30964. }
  30965. /**
  30966. *
  30967. * Update an interpolated style on an element with 7 bound values surrounded by text.
  30968. *
  30969. * Used when the value passed to a property has 7 interpolated values in it:
  30970. *
  30971. * ```html
  30972. * <div style="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}; key4: {{v4}}; key5: {{v5}};
  30973. * key6: {{v6}}suffix"></div>
  30974. * ```
  30975. *
  30976. * Its compiled representation is:
  30977. *
  30978. * ```ts
  30979. * ɵɵstyleMapInterpolate7(
  30980. * 'key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, '; key4: ', v4, '; key5: ', v5,
  30981. * '; key6: ', v6, 'suffix');
  30982. * ```
  30983. *
  30984. * @param prefix Static value used for concatenation only.
  30985. * @param v0 Value checked for change.
  30986. * @param i0 Static value used for concatenation only.
  30987. * @param v1 Value checked for change.
  30988. * @param i1 Static value used for concatenation only.
  30989. * @param v2 Value checked for change.
  30990. * @param i2 Static value used for concatenation only.
  30991. * @param v3 Value checked for change.
  30992. * @param i3 Static value used for concatenation only.
  30993. * @param v4 Value checked for change.
  30994. * @param i4 Static value used for concatenation only.
  30995. * @param v5 Value checked for change.
  30996. * @param i5 Static value used for concatenation only.
  30997. * @param v6 Value checked for change.
  30998. * @param suffix Static value used for concatenation only.
  30999. * @codeGenApi
  31000. */
  31001. function ɵɵstyleMapInterpolate7(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix) {
  31002. const lView = getLView();
  31003. const interpolatedValue = interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix);
  31004. ɵɵstyleMap(interpolatedValue);
  31005. }
  31006. /**
  31007. *
  31008. * Update an interpolated style on an element with 8 bound values surrounded by text.
  31009. *
  31010. * Used when the value passed to a property has 8 interpolated values in it:
  31011. *
  31012. * ```html
  31013. * <div style="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}; key4: {{v4}}; key5: {{v5}};
  31014. * key6: {{v6}}; key7: {{v7}}suffix"></div>
  31015. * ```
  31016. *
  31017. * Its compiled representation is:
  31018. *
  31019. * ```ts
  31020. * ɵɵstyleMapInterpolate8(
  31021. * 'key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, '; key4: ', v4, '; key5: ', v5,
  31022. * '; key6: ', v6, '; key7: ', v7, 'suffix');
  31023. * ```
  31024. *
  31025. * @param prefix Static value used for concatenation only.
  31026. * @param v0 Value checked for change.
  31027. * @param i0 Static value used for concatenation only.
  31028. * @param v1 Value checked for change.
  31029. * @param i1 Static value used for concatenation only.
  31030. * @param v2 Value checked for change.
  31031. * @param i2 Static value used for concatenation only.
  31032. * @param v3 Value checked for change.
  31033. * @param i3 Static value used for concatenation only.
  31034. * @param v4 Value checked for change.
  31035. * @param i4 Static value used for concatenation only.
  31036. * @param v5 Value checked for change.
  31037. * @param i5 Static value used for concatenation only.
  31038. * @param v6 Value checked for change.
  31039. * @param i6 Static value used for concatenation only.
  31040. * @param v7 Value checked for change.
  31041. * @param suffix Static value used for concatenation only.
  31042. * @codeGenApi
  31043. */
  31044. function ɵɵstyleMapInterpolate8(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix) {
  31045. const lView = getLView();
  31046. const interpolatedValue = interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix);
  31047. ɵɵstyleMap(interpolatedValue);
  31048. }
  31049. /**
  31050. * Update an interpolated style on an element with 9 or more bound values surrounded by text.
  31051. *
  31052. * Used when the number of interpolated values exceeds 8.
  31053. *
  31054. * ```html
  31055. * <div
  31056. * class="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}; key4: {{v4}}; key5: {{v5}};
  31057. * key6: {{v6}}; key7: {{v7}}; key8: {{v8}}; key9: {{v9}}suffix"></div>
  31058. * ```
  31059. *
  31060. * Its compiled representation is:
  31061. *
  31062. * ```ts
  31063. * ɵɵstyleMapInterpolateV(
  31064. * ['key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, '; key4: ', v4, '; key5: ', v5,
  31065. * '; key6: ', v6, '; key7: ', v7, '; key8: ', v8, '; key9: ', v9, 'suffix']);
  31066. * ```
  31067. *.
  31068. * @param values The collection of values and the strings in-between those values, beginning with
  31069. * a string prefix and ending with a string suffix.
  31070. * (e.g. `['prefix', value0, '; key2: ', value1, '; key2: ', value2, ..., value99, 'suffix']`)
  31071. * @codeGenApi
  31072. */
  31073. function ɵɵstyleMapInterpolateV(values) {
  31074. const lView = getLView();
  31075. const interpolatedValue = interpolationV(lView, values);
  31076. ɵɵstyleMap(interpolatedValue);
  31077. }
  31078. /**
  31079. *
  31080. * Update an interpolated style property on an element with single bound value surrounded by text.
  31081. *
  31082. * Used when the value passed to a property has 1 interpolated value in it:
  31083. *
  31084. * ```html
  31085. * <div style.color="prefix{{v0}}suffix"></div>
  31086. * ```
  31087. *
  31088. * Its compiled representation is:
  31089. *
  31090. * ```ts
  31091. * ɵɵstylePropInterpolate1(0, 'prefix', v0, 'suffix');
  31092. * ```
  31093. *
  31094. * @param styleIndex Index of style to update. This index value refers to the
  31095. * index of the style in the style bindings array that was passed into
  31096. * `styling`.
  31097. * @param prefix Static value used for concatenation only.
  31098. * @param v0 Value checked for change.
  31099. * @param suffix Static value used for concatenation only.
  31100. * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
  31101. * @returns itself, so that it may be chained.
  31102. * @codeGenApi
  31103. */
  31104. function ɵɵstylePropInterpolate1(prop, prefix, v0, suffix, valueSuffix) {
  31105. const lView = getLView();
  31106. const interpolatedValue = interpolation1(lView, prefix, v0, suffix);
  31107. checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
  31108. return ɵɵstylePropInterpolate1;
  31109. }
  31110. /**
  31111. *
  31112. * Update an interpolated style property on an element with 2 bound values surrounded by text.
  31113. *
  31114. * Used when the value passed to a property has 2 interpolated values in it:
  31115. *
  31116. * ```html
  31117. * <div style.color="prefix{{v0}}-{{v1}}suffix"></div>
  31118. * ```
  31119. *
  31120. * Its compiled representation is:
  31121. *
  31122. * ```ts
  31123. * ɵɵstylePropInterpolate2(0, 'prefix', v0, '-', v1, 'suffix');
  31124. * ```
  31125. *
  31126. * @param styleIndex Index of style to update. This index value refers to the
  31127. * index of the style in the style bindings array that was passed into
  31128. * `styling`.
  31129. * @param prefix Static value used for concatenation only.
  31130. * @param v0 Value checked for change.
  31131. * @param i0 Static value used for concatenation only.
  31132. * @param v1 Value checked for change.
  31133. * @param suffix Static value used for concatenation only.
  31134. * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
  31135. * @returns itself, so that it may be chained.
  31136. * @codeGenApi
  31137. */
  31138. function ɵɵstylePropInterpolate2(prop, prefix, v0, i0, v1, suffix, valueSuffix) {
  31139. const lView = getLView();
  31140. const interpolatedValue = interpolation2(lView, prefix, v0, i0, v1, suffix);
  31141. checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
  31142. return ɵɵstylePropInterpolate2;
  31143. }
  31144. /**
  31145. *
  31146. * Update an interpolated style property on an element with 3 bound values surrounded by text.
  31147. *
  31148. * Used when the value passed to a property has 3 interpolated values in it:
  31149. *
  31150. * ```html
  31151. * <div style.color="prefix{{v0}}-{{v1}}-{{v2}}suffix"></div>
  31152. * ```
  31153. *
  31154. * Its compiled representation is:
  31155. *
  31156. * ```ts
  31157. * ɵɵstylePropInterpolate3(0, 'prefix', v0, '-', v1, '-', v2, 'suffix');
  31158. * ```
  31159. *
  31160. * @param styleIndex Index of style to update. This index value refers to the
  31161. * index of the style in the style bindings array that was passed into
  31162. * `styling`.
  31163. * @param prefix Static value used for concatenation only.
  31164. * @param v0 Value checked for change.
  31165. * @param i0 Static value used for concatenation only.
  31166. * @param v1 Value checked for change.
  31167. * @param i1 Static value used for concatenation only.
  31168. * @param v2 Value checked for change.
  31169. * @param suffix Static value used for concatenation only.
  31170. * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
  31171. * @returns itself, so that it may be chained.
  31172. * @codeGenApi
  31173. */
  31174. function ɵɵstylePropInterpolate3(prop, prefix, v0, i0, v1, i1, v2, suffix, valueSuffix) {
  31175. const lView = getLView();
  31176. const interpolatedValue = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix);
  31177. checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
  31178. return ɵɵstylePropInterpolate3;
  31179. }
  31180. /**
  31181. *
  31182. * Update an interpolated style property on an element with 4 bound values surrounded by text.
  31183. *
  31184. * Used when the value passed to a property has 4 interpolated values in it:
  31185. *
  31186. * ```html
  31187. * <div style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}suffix"></div>
  31188. * ```
  31189. *
  31190. * Its compiled representation is:
  31191. *
  31192. * ```ts
  31193. * ɵɵstylePropInterpolate4(0, 'prefix', v0, '-', v1, '-', v2, '-', v3, 'suffix');
  31194. * ```
  31195. *
  31196. * @param styleIndex Index of style to update. This index value refers to the
  31197. * index of the style in the style bindings array that was passed into
  31198. * `styling`.
  31199. * @param prefix Static value used for concatenation only.
  31200. * @param v0 Value checked for change.
  31201. * @param i0 Static value used for concatenation only.
  31202. * @param v1 Value checked for change.
  31203. * @param i1 Static value used for concatenation only.
  31204. * @param v2 Value checked for change.
  31205. * @param i2 Static value used for concatenation only.
  31206. * @param v3 Value checked for change.
  31207. * @param suffix Static value used for concatenation only.
  31208. * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
  31209. * @returns itself, so that it may be chained.
  31210. * @codeGenApi
  31211. */
  31212. function ɵɵstylePropInterpolate4(prop, prefix, v0, i0, v1, i1, v2, i2, v3, suffix, valueSuffix) {
  31213. const lView = getLView();
  31214. const interpolatedValue = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix);
  31215. checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
  31216. return ɵɵstylePropInterpolate4;
  31217. }
  31218. /**
  31219. *
  31220. * Update an interpolated style property on an element with 5 bound values surrounded by text.
  31221. *
  31222. * Used when the value passed to a property has 5 interpolated values in it:
  31223. *
  31224. * ```html
  31225. * <div style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}suffix"></div>
  31226. * ```
  31227. *
  31228. * Its compiled representation is:
  31229. *
  31230. * ```ts
  31231. * ɵɵstylePropInterpolate5(0, 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, 'suffix');
  31232. * ```
  31233. *
  31234. * @param styleIndex Index of style to update. This index value refers to the
  31235. * index of the style in the style bindings array that was passed into
  31236. * `styling`.
  31237. * @param prefix Static value used for concatenation only.
  31238. * @param v0 Value checked for change.
  31239. * @param i0 Static value used for concatenation only.
  31240. * @param v1 Value checked for change.
  31241. * @param i1 Static value used for concatenation only.
  31242. * @param v2 Value checked for change.
  31243. * @param i2 Static value used for concatenation only.
  31244. * @param v3 Value checked for change.
  31245. * @param i3 Static value used for concatenation only.
  31246. * @param v4 Value checked for change.
  31247. * @param suffix Static value used for concatenation only.
  31248. * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
  31249. * @returns itself, so that it may be chained.
  31250. * @codeGenApi
  31251. */
  31252. function ɵɵstylePropInterpolate5(prop, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix, valueSuffix) {
  31253. const lView = getLView();
  31254. const interpolatedValue = interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix);
  31255. checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
  31256. return ɵɵstylePropInterpolate5;
  31257. }
  31258. /**
  31259. *
  31260. * Update an interpolated style property on an element with 6 bound values surrounded by text.
  31261. *
  31262. * Used when the value passed to a property has 6 interpolated values in it:
  31263. *
  31264. * ```html
  31265. * <div style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}suffix"></div>
  31266. * ```
  31267. *
  31268. * Its compiled representation is:
  31269. *
  31270. * ```ts
  31271. * ɵɵstylePropInterpolate6(0, 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, 'suffix');
  31272. * ```
  31273. *
  31274. * @param styleIndex Index of style to update. This index value refers to the
  31275. * index of the style in the style bindings array that was passed into
  31276. * `styling`.
  31277. * @param prefix Static value used for concatenation only.
  31278. * @param v0 Value checked for change.
  31279. * @param i0 Static value used for concatenation only.
  31280. * @param v1 Value checked for change.
  31281. * @param i1 Static value used for concatenation only.
  31282. * @param v2 Value checked for change.
  31283. * @param i2 Static value used for concatenation only.
  31284. * @param v3 Value checked for change.
  31285. * @param i3 Static value used for concatenation only.
  31286. * @param v4 Value checked for change.
  31287. * @param i4 Static value used for concatenation only.
  31288. * @param v5 Value checked for change.
  31289. * @param suffix Static value used for concatenation only.
  31290. * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
  31291. * @returns itself, so that it may be chained.
  31292. * @codeGenApi
  31293. */
  31294. function ɵɵstylePropInterpolate6(prop, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix, valueSuffix) {
  31295. const lView = getLView();
  31296. const interpolatedValue = interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix);
  31297. checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
  31298. return ɵɵstylePropInterpolate6;
  31299. }
  31300. /**
  31301. *
  31302. * Update an interpolated style property on an element with 7 bound values surrounded by text.
  31303. *
  31304. * Used when the value passed to a property has 7 interpolated values in it:
  31305. *
  31306. * ```html
  31307. * <div style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}suffix"></div>
  31308. * ```
  31309. *
  31310. * Its compiled representation is:
  31311. *
  31312. * ```ts
  31313. * ɵɵstylePropInterpolate7(
  31314. * 0, 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, 'suffix');
  31315. * ```
  31316. *
  31317. * @param styleIndex Index of style to update. This index value refers to the
  31318. * index of the style in the style bindings array that was passed into
  31319. * `styling`.
  31320. * @param prefix Static value used for concatenation only.
  31321. * @param v0 Value checked for change.
  31322. * @param i0 Static value used for concatenation only.
  31323. * @param v1 Value checked for change.
  31324. * @param i1 Static value used for concatenation only.
  31325. * @param v2 Value checked for change.
  31326. * @param i2 Static value used for concatenation only.
  31327. * @param v3 Value checked for change.
  31328. * @param i3 Static value used for concatenation only.
  31329. * @param v4 Value checked for change.
  31330. * @param i4 Static value used for concatenation only.
  31331. * @param v5 Value checked for change.
  31332. * @param i5 Static value used for concatenation only.
  31333. * @param v6 Value checked for change.
  31334. * @param suffix Static value used for concatenation only.
  31335. * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
  31336. * @returns itself, so that it may be chained.
  31337. * @codeGenApi
  31338. */
  31339. function ɵɵstylePropInterpolate7(prop, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix, valueSuffix) {
  31340. const lView = getLView();
  31341. const interpolatedValue = interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix);
  31342. checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
  31343. return ɵɵstylePropInterpolate7;
  31344. }
  31345. /**
  31346. *
  31347. * Update an interpolated style property on an element with 8 bound values surrounded by text.
  31348. *
  31349. * Used when the value passed to a property has 8 interpolated values in it:
  31350. *
  31351. * ```html
  31352. * <div style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}suffix"></div>
  31353. * ```
  31354. *
  31355. * Its compiled representation is:
  31356. *
  31357. * ```ts
  31358. * ɵɵstylePropInterpolate8(0, 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6,
  31359. * '-', v7, 'suffix');
  31360. * ```
  31361. *
  31362. * @param styleIndex Index of style to update. This index value refers to the
  31363. * index of the style in the style bindings array that was passed into
  31364. * `styling`.
  31365. * @param prefix Static value used for concatenation only.
  31366. * @param v0 Value checked for change.
  31367. * @param i0 Static value used for concatenation only.
  31368. * @param v1 Value checked for change.
  31369. * @param i1 Static value used for concatenation only.
  31370. * @param v2 Value checked for change.
  31371. * @param i2 Static value used for concatenation only.
  31372. * @param v3 Value checked for change.
  31373. * @param i3 Static value used for concatenation only.
  31374. * @param v4 Value checked for change.
  31375. * @param i4 Static value used for concatenation only.
  31376. * @param v5 Value checked for change.
  31377. * @param i5 Static value used for concatenation only.
  31378. * @param v6 Value checked for change.
  31379. * @param i6 Static value used for concatenation only.
  31380. * @param v7 Value checked for change.
  31381. * @param suffix Static value used for concatenation only.
  31382. * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
  31383. * @returns itself, so that it may be chained.
  31384. * @codeGenApi
  31385. */
  31386. function ɵɵstylePropInterpolate8(prop, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix, valueSuffix) {
  31387. const lView = getLView();
  31388. const interpolatedValue = interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix);
  31389. checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
  31390. return ɵɵstylePropInterpolate8;
  31391. }
  31392. /**
  31393. * Update an interpolated style property on an element with 9 or more bound values surrounded by
  31394. * text.
  31395. *
  31396. * Used when the number of interpolated values exceeds 8.
  31397. *
  31398. * ```html
  31399. * <div
  31400. * style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}-{{v8}}-{{v9}}suffix">
  31401. * </div>
  31402. * ```
  31403. *
  31404. * Its compiled representation is:
  31405. *
  31406. * ```ts
  31407. * ɵɵstylePropInterpolateV(
  31408. * 0, ['prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, '-', v9,
  31409. * 'suffix']);
  31410. * ```
  31411. *
  31412. * @param styleIndex Index of style to update. This index value refers to the
  31413. * index of the style in the style bindings array that was passed into
  31414. * `styling`..
  31415. * @param values The collection of values and the strings in-between those values, beginning with
  31416. * a string prefix and ending with a string suffix.
  31417. * (e.g. `['prefix', value0, '-', value1, '-', value2, ..., value99, 'suffix']`)
  31418. * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
  31419. * @returns itself, so that it may be chained.
  31420. * @codeGenApi
  31421. */
  31422. function ɵɵstylePropInterpolateV(prop, values, valueSuffix) {
  31423. const lView = getLView();
  31424. const interpolatedValue = interpolationV(lView, values);
  31425. checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
  31426. return ɵɵstylePropInterpolateV;
  31427. }
  31428. /**
  31429. * Create static text node
  31430. *
  31431. * @param index Index of the node in the data array
  31432. * @param value Static string value to write.
  31433. *
  31434. * @codeGenApi
  31435. */
  31436. function ɵɵtext(index, value = '') {
  31437. const lView = getLView();
  31438. const tView = getTView();
  31439. const adjustedIndex = index + HEADER_OFFSET;
  31440. ngDevMode &&
  31441. assertEqual(getBindingIndex(), tView.bindingStartIndex, 'text nodes should be created before any bindings');
  31442. ngDevMode && assertIndexInRange(lView, adjustedIndex);
  31443. const tNode = tView.firstCreatePass
  31444. ? getOrCreateTNode(tView, adjustedIndex, 1 /* TNodeType.Text */, value, null)
  31445. : tView.data[adjustedIndex];
  31446. const textNative = _locateOrCreateTextNode(tView, lView, tNode, value, index);
  31447. lView[adjustedIndex] = textNative;
  31448. if (wasLastNodeCreated()) {
  31449. appendChild(tView, lView, textNative, tNode);
  31450. }
  31451. // Text nodes are self closing.
  31452. setCurrentTNode(tNode, false);
  31453. }
  31454. let _locateOrCreateTextNode = (tView, lView, tNode, value, index) => {
  31455. lastNodeWasCreated(true);
  31456. return createTextNode(lView[RENDERER], value);
  31457. };
  31458. /**
  31459. * Enables hydration code path (to lookup existing elements in DOM)
  31460. * in addition to the regular creation mode of text nodes.
  31461. */
  31462. function locateOrCreateTextNodeImpl(tView, lView, tNode, value, index) {
  31463. const hydrationInfo = lView[HYDRATION];
  31464. const isNodeCreationMode = !hydrationInfo ||
  31465. isInSkipHydrationBlock$1() ||
  31466. isDetachedByI18n(tNode) ||
  31467. isDisconnectedNode$1(hydrationInfo, index);
  31468. lastNodeWasCreated(isNodeCreationMode);
  31469. // Regular creation mode.
  31470. if (isNodeCreationMode) {
  31471. return createTextNode(lView[RENDERER], value);
  31472. }
  31473. // Hydration mode, looking up an existing element in DOM.
  31474. const textNative = locateNextRNode(hydrationInfo, tView, lView, tNode);
  31475. ngDevMode && validateMatchingNode(textNative, Node.TEXT_NODE, null, lView, tNode);
  31476. ngDevMode && markRNodeAsClaimedByHydration(textNative);
  31477. return textNative;
  31478. }
  31479. function enableLocateOrCreateTextNodeImpl() {
  31480. _locateOrCreateTextNode = locateOrCreateTextNodeImpl;
  31481. }
  31482. /**
  31483. *
  31484. * Update text content with a lone bound value
  31485. *
  31486. * Used when a text node has 1 interpolated value in it, an no additional text
  31487. * surrounds that interpolated value:
  31488. *
  31489. * ```html
  31490. * <div>{{v0}}</div>
  31491. * ```
  31492. *
  31493. * Its compiled representation is:
  31494. *
  31495. * ```ts
  31496. * ɵɵtextInterpolate(v0);
  31497. * ```
  31498. * @returns itself, so that it may be chained.
  31499. * @see textInterpolateV
  31500. * @codeGenApi
  31501. */
  31502. function ɵɵtextInterpolate(v0) {
  31503. ɵɵtextInterpolate1('', v0, '');
  31504. return ɵɵtextInterpolate;
  31505. }
  31506. /**
  31507. *
  31508. * Update text content with single bound value surrounded by other text.
  31509. *
  31510. * Used when a text node has 1 interpolated value in it:
  31511. *
  31512. * ```html
  31513. * <div>prefix{{v0}}suffix</div>
  31514. * ```
  31515. *
  31516. * Its compiled representation is:
  31517. *
  31518. * ```ts
  31519. * ɵɵtextInterpolate1('prefix', v0, 'suffix');
  31520. * ```
  31521. * @returns itself, so that it may be chained.
  31522. * @see textInterpolateV
  31523. * @codeGenApi
  31524. */
  31525. function ɵɵtextInterpolate1(prefix, v0, suffix) {
  31526. const lView = getLView();
  31527. const interpolated = interpolation1(lView, prefix, v0, suffix);
  31528. if (interpolated !== NO_CHANGE) {
  31529. textBindingInternal(lView, getSelectedIndex(), interpolated);
  31530. }
  31531. return ɵɵtextInterpolate1;
  31532. }
  31533. /**
  31534. *
  31535. * Update text content with 2 bound values surrounded by other text.
  31536. *
  31537. * Used when a text node has 2 interpolated values in it:
  31538. *
  31539. * ```html
  31540. * <div>prefix{{v0}}-{{v1}}suffix</div>
  31541. * ```
  31542. *
  31543. * Its compiled representation is:
  31544. *
  31545. * ```ts
  31546. * ɵɵtextInterpolate2('prefix', v0, '-', v1, 'suffix');
  31547. * ```
  31548. * @returns itself, so that it may be chained.
  31549. * @see textInterpolateV
  31550. * @codeGenApi
  31551. */
  31552. function ɵɵtextInterpolate2(prefix, v0, i0, v1, suffix) {
  31553. const lView = getLView();
  31554. const interpolated = interpolation2(lView, prefix, v0, i0, v1, suffix);
  31555. if (interpolated !== NO_CHANGE) {
  31556. textBindingInternal(lView, getSelectedIndex(), interpolated);
  31557. }
  31558. return ɵɵtextInterpolate2;
  31559. }
  31560. /**
  31561. *
  31562. * Update text content with 3 bound values surrounded by other text.
  31563. *
  31564. * Used when a text node has 3 interpolated values in it:
  31565. *
  31566. * ```html
  31567. * <div>prefix{{v0}}-{{v1}}-{{v2}}suffix</div>
  31568. * ```
  31569. *
  31570. * Its compiled representation is:
  31571. *
  31572. * ```ts
  31573. * ɵɵtextInterpolate3(
  31574. * 'prefix', v0, '-', v1, '-', v2, 'suffix');
  31575. * ```
  31576. * @returns itself, so that it may be chained.
  31577. * @see textInterpolateV
  31578. * @codeGenApi
  31579. */
  31580. function ɵɵtextInterpolate3(prefix, v0, i0, v1, i1, v2, suffix) {
  31581. const lView = getLView();
  31582. const interpolated = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix);
  31583. if (interpolated !== NO_CHANGE) {
  31584. textBindingInternal(lView, getSelectedIndex(), interpolated);
  31585. }
  31586. return ɵɵtextInterpolate3;
  31587. }
  31588. /**
  31589. *
  31590. * Update text content with 4 bound values surrounded by other text.
  31591. *
  31592. * Used when a text node has 4 interpolated values in it:
  31593. *
  31594. * ```html
  31595. * <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}suffix</div>
  31596. * ```
  31597. *
  31598. * Its compiled representation is:
  31599. *
  31600. * ```ts
  31601. * ɵɵtextInterpolate4(
  31602. * 'prefix', v0, '-', v1, '-', v2, '-', v3, 'suffix');
  31603. * ```
  31604. * @returns itself, so that it may be chained.
  31605. * @see ɵɵtextInterpolateV
  31606. * @codeGenApi
  31607. */
  31608. function ɵɵtextInterpolate4(prefix, v0, i0, v1, i1, v2, i2, v3, suffix) {
  31609. const lView = getLView();
  31610. const interpolated = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix);
  31611. if (interpolated !== NO_CHANGE) {
  31612. textBindingInternal(lView, getSelectedIndex(), interpolated);
  31613. }
  31614. return ɵɵtextInterpolate4;
  31615. }
  31616. /**
  31617. *
  31618. * Update text content with 5 bound values surrounded by other text.
  31619. *
  31620. * Used when a text node has 5 interpolated values in it:
  31621. *
  31622. * ```html
  31623. * <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}suffix</div>
  31624. * ```
  31625. *
  31626. * Its compiled representation is:
  31627. *
  31628. * ```ts
  31629. * ɵɵtextInterpolate5(
  31630. * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, 'suffix');
  31631. * ```
  31632. * @returns itself, so that it may be chained.
  31633. * @see textInterpolateV
  31634. * @codeGenApi
  31635. */
  31636. function ɵɵtextInterpolate5(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix) {
  31637. const lView = getLView();
  31638. const interpolated = interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix);
  31639. if (interpolated !== NO_CHANGE) {
  31640. textBindingInternal(lView, getSelectedIndex(), interpolated);
  31641. }
  31642. return ɵɵtextInterpolate5;
  31643. }
  31644. /**
  31645. *
  31646. * Update text content with 6 bound values surrounded by other text.
  31647. *
  31648. * Used when a text node has 6 interpolated values in it:
  31649. *
  31650. * ```html
  31651. * <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}suffix</div>
  31652. * ```
  31653. *
  31654. * Its compiled representation is:
  31655. *
  31656. * ```ts
  31657. * ɵɵtextInterpolate6(
  31658. * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, 'suffix');
  31659. * ```
  31660. *
  31661. * @param i4 Static value used for concatenation only.
  31662. * @param v5 Value checked for change. @returns itself, so that it may be chained.
  31663. * @see textInterpolateV
  31664. * @codeGenApi
  31665. */
  31666. function ɵɵtextInterpolate6(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix) {
  31667. const lView = getLView();
  31668. const interpolated = interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix);
  31669. if (interpolated !== NO_CHANGE) {
  31670. textBindingInternal(lView, getSelectedIndex(), interpolated);
  31671. }
  31672. return ɵɵtextInterpolate6;
  31673. }
  31674. /**
  31675. *
  31676. * Update text content with 7 bound values surrounded by other text.
  31677. *
  31678. * Used when a text node has 7 interpolated values in it:
  31679. *
  31680. * ```html
  31681. * <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}suffix</div>
  31682. * ```
  31683. *
  31684. * Its compiled representation is:
  31685. *
  31686. * ```ts
  31687. * ɵɵtextInterpolate7(
  31688. * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, 'suffix');
  31689. * ```
  31690. * @returns itself, so that it may be chained.
  31691. * @see textInterpolateV
  31692. * @codeGenApi
  31693. */
  31694. function ɵɵtextInterpolate7(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix) {
  31695. const lView = getLView();
  31696. const interpolated = interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix);
  31697. if (interpolated !== NO_CHANGE) {
  31698. textBindingInternal(lView, getSelectedIndex(), interpolated);
  31699. }
  31700. return ɵɵtextInterpolate7;
  31701. }
  31702. /**
  31703. *
  31704. * Update text content with 8 bound values surrounded by other text.
  31705. *
  31706. * Used when a text node has 8 interpolated values in it:
  31707. *
  31708. * ```html
  31709. * <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}suffix</div>
  31710. * ```
  31711. *
  31712. * Its compiled representation is:
  31713. *
  31714. * ```ts
  31715. * ɵɵtextInterpolate8(
  31716. * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, 'suffix');
  31717. * ```
  31718. * @returns itself, so that it may be chained.
  31719. * @see textInterpolateV
  31720. * @codeGenApi
  31721. */
  31722. function ɵɵtextInterpolate8(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix) {
  31723. const lView = getLView();
  31724. const interpolated = interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix);
  31725. if (interpolated !== NO_CHANGE) {
  31726. textBindingInternal(lView, getSelectedIndex(), interpolated);
  31727. }
  31728. return ɵɵtextInterpolate8;
  31729. }
  31730. /**
  31731. * Update text content with 9 or more bound values other surrounded by text.
  31732. *
  31733. * Used when the number of interpolated values exceeds 8.
  31734. *
  31735. * ```html
  31736. * <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}-{{v8}}-{{v9}}suffix</div>
  31737. * ```
  31738. *
  31739. * Its compiled representation is:
  31740. *
  31741. * ```ts
  31742. * ɵɵtextInterpolateV(
  31743. * ['prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, '-', v9,
  31744. * 'suffix']);
  31745. * ```
  31746. *.
  31747. * @param values The collection of values and the strings in between those values, beginning with
  31748. * a string prefix and ending with a string suffix.
  31749. * (e.g. `['prefix', value0, '-', value1, '-', value2, ..., value99, 'suffix']`)
  31750. *
  31751. * @returns itself, so that it may be chained.
  31752. * @codeGenApi
  31753. */
  31754. function ɵɵtextInterpolateV(values) {
  31755. const lView = getLView();
  31756. const interpolated = interpolationV(lView, values);
  31757. if (interpolated !== NO_CHANGE) {
  31758. textBindingInternal(lView, getSelectedIndex(), interpolated);
  31759. }
  31760. return ɵɵtextInterpolateV;
  31761. }
  31762. /**
  31763. * Updates a text binding at a given index in a given LView.
  31764. */
  31765. function textBindingInternal(lView, index, value) {
  31766. ngDevMode && assertString(value, 'Value should be a string');
  31767. ngDevMode && assertNotSame(value, NO_CHANGE, 'value should not be NO_CHANGE');
  31768. ngDevMode && assertIndexInRange(lView, index);
  31769. const element = getNativeByIndex(index, lView);
  31770. ngDevMode && assertDefined(element, 'native element should exist');
  31771. updateTextNode(lView[RENDERER], element, value);
  31772. }
  31773. /*!
  31774. * @license
  31775. * Copyright Google LLC All Rights Reserved.
  31776. *
  31777. * Use of this source code is governed by an MIT-style license that can be
  31778. * found in the LICENSE file at https://angular.dev/license
  31779. */
  31780. /**
  31781. * Update a two-way bound property on a selected element.
  31782. *
  31783. * Operates on the element selected by index via the {@link select} instruction.
  31784. *
  31785. * @param propName Name of property.
  31786. * @param value New value to write.
  31787. * @param sanitizer An optional function used to sanitize the value.
  31788. * @returns This function returns itself so that it may be chained
  31789. * (e.g. `twoWayProperty('name', ctx.name)('title', ctx.title)`)
  31790. *
  31791. * @codeGenApi
  31792. */
  31793. function ɵɵtwoWayProperty(propName, value, sanitizer) {
  31794. // TODO(crisbeto): perf impact of re-evaluating this on each change detection?
  31795. if (isWritableSignal(value)) {
  31796. value = value();
  31797. }
  31798. const lView = getLView();
  31799. const bindingIndex = nextBindingIndex();
  31800. if (bindingUpdated(lView, bindingIndex, value)) {
  31801. const tView = getTView();
  31802. const tNode = getSelectedTNode();
  31803. elementPropertyInternal(tView, tNode, lView, propName, value, lView[RENDERER], sanitizer, false);
  31804. ngDevMode && storePropertyBindingMetadata(tView.data, tNode, propName, bindingIndex);
  31805. }
  31806. return ɵɵtwoWayProperty;
  31807. }
  31808. /**
  31809. * Function used inside two-way listeners to conditionally set the value of the bound expression.
  31810. *
  31811. * @param target Field on which to set the value.
  31812. * @param value Value to be set to the field.
  31813. *
  31814. * @codeGenApi
  31815. */
  31816. function ɵɵtwoWayBindingSet(target, value) {
  31817. const canWrite = isWritableSignal(target);
  31818. canWrite && target.set(value);
  31819. return canWrite;
  31820. }
  31821. /**
  31822. * Adds an event listener that updates a two-way binding to the current node.
  31823. *
  31824. * @param eventName Name of the event.
  31825. * @param listenerFn The function to be called when event emits.
  31826. *
  31827. * @codeGenApi
  31828. */
  31829. function ɵɵtwoWayListener(eventName, listenerFn) {
  31830. const lView = getLView();
  31831. const tView = getTView();
  31832. const tNode = getCurrentTNode();
  31833. listenerInternal(tView, lView, lView[RENDERER], tNode, eventName, listenerFn);
  31834. return ɵɵtwoWayListener;
  31835. }
  31836. /*!
  31837. * @license
  31838. * Copyright Google LLC All Rights Reserved.
  31839. *
  31840. * Use of this source code is governed by an MIT-style license that can be
  31841. * found in the LICENSE file at https://angular.dev/license
  31842. */
  31843. /** Object that indicates the value of a `@let` declaration that hasn't been initialized yet. */
  31844. const UNINITIALIZED_LET = {};
  31845. /**
  31846. * Declares an `@let` at a specific data slot. Returns itself to allow chaining.
  31847. *
  31848. * @param index Index at which to declare the `@let`.
  31849. *
  31850. * @codeGenApi
  31851. */
  31852. function ɵɵdeclareLet(index) {
  31853. const tView = getTView();
  31854. const lView = getLView();
  31855. const adjustedIndex = index + HEADER_OFFSET;
  31856. const tNode = getOrCreateTNode(tView, adjustedIndex, 128 /* TNodeType.LetDeclaration */, null, null);
  31857. setCurrentTNode(tNode, false);
  31858. store(tView, lView, adjustedIndex, UNINITIALIZED_LET);
  31859. return ɵɵdeclareLet;
  31860. }
  31861. /**
  31862. * Instruction that stores the value of a `@let` declaration on the current view.
  31863. * Returns the value to allow usage inside variable initializers.
  31864. *
  31865. * @codeGenApi
  31866. */
  31867. function ɵɵstoreLet(value) {
  31868. performanceMarkFeature('NgLet');
  31869. const tView = getTView();
  31870. const lView = getLView();
  31871. const index = getSelectedIndex();
  31872. store(tView, lView, index, value);
  31873. return value;
  31874. }
  31875. /**
  31876. * Retrieves the value of a `@let` declaration defined in a parent view.
  31877. *
  31878. * @param index Index of the declaration within the view.
  31879. *
  31880. * @codeGenApi
  31881. */
  31882. function ɵɵreadContextLet(index) {
  31883. const contextLView = getContextLView();
  31884. const value = load(contextLView, HEADER_OFFSET + index);
  31885. if (value === UNINITIALIZED_LET) {
  31886. throw new RuntimeError(314 /* RuntimeErrorCode.UNINITIALIZED_LET_ACCESS */, ngDevMode && 'Attempting to access a @let declaration whose value is not available yet');
  31887. }
  31888. return value;
  31889. }
  31890. /*!
  31891. * @license
  31892. * Copyright Google LLC All Rights Reserved.
  31893. *
  31894. * Use of this source code is governed by an MIT-style license that can be
  31895. * found in the LICENSE file at https://angular.dev/license
  31896. */
  31897. /**
  31898. * Sets the location within the source template at which
  31899. * each element in the current view was defined.
  31900. *
  31901. * @param index Index at which the DOM node was created.
  31902. * @param templatePath Path to the template at which the node was defined.
  31903. * @param locations Element locations to which to attach the source location.
  31904. *
  31905. * @codeGenApi
  31906. */
  31907. function ɵɵattachSourceLocations(templatePath, locations) {
  31908. const tView = getTView();
  31909. const lView = getLView();
  31910. const renderer = lView[RENDERER];
  31911. const attributeName = 'data-ng-source-location';
  31912. for (const [index, offset, line, column] of locations) {
  31913. const tNode = getTNode(tView, index + HEADER_OFFSET);
  31914. // The compiler shouldn't generate the instruction for non-element nodes, but assert just in case.
  31915. ngDevMode && assertTNodeType(tNode, 2 /* TNodeType.Element */);
  31916. const node = getNativeByIndex(index + HEADER_OFFSET, lView);
  31917. // Set the attribute directly in the DOM so it doesn't participate in directive matching.
  31918. if (!node.hasAttribute(attributeName)) {
  31919. const attributeValue = `${templatePath}@o:${offset},l:${line},c:${column}`;
  31920. renderer.setAttribute(node, attributeName, attributeValue);
  31921. }
  31922. }
  31923. }
  31924. /**
  31925. * Resolves the providers which are defined in the DirectiveDef.
  31926. *
  31927. * When inserting the tokens and the factories in their respective arrays, we can assume that
  31928. * this method is called first for the component (if any), and then for other directives on the same
  31929. * node.
  31930. * As a consequence,the providers are always processed in that order:
  31931. * 1) The view providers of the component
  31932. * 2) The providers of the component
  31933. * 3) The providers of the other directives
  31934. * This matches the structure of the injectables arrays of a view (for each node).
  31935. * So the tokens and the factories can be pushed at the end of the arrays, except
  31936. * in one case for multi providers.
  31937. *
  31938. * @param def the directive definition
  31939. * @param providers: Array of `providers`.
  31940. * @param viewProviders: Array of `viewProviders`.
  31941. */
  31942. function providersResolver(def, providers, viewProviders) {
  31943. const tView = getTView();
  31944. if (tView.firstCreatePass) {
  31945. const isComponent = isComponentDef(def);
  31946. // The list of view providers is processed first, and the flags are updated
  31947. resolveProvider(viewProviders, tView.data, tView.blueprint, isComponent, true);
  31948. // Then, the list of providers is processed, and the flags are updated
  31949. resolveProvider(providers, tView.data, tView.blueprint, isComponent, false);
  31950. }
  31951. }
  31952. /**
  31953. * Resolves a provider and publishes it to the DI system.
  31954. */
  31955. function resolveProvider(provider, tInjectables, lInjectablesBlueprint, isComponent, isViewProvider) {
  31956. provider = resolveForwardRef(provider);
  31957. if (Array.isArray(provider)) {
  31958. // Recursively call `resolveProvider`
  31959. // Recursion is OK in this case because this code will not be in hot-path once we implement
  31960. // cloning of the initial state.
  31961. for (let i = 0; i < provider.length; i++) {
  31962. resolveProvider(provider[i], tInjectables, lInjectablesBlueprint, isComponent, isViewProvider);
  31963. }
  31964. }
  31965. else {
  31966. const tView = getTView();
  31967. const lView = getLView();
  31968. const tNode = getCurrentTNode();
  31969. let token = isTypeProvider(provider) ? provider : resolveForwardRef(provider.provide);
  31970. const providerFactory = providerToFactory(provider);
  31971. if (ngDevMode) {
  31972. const injector = new NodeInjector(tNode, lView);
  31973. runInInjectorProfilerContext(injector, token, () => {
  31974. emitProviderConfiguredEvent(provider, isViewProvider);
  31975. });
  31976. }
  31977. const beginIndex = tNode.providerIndexes & 1048575 /* TNodeProviderIndexes.ProvidersStartIndexMask */;
  31978. const endIndex = tNode.directiveStart;
  31979. const cptViewProvidersCount = tNode.providerIndexes >> 20 /* TNodeProviderIndexes.CptViewProvidersCountShift */;
  31980. if (isTypeProvider(provider) || !provider.multi) {
  31981. // Single provider case: the factory is created and pushed immediately
  31982. const factory = new NodeInjectorFactory(providerFactory, isViewProvider, ɵɵdirectiveInject);
  31983. const existingFactoryIndex = indexOf(token, tInjectables, isViewProvider ? beginIndex : beginIndex + cptViewProvidersCount, endIndex);
  31984. if (existingFactoryIndex === -1) {
  31985. diPublicInInjector(getOrCreateNodeInjectorForNode(tNode, lView), tView, token);
  31986. registerDestroyHooksIfSupported(tView, provider, tInjectables.length);
  31987. tInjectables.push(token);
  31988. tNode.directiveStart++;
  31989. tNode.directiveEnd++;
  31990. if (isViewProvider) {
  31991. tNode.providerIndexes += 1048576 /* TNodeProviderIndexes.CptViewProvidersCountShifter */;
  31992. }
  31993. lInjectablesBlueprint.push(factory);
  31994. lView.push(factory);
  31995. }
  31996. else {
  31997. lInjectablesBlueprint[existingFactoryIndex] = factory;
  31998. lView[existingFactoryIndex] = factory;
  31999. }
  32000. }
  32001. else {
  32002. // Multi provider case:
  32003. // We create a multi factory which is going to aggregate all the values.
  32004. // Since the output of such a factory depends on content or view injection,
  32005. // we create two of them, which are linked together.
  32006. //
  32007. // The first one (for view providers) is always in the first block of the injectables array,
  32008. // and the second one (for providers) is always in the second block.
  32009. // This is important because view providers have higher priority. When a multi token
  32010. // is being looked up, the view providers should be found first.
  32011. // Note that it is not possible to have a multi factory in the third block (directive block).
  32012. //
  32013. // The algorithm to process multi providers is as follows:
  32014. // 1) If the multi provider comes from the `viewProviders` of the component:
  32015. // a) If the special view providers factory doesn't exist, it is created and pushed.
  32016. // b) Else, the multi provider is added to the existing multi factory.
  32017. // 2) If the multi provider comes from the `providers` of the component or of another
  32018. // directive:
  32019. // a) If the multi factory doesn't exist, it is created and provider pushed into it.
  32020. // It is also linked to the multi factory for view providers, if it exists.
  32021. // b) Else, the multi provider is added to the existing multi factory.
  32022. const existingProvidersFactoryIndex = indexOf(token, tInjectables, beginIndex + cptViewProvidersCount, endIndex);
  32023. const existingViewProvidersFactoryIndex = indexOf(token, tInjectables, beginIndex, beginIndex + cptViewProvidersCount);
  32024. const doesProvidersFactoryExist = existingProvidersFactoryIndex >= 0 && lInjectablesBlueprint[existingProvidersFactoryIndex];
  32025. const doesViewProvidersFactoryExist = existingViewProvidersFactoryIndex >= 0 &&
  32026. lInjectablesBlueprint[existingViewProvidersFactoryIndex];
  32027. if ((isViewProvider && !doesViewProvidersFactoryExist) ||
  32028. (!isViewProvider && !doesProvidersFactoryExist)) {
  32029. // Cases 1.a and 2.a
  32030. diPublicInInjector(getOrCreateNodeInjectorForNode(tNode, lView), tView, token);
  32031. const factory = multiFactory(isViewProvider ? multiViewProvidersFactoryResolver : multiProvidersFactoryResolver, lInjectablesBlueprint.length, isViewProvider, isComponent, providerFactory);
  32032. if (!isViewProvider && doesViewProvidersFactoryExist) {
  32033. lInjectablesBlueprint[existingViewProvidersFactoryIndex].providerFactory = factory;
  32034. }
  32035. registerDestroyHooksIfSupported(tView, provider, tInjectables.length, 0);
  32036. tInjectables.push(token);
  32037. tNode.directiveStart++;
  32038. tNode.directiveEnd++;
  32039. if (isViewProvider) {
  32040. tNode.providerIndexes += 1048576 /* TNodeProviderIndexes.CptViewProvidersCountShifter */;
  32041. }
  32042. lInjectablesBlueprint.push(factory);
  32043. lView.push(factory);
  32044. }
  32045. else {
  32046. // Cases 1.b and 2.b
  32047. const indexInFactory = multiFactoryAdd(lInjectablesBlueprint[isViewProvider ? existingViewProvidersFactoryIndex : existingProvidersFactoryIndex], providerFactory, !isViewProvider && isComponent);
  32048. registerDestroyHooksIfSupported(tView, provider, existingProvidersFactoryIndex > -1
  32049. ? existingProvidersFactoryIndex
  32050. : existingViewProvidersFactoryIndex, indexInFactory);
  32051. }
  32052. if (!isViewProvider && isComponent && doesViewProvidersFactoryExist) {
  32053. lInjectablesBlueprint[existingViewProvidersFactoryIndex].componentProviders++;
  32054. }
  32055. }
  32056. }
  32057. }
  32058. /**
  32059. * Registers the `ngOnDestroy` hook of a provider, if the provider supports destroy hooks.
  32060. * @param tView `TView` in which to register the hook.
  32061. * @param provider Provider whose hook should be registered.
  32062. * @param contextIndex Index under which to find the context for the hook when it's being invoked.
  32063. * @param indexInFactory Only required for `multi` providers. Index of the provider in the multi
  32064. * provider factory.
  32065. */
  32066. function registerDestroyHooksIfSupported(tView, provider, contextIndex, indexInFactory) {
  32067. const providerIsTypeProvider = isTypeProvider(provider);
  32068. const providerIsClassProvider = isClassProvider(provider);
  32069. if (providerIsTypeProvider || providerIsClassProvider) {
  32070. // Resolve forward references as `useClass` can hold a forward reference.
  32071. const classToken = providerIsClassProvider ? resolveForwardRef(provider.useClass) : provider;
  32072. const prototype = classToken.prototype;
  32073. const ngOnDestroy = prototype.ngOnDestroy;
  32074. if (ngOnDestroy) {
  32075. const hooks = tView.destroyHooks || (tView.destroyHooks = []);
  32076. if (!providerIsTypeProvider && provider.multi) {
  32077. ngDevMode &&
  32078. assertDefined(indexInFactory, 'indexInFactory when registering multi factory destroy hook');
  32079. const existingCallbacksIndex = hooks.indexOf(contextIndex);
  32080. if (existingCallbacksIndex === -1) {
  32081. hooks.push(contextIndex, [indexInFactory, ngOnDestroy]);
  32082. }
  32083. else {
  32084. hooks[existingCallbacksIndex + 1].push(indexInFactory, ngOnDestroy);
  32085. }
  32086. }
  32087. else {
  32088. hooks.push(contextIndex, ngOnDestroy);
  32089. }
  32090. }
  32091. }
  32092. }
  32093. /**
  32094. * Add a factory in a multi factory.
  32095. * @returns Index at which the factory was inserted.
  32096. */
  32097. function multiFactoryAdd(multiFactory, factory, isComponentProvider) {
  32098. if (isComponentProvider) {
  32099. multiFactory.componentProviders++;
  32100. }
  32101. return multiFactory.multi.push(factory) - 1;
  32102. }
  32103. /**
  32104. * Returns the index of item in the array, but only in the begin to end range.
  32105. */
  32106. function indexOf(item, arr, begin, end) {
  32107. for (let i = begin; i < end; i++) {
  32108. if (arr[i] === item)
  32109. return i;
  32110. }
  32111. return -1;
  32112. }
  32113. /**
  32114. * Use this with `multi` `providers`.
  32115. */
  32116. function multiProvidersFactoryResolver(_, tData, lData, tNode) {
  32117. return multiResolve(this.multi, []);
  32118. }
  32119. /**
  32120. * Use this with `multi` `viewProviders`.
  32121. *
  32122. * This factory knows how to concatenate itself with the existing `multi` `providers`.
  32123. */
  32124. function multiViewProvidersFactoryResolver(_, tData, lView, tNode) {
  32125. const factories = this.multi;
  32126. let result;
  32127. if (this.providerFactory) {
  32128. const componentCount = this.providerFactory.componentProviders;
  32129. const multiProviders = getNodeInjectable(lView, lView[TVIEW], this.providerFactory.index, tNode);
  32130. // Copy the section of the array which contains `multi` `providers` from the component
  32131. result = multiProviders.slice(0, componentCount);
  32132. // Insert the `viewProvider` instances.
  32133. multiResolve(factories, result);
  32134. // Copy the section of the array which contains `multi` `providers` from other directives
  32135. for (let i = componentCount; i < multiProviders.length; i++) {
  32136. result.push(multiProviders[i]);
  32137. }
  32138. }
  32139. else {
  32140. result = [];
  32141. // Insert the `viewProvider` instances.
  32142. multiResolve(factories, result);
  32143. }
  32144. return result;
  32145. }
  32146. /**
  32147. * Maps an array of factories into an array of values.
  32148. */
  32149. function multiResolve(factories, result) {
  32150. for (let i = 0; i < factories.length; i++) {
  32151. const factory = factories[i];
  32152. result.push(factory());
  32153. }
  32154. return result;
  32155. }
  32156. /**
  32157. * Creates a multi factory.
  32158. */
  32159. function multiFactory(factoryFn, index, isViewProvider, isComponent, f) {
  32160. const factory = new NodeInjectorFactory(factoryFn, isViewProvider, ɵɵdirectiveInject);
  32161. factory.multi = [];
  32162. factory.index = index;
  32163. factory.componentProviders = 0;
  32164. multiFactoryAdd(factory, f, isComponent && !isViewProvider);
  32165. return factory;
  32166. }
  32167. /**
  32168. * This feature resolves the providers of a directive (or component),
  32169. * and publish them into the DI system, making it visible to others for injection.
  32170. *
  32171. * For example:
  32172. * ```ts
  32173. * class ComponentWithProviders {
  32174. * constructor(private greeter: GreeterDE) {}
  32175. *
  32176. * static ɵcmp = defineComponent({
  32177. * type: ComponentWithProviders,
  32178. * selectors: [['component-with-providers']],
  32179. * factory: () => new ComponentWithProviders(directiveInject(GreeterDE as any)),
  32180. * decls: 1,
  32181. * vars: 1,
  32182. * template: function(fs: RenderFlags, ctx: ComponentWithProviders) {
  32183. * if (fs & RenderFlags.Create) {
  32184. * ɵɵtext(0);
  32185. * }
  32186. * if (fs & RenderFlags.Update) {
  32187. * ɵɵtextInterpolate(ctx.greeter.greet());
  32188. * }
  32189. * },
  32190. * features: [ɵɵProvidersFeature([GreeterDE])]
  32191. * });
  32192. * }
  32193. * ```
  32194. *
  32195. * @param definition
  32196. *
  32197. * @codeGenApi
  32198. */
  32199. function ɵɵProvidersFeature(providers, viewProviders = []) {
  32200. return (definition) => {
  32201. definition.providersResolver = (def, processProvidersFn) => {
  32202. return providersResolver(def, //
  32203. processProvidersFn ? processProvidersFn(providers) : providers, //
  32204. viewProviders);
  32205. };
  32206. };
  32207. }
  32208. /**
  32209. * A feature that adds support for external runtime styles for a component.
  32210. * An external runtime style is a URL to a CSS stylesheet that contains the styles
  32211. * for a given component. For browsers, this URL will be used in an appended `link` element
  32212. * when the component is rendered. This feature is typically used for Hot Module Replacement
  32213. * (HMR) of component stylesheets by leveraging preexisting global stylesheet HMR available
  32214. * in most development servers.
  32215. *
  32216. * @codeGenApi
  32217. */
  32218. function ɵɵExternalStylesFeature(styleUrls) {
  32219. return (definition) => {
  32220. if (styleUrls.length < 1) {
  32221. return;
  32222. }
  32223. definition.getExternalStyles = (encapsulationId) => {
  32224. // Add encapsulation ID search parameter `ngcomp` to support external style encapsulation as well as the encapsulation mode
  32225. // for usage tracking.
  32226. const urls = styleUrls.map((value) => value +
  32227. '?ngcomp' +
  32228. (encapsulationId ? '=' + encodeURIComponent(encapsulationId) : '') +
  32229. '&e=' +
  32230. definition.encapsulation);
  32231. return urls;
  32232. };
  32233. };
  32234. }
  32235. /**
  32236. * Generated next to NgModules to monkey-patch directive and pipe references onto a component's
  32237. * definition, when generating a direct reference in the component file would otherwise create an
  32238. * import cycle.
  32239. *
  32240. * See [this explanation](https://hackmd.io/Odw80D0pR6yfsOjg_7XCJg?view) for more details.
  32241. *
  32242. * @codeGenApi
  32243. */
  32244. function ɵɵsetComponentScope(type, directives, pipes) {
  32245. const def = type.ɵcmp;
  32246. def.directiveDefs = extractDefListOrFactory(directives, /* pipeDef */ false);
  32247. def.pipeDefs = extractDefListOrFactory(pipes, /* pipeDef */ true);
  32248. }
  32249. /**
  32250. * Adds the module metadata that is necessary to compute the module's transitive scope to an
  32251. * existing module definition.
  32252. *
  32253. * Scope metadata of modules is not used in production builds, so calls to this function can be
  32254. * marked pure to tree-shake it from the bundle, allowing for all referenced declarations
  32255. * to become eligible for tree-shaking as well.
  32256. *
  32257. * @codeGenApi
  32258. */
  32259. function ɵɵsetNgModuleScope(type, scope) {
  32260. return noSideEffects(() => {
  32261. const ngModuleDef = getNgModuleDef(type, true);
  32262. ngModuleDef.declarations = convertToTypeArray(scope.declarations || EMPTY_ARRAY);
  32263. ngModuleDef.imports = convertToTypeArray(scope.imports || EMPTY_ARRAY);
  32264. ngModuleDef.exports = convertToTypeArray(scope.exports || EMPTY_ARRAY);
  32265. if (scope.bootstrap) {
  32266. // This only happens in local compilation mode.
  32267. ngModuleDef.bootstrap = convertToTypeArray(scope.bootstrap);
  32268. }
  32269. depsTracker.registerNgModule(type, scope);
  32270. });
  32271. }
  32272. function convertToTypeArray(values) {
  32273. if (typeof values === 'function') {
  32274. return values;
  32275. }
  32276. const flattenValues = flatten(values);
  32277. if (flattenValues.some(isForwardRef)) {
  32278. return () => flattenValues.map(resolveForwardRef).map(maybeUnwrapModuleWithProviders);
  32279. }
  32280. else {
  32281. return flattenValues.map(maybeUnwrapModuleWithProviders);
  32282. }
  32283. }
  32284. function maybeUnwrapModuleWithProviders(value) {
  32285. return isModuleWithProviders(value) ? value.ngModule : value;
  32286. }
  32287. /**
  32288. * Bindings for pure functions are stored after regular bindings.
  32289. *
  32290. * |-------decls------|---------vars---------| |----- hostVars (dir1) ------|
  32291. * ------------------------------------------------------------------------------------------
  32292. * | nodes/refs/pipes | bindings | fn slots | injector | dir1 | host bindings | host slots |
  32293. * ------------------------------------------------------------------------------------------
  32294. * ^ ^
  32295. * TView.bindingStartIndex TView.expandoStartIndex
  32296. *
  32297. * Pure function instructions are given an offset from the binding root. Adding the offset to the
  32298. * binding root gives the first index where the bindings are stored. In component views, the binding
  32299. * root is the bindingStartIndex. In host bindings, the binding root is the expandoStartIndex +
  32300. * any directive instances + any hostVars in directives evaluated before it.
  32301. *
  32302. * See VIEW_DATA.md for more information about host binding resolution.
  32303. */
  32304. /**
  32305. * If the value hasn't been saved, calls the pure function to store and return the
  32306. * value. If it has been saved, returns the saved value.
  32307. *
  32308. * @param slotOffset the offset from binding root to the reserved slot
  32309. * @param pureFn Function that returns a value
  32310. * @param thisArg Optional calling context of pureFn
  32311. * @returns value
  32312. *
  32313. * @codeGenApi
  32314. */
  32315. function ɵɵpureFunction0(slotOffset, pureFn, thisArg) {
  32316. const bindingIndex = getBindingRoot() + slotOffset;
  32317. const lView = getLView();
  32318. return lView[bindingIndex] === NO_CHANGE
  32319. ? updateBinding(lView, bindingIndex, thisArg ? pureFn.call(thisArg) : pureFn())
  32320. : getBinding(lView, bindingIndex);
  32321. }
  32322. /**
  32323. * If the value of the provided exp has changed, calls the pure function to return
  32324. * an updated value. Or if the value has not changed, returns cached value.
  32325. *
  32326. * @param slotOffset the offset from binding root to the reserved slot
  32327. * @param pureFn Function that returns an updated value
  32328. * @param exp Updated expression value
  32329. * @param thisArg Optional calling context of pureFn
  32330. * @returns Updated or cached value
  32331. *
  32332. * @codeGenApi
  32333. */
  32334. function ɵɵpureFunction1(slotOffset, pureFn, exp, thisArg) {
  32335. return pureFunction1Internal(getLView(), getBindingRoot(), slotOffset, pureFn, exp, thisArg);
  32336. }
  32337. /**
  32338. * If the value of any provided exp has changed, calls the pure function to return
  32339. * an updated value. Or if no values have changed, returns cached value.
  32340. *
  32341. * @param slotOffset the offset from binding root to the reserved slot
  32342. * @param pureFn
  32343. * @param exp1
  32344. * @param exp2
  32345. * @param thisArg Optional calling context of pureFn
  32346. * @returns Updated or cached value
  32347. *
  32348. * @codeGenApi
  32349. */
  32350. function ɵɵpureFunction2(slotOffset, pureFn, exp1, exp2, thisArg) {
  32351. return pureFunction2Internal(getLView(), getBindingRoot(), slotOffset, pureFn, exp1, exp2, thisArg);
  32352. }
  32353. /**
  32354. * If the value of any provided exp has changed, calls the pure function to return
  32355. * an updated value. Or if no values have changed, returns cached value.
  32356. *
  32357. * @param slotOffset the offset from binding root to the reserved slot
  32358. * @param pureFn
  32359. * @param exp1
  32360. * @param exp2
  32361. * @param exp3
  32362. * @param thisArg Optional calling context of pureFn
  32363. * @returns Updated or cached value
  32364. *
  32365. * @codeGenApi
  32366. */
  32367. function ɵɵpureFunction3(slotOffset, pureFn, exp1, exp2, exp3, thisArg) {
  32368. return pureFunction3Internal(getLView(), getBindingRoot(), slotOffset, pureFn, exp1, exp2, exp3, thisArg);
  32369. }
  32370. /**
  32371. * If the value of any provided exp has changed, calls the pure function to return
  32372. * an updated value. Or if no values have changed, returns cached value.
  32373. *
  32374. * @param slotOffset the offset from binding root to the reserved slot
  32375. * @param pureFn
  32376. * @param exp1
  32377. * @param exp2
  32378. * @param exp3
  32379. * @param exp4
  32380. * @param thisArg Optional calling context of pureFn
  32381. * @returns Updated or cached value
  32382. *
  32383. * @codeGenApi
  32384. */
  32385. function ɵɵpureFunction4(slotOffset, pureFn, exp1, exp2, exp3, exp4, thisArg) {
  32386. return pureFunction4Internal(getLView(), getBindingRoot(), slotOffset, pureFn, exp1, exp2, exp3, exp4, thisArg);
  32387. }
  32388. /**
  32389. * If the value of any provided exp has changed, calls the pure function to return
  32390. * an updated value. Or if no values have changed, returns cached value.
  32391. *
  32392. * @param slotOffset the offset from binding root to the reserved slot
  32393. * @param pureFn
  32394. * @param exp1
  32395. * @param exp2
  32396. * @param exp3
  32397. * @param exp4
  32398. * @param exp5
  32399. * @param thisArg Optional calling context of pureFn
  32400. * @returns Updated or cached value
  32401. *
  32402. * @codeGenApi
  32403. */
  32404. function ɵɵpureFunction5(slotOffset, pureFn, exp1, exp2, exp3, exp4, exp5, thisArg) {
  32405. const bindingIndex = getBindingRoot() + slotOffset;
  32406. const lView = getLView();
  32407. const different = bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4);
  32408. return bindingUpdated(lView, bindingIndex + 4, exp5) || different
  32409. ? updateBinding(lView, bindingIndex + 5, thisArg
  32410. ? pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5)
  32411. : pureFn(exp1, exp2, exp3, exp4, exp5))
  32412. : getBinding(lView, bindingIndex + 5);
  32413. }
  32414. /**
  32415. * If the value of any provided exp has changed, calls the pure function to return
  32416. * an updated value. Or if no values have changed, returns cached value.
  32417. *
  32418. * @param slotOffset the offset from binding root to the reserved slot
  32419. * @param pureFn
  32420. * @param exp1
  32421. * @param exp2
  32422. * @param exp3
  32423. * @param exp4
  32424. * @param exp5
  32425. * @param exp6
  32426. * @param thisArg Optional calling context of pureFn
  32427. * @returns Updated or cached value
  32428. *
  32429. * @codeGenApi
  32430. */
  32431. function ɵɵpureFunction6(slotOffset, pureFn, exp1, exp2, exp3, exp4, exp5, exp6, thisArg) {
  32432. const bindingIndex = getBindingRoot() + slotOffset;
  32433. const lView = getLView();
  32434. const different = bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4);
  32435. return bindingUpdated2(lView, bindingIndex + 4, exp5, exp6) || different
  32436. ? updateBinding(lView, bindingIndex + 6, thisArg
  32437. ? pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5, exp6)
  32438. : pureFn(exp1, exp2, exp3, exp4, exp5, exp6))
  32439. : getBinding(lView, bindingIndex + 6);
  32440. }
  32441. /**
  32442. * If the value of any provided exp has changed, calls the pure function to return
  32443. * an updated value. Or if no values have changed, returns cached value.
  32444. *
  32445. * @param slotOffset the offset from binding root to the reserved slot
  32446. * @param pureFn
  32447. * @param exp1
  32448. * @param exp2
  32449. * @param exp3
  32450. * @param exp4
  32451. * @param exp5
  32452. * @param exp6
  32453. * @param exp7
  32454. * @param thisArg Optional calling context of pureFn
  32455. * @returns Updated or cached value
  32456. *
  32457. * @codeGenApi
  32458. */
  32459. function ɵɵpureFunction7(slotOffset, pureFn, exp1, exp2, exp3, exp4, exp5, exp6, exp7, thisArg) {
  32460. const bindingIndex = getBindingRoot() + slotOffset;
  32461. const lView = getLView();
  32462. let different = bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4);
  32463. return bindingUpdated3(lView, bindingIndex + 4, exp5, exp6, exp7) || different
  32464. ? updateBinding(lView, bindingIndex + 7, thisArg
  32465. ? pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5, exp6, exp7)
  32466. : pureFn(exp1, exp2, exp3, exp4, exp5, exp6, exp7))
  32467. : getBinding(lView, bindingIndex + 7);
  32468. }
  32469. /**
  32470. * If the value of any provided exp has changed, calls the pure function to return
  32471. * an updated value. Or if no values have changed, returns cached value.
  32472. *
  32473. * @param slotOffset the offset from binding root to the reserved slot
  32474. * @param pureFn
  32475. * @param exp1
  32476. * @param exp2
  32477. * @param exp3
  32478. * @param exp4
  32479. * @param exp5
  32480. * @param exp6
  32481. * @param exp7
  32482. * @param exp8
  32483. * @param thisArg Optional calling context of pureFn
  32484. * @returns Updated or cached value
  32485. *
  32486. * @codeGenApi
  32487. */
  32488. function ɵɵpureFunction8(slotOffset, pureFn, exp1, exp2, exp3, exp4, exp5, exp6, exp7, exp8, thisArg) {
  32489. const bindingIndex = getBindingRoot() + slotOffset;
  32490. const lView = getLView();
  32491. const different = bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4);
  32492. return bindingUpdated4(lView, bindingIndex + 4, exp5, exp6, exp7, exp8) || different
  32493. ? updateBinding(lView, bindingIndex + 8, thisArg
  32494. ? pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5, exp6, exp7, exp8)
  32495. : pureFn(exp1, exp2, exp3, exp4, exp5, exp6, exp7, exp8))
  32496. : getBinding(lView, bindingIndex + 8);
  32497. }
  32498. /**
  32499. * pureFunction instruction that can support any number of bindings.
  32500. *
  32501. * If the value of any provided exp has changed, calls the pure function to return
  32502. * an updated value. Or if no values have changed, returns cached value.
  32503. *
  32504. * @param slotOffset the offset from binding root to the reserved slot
  32505. * @param pureFn A pure function that takes binding values and builds an object or array
  32506. * containing those values.
  32507. * @param exps An array of binding values
  32508. * @param thisArg Optional calling context of pureFn
  32509. * @returns Updated or cached value
  32510. *
  32511. * @codeGenApi
  32512. */
  32513. function ɵɵpureFunctionV(slotOffset, pureFn, exps, thisArg) {
  32514. return pureFunctionVInternal(getLView(), getBindingRoot(), slotOffset, pureFn, exps, thisArg);
  32515. }
  32516. /**
  32517. * Results of a pure function invocation are stored in LView in a dedicated slot that is initialized
  32518. * to NO_CHANGE. In rare situations a pure pipe might throw an exception on the very first
  32519. * invocation and not produce any valid results. In this case LView would keep holding the NO_CHANGE
  32520. * value. The NO_CHANGE is not something that we can use in expressions / bindings thus we convert
  32521. * it to `undefined`.
  32522. */
  32523. function getPureFunctionReturnValue(lView, returnValueIndex) {
  32524. ngDevMode && assertIndexInRange(lView, returnValueIndex);
  32525. const lastReturnValue = lView[returnValueIndex];
  32526. return lastReturnValue === NO_CHANGE ? undefined : lastReturnValue;
  32527. }
  32528. /**
  32529. * If the value of the provided exp has changed, calls the pure function to return
  32530. * an updated value. Or if the value has not changed, returns cached value.
  32531. *
  32532. * @param lView LView in which the function is being executed.
  32533. * @param bindingRoot Binding root index.
  32534. * @param slotOffset the offset from binding root to the reserved slot
  32535. * @param pureFn Function that returns an updated value
  32536. * @param exp Updated expression value
  32537. * @param thisArg Optional calling context of pureFn
  32538. * @returns Updated or cached value
  32539. */
  32540. function pureFunction1Internal(lView, bindingRoot, slotOffset, pureFn, exp, thisArg) {
  32541. const bindingIndex = bindingRoot + slotOffset;
  32542. return bindingUpdated(lView, bindingIndex, exp)
  32543. ? updateBinding(lView, bindingIndex + 1, thisArg ? pureFn.call(thisArg, exp) : pureFn(exp))
  32544. : getPureFunctionReturnValue(lView, bindingIndex + 1);
  32545. }
  32546. /**
  32547. * If the value of any provided exp has changed, calls the pure function to return
  32548. * an updated value. Or if no values have changed, returns cached value.
  32549. *
  32550. * @param lView LView in which the function is being executed.
  32551. * @param bindingRoot Binding root index.
  32552. * @param slotOffset the offset from binding root to the reserved slot
  32553. * @param pureFn
  32554. * @param exp1
  32555. * @param exp2
  32556. * @param thisArg Optional calling context of pureFn
  32557. * @returns Updated or cached value
  32558. */
  32559. function pureFunction2Internal(lView, bindingRoot, slotOffset, pureFn, exp1, exp2, thisArg) {
  32560. const bindingIndex = bindingRoot + slotOffset;
  32561. return bindingUpdated2(lView, bindingIndex, exp1, exp2)
  32562. ? updateBinding(lView, bindingIndex + 2, thisArg ? pureFn.call(thisArg, exp1, exp2) : pureFn(exp1, exp2))
  32563. : getPureFunctionReturnValue(lView, bindingIndex + 2);
  32564. }
  32565. /**
  32566. * If the value of any provided exp has changed, calls the pure function to return
  32567. * an updated value. Or if no values have changed, returns cached value.
  32568. *
  32569. * @param lView LView in which the function is being executed.
  32570. * @param bindingRoot Binding root index.
  32571. * @param slotOffset the offset from binding root to the reserved slot
  32572. * @param pureFn
  32573. * @param exp1
  32574. * @param exp2
  32575. * @param exp3
  32576. * @param thisArg Optional calling context of pureFn
  32577. * @returns Updated or cached value
  32578. */
  32579. function pureFunction3Internal(lView, bindingRoot, slotOffset, pureFn, exp1, exp2, exp3, thisArg) {
  32580. const bindingIndex = bindingRoot + slotOffset;
  32581. return bindingUpdated3(lView, bindingIndex, exp1, exp2, exp3)
  32582. ? updateBinding(lView, bindingIndex + 3, thisArg ? pureFn.call(thisArg, exp1, exp2, exp3) : pureFn(exp1, exp2, exp3))
  32583. : getPureFunctionReturnValue(lView, bindingIndex + 3);
  32584. }
  32585. /**
  32586. * If the value of any provided exp has changed, calls the pure function to return
  32587. * an updated value. Or if no values have changed, returns cached value.
  32588. *
  32589. * @param lView LView in which the function is being executed.
  32590. * @param bindingRoot Binding root index.
  32591. * @param slotOffset the offset from binding root to the reserved slot
  32592. * @param pureFn
  32593. * @param exp1
  32594. * @param exp2
  32595. * @param exp3
  32596. * @param exp4
  32597. * @param thisArg Optional calling context of pureFn
  32598. * @returns Updated or cached value
  32599. *
  32600. */
  32601. function pureFunction4Internal(lView, bindingRoot, slotOffset, pureFn, exp1, exp2, exp3, exp4, thisArg) {
  32602. const bindingIndex = bindingRoot + slotOffset;
  32603. return bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4)
  32604. ? updateBinding(lView, bindingIndex + 4, thisArg ? pureFn.call(thisArg, exp1, exp2, exp3, exp4) : pureFn(exp1, exp2, exp3, exp4))
  32605. : getPureFunctionReturnValue(lView, bindingIndex + 4);
  32606. }
  32607. /**
  32608. * pureFunction instruction that can support any number of bindings.
  32609. *
  32610. * If the value of any provided exp has changed, calls the pure function to return
  32611. * an updated value. Or if no values have changed, returns cached value.
  32612. *
  32613. * @param lView LView in which the function is being executed.
  32614. * @param bindingRoot Binding root index.
  32615. * @param slotOffset the offset from binding root to the reserved slot
  32616. * @param pureFn A pure function that takes binding values and builds an object or array
  32617. * containing those values.
  32618. * @param exps An array of binding values
  32619. * @param thisArg Optional calling context of pureFn
  32620. * @returns Updated or cached value
  32621. */
  32622. function pureFunctionVInternal(lView, bindingRoot, slotOffset, pureFn, exps, thisArg) {
  32623. let bindingIndex = bindingRoot + slotOffset;
  32624. let different = false;
  32625. for (let i = 0; i < exps.length; i++) {
  32626. bindingUpdated(lView, bindingIndex++, exps[i]) && (different = true);
  32627. }
  32628. return different
  32629. ? updateBinding(lView, bindingIndex, pureFn.apply(thisArg, exps))
  32630. : getPureFunctionReturnValue(lView, bindingIndex);
  32631. }
  32632. /**
  32633. * Create a pipe.
  32634. *
  32635. * @param index Pipe index where the pipe will be stored.
  32636. * @param pipeName The name of the pipe
  32637. * @returns T the instance of the pipe.
  32638. *
  32639. * @codeGenApi
  32640. */
  32641. function ɵɵpipe(index, pipeName) {
  32642. const tView = getTView();
  32643. let pipeDef;
  32644. const adjustedIndex = index + HEADER_OFFSET;
  32645. if (tView.firstCreatePass) {
  32646. // The `getPipeDef` throws if a pipe with a given name is not found
  32647. // (so we use non-null assertion below).
  32648. pipeDef = getPipeDef(pipeName, tView.pipeRegistry);
  32649. tView.data[adjustedIndex] = pipeDef;
  32650. if (pipeDef.onDestroy) {
  32651. (tView.destroyHooks ??= []).push(adjustedIndex, pipeDef.onDestroy);
  32652. }
  32653. }
  32654. else {
  32655. pipeDef = tView.data[adjustedIndex];
  32656. }
  32657. const pipeFactory = pipeDef.factory || (pipeDef.factory = getFactoryDef(pipeDef.type, true));
  32658. let previousInjectorProfilerContext;
  32659. if (ngDevMode) {
  32660. previousInjectorProfilerContext = setInjectorProfilerContext({
  32661. injector: new NodeInjector(getCurrentTNode(), getLView()),
  32662. token: pipeDef.type,
  32663. });
  32664. }
  32665. const previousInjectImplementation = setInjectImplementation(ɵɵdirectiveInject);
  32666. try {
  32667. // DI for pipes is supposed to behave like directives when placed on a component
  32668. // host node, which means that we have to disable access to `viewProviders`.
  32669. const previousIncludeViewProviders = setIncludeViewProviders(false);
  32670. const pipeInstance = pipeFactory();
  32671. setIncludeViewProviders(previousIncludeViewProviders);
  32672. store(tView, getLView(), adjustedIndex, pipeInstance);
  32673. return pipeInstance;
  32674. }
  32675. finally {
  32676. // we have to restore the injector implementation in finally, just in case the creation of the
  32677. // pipe throws an error.
  32678. setInjectImplementation(previousInjectImplementation);
  32679. ngDevMode && setInjectorProfilerContext(previousInjectorProfilerContext);
  32680. }
  32681. }
  32682. /**
  32683. * Searches the pipe registry for a pipe with the given name. If one is found,
  32684. * returns the pipe. Otherwise, an error is thrown because the pipe cannot be resolved.
  32685. *
  32686. * @param name Name of pipe to resolve
  32687. * @param registry Full list of available pipes
  32688. * @returns Matching PipeDef
  32689. */
  32690. function getPipeDef(name, registry) {
  32691. if (registry) {
  32692. if (ngDevMode) {
  32693. const pipes = registry.filter((pipe) => pipe.name === name);
  32694. // TODO: Throw an error in the next major
  32695. if (pipes.length > 1) {
  32696. console.warn(formatRuntimeError(313 /* RuntimeErrorCode.MULTIPLE_MATCHING_PIPES */, getMultipleMatchingPipesMessage(name)));
  32697. }
  32698. }
  32699. for (let i = registry.length - 1; i >= 0; i--) {
  32700. const pipeDef = registry[i];
  32701. if (name === pipeDef.name) {
  32702. return pipeDef;
  32703. }
  32704. }
  32705. }
  32706. if (ngDevMode) {
  32707. throw new RuntimeError(-302 /* RuntimeErrorCode.PIPE_NOT_FOUND */, getPipeNotFoundErrorMessage(name));
  32708. }
  32709. return;
  32710. }
  32711. /**
  32712. * Generates a helpful error message for the user when multiple pipes match the name.
  32713. *
  32714. * @param name Name of the pipe
  32715. * @returns The error message
  32716. */
  32717. function getMultipleMatchingPipesMessage(name) {
  32718. const lView = getLView();
  32719. const declarationLView = lView[DECLARATION_COMPONENT_VIEW];
  32720. const context = declarationLView[CONTEXT];
  32721. const hostIsStandalone = isHostComponentStandalone(lView);
  32722. const componentInfoMessage = context ? ` in the '${context.constructor.name}' component` : '';
  32723. const verifyMessage = `check ${hostIsStandalone ? "'@Component.imports' of this component" : 'the imports of this module'}`;
  32724. const errorMessage = `Multiple pipes match the name \`${name}\`${componentInfoMessage}. ${verifyMessage}`;
  32725. return errorMessage;
  32726. }
  32727. /**
  32728. * Generates a helpful error message for the user when a pipe is not found.
  32729. *
  32730. * @param name Name of the missing pipe
  32731. * @returns The error message
  32732. */
  32733. function getPipeNotFoundErrorMessage(name) {
  32734. const lView = getLView();
  32735. const declarationLView = lView[DECLARATION_COMPONENT_VIEW];
  32736. const context = declarationLView[CONTEXT];
  32737. const hostIsStandalone = isHostComponentStandalone(lView);
  32738. const componentInfoMessage = context ? ` in the '${context.constructor.name}' component` : '';
  32739. const verifyMessage = `Verify that it is ${hostIsStandalone
  32740. ? "included in the '@Component.imports' of this component"
  32741. : 'declared or imported in this module'}`;
  32742. const errorMessage = `The pipe '${name}' could not be found${componentInfoMessage}. ${verifyMessage}`;
  32743. return errorMessage;
  32744. }
  32745. /**
  32746. * Invokes a pipe with 1 arguments.
  32747. *
  32748. * This instruction acts as a guard to {@link PipeTransform#transform} invoking
  32749. * the pipe only when an input to the pipe changes.
  32750. *
  32751. * @param index Pipe index where the pipe was stored on creation.
  32752. * @param offset the binding offset
  32753. * @param v1 1st argument to {@link PipeTransform#transform}.
  32754. *
  32755. * @codeGenApi
  32756. */
  32757. function ɵɵpipeBind1(index, offset, v1) {
  32758. const adjustedIndex = index + HEADER_OFFSET;
  32759. const lView = getLView();
  32760. const pipeInstance = load(lView, adjustedIndex);
  32761. return isPure(lView, adjustedIndex)
  32762. ? pureFunction1Internal(lView, getBindingRoot(), offset, pipeInstance.transform, v1, pipeInstance)
  32763. : pipeInstance.transform(v1);
  32764. }
  32765. /**
  32766. * Invokes a pipe with 2 arguments.
  32767. *
  32768. * This instruction acts as a guard to {@link PipeTransform#transform} invoking
  32769. * the pipe only when an input to the pipe changes.
  32770. *
  32771. * @param index Pipe index where the pipe was stored on creation.
  32772. * @param slotOffset the offset in the reserved slot space
  32773. * @param v1 1st argument to {@link PipeTransform#transform}.
  32774. * @param v2 2nd argument to {@link PipeTransform#transform}.
  32775. *
  32776. * @codeGenApi
  32777. */
  32778. function ɵɵpipeBind2(index, slotOffset, v1, v2) {
  32779. const adjustedIndex = index + HEADER_OFFSET;
  32780. const lView = getLView();
  32781. const pipeInstance = load(lView, adjustedIndex);
  32782. return isPure(lView, adjustedIndex)
  32783. ? pureFunction2Internal(lView, getBindingRoot(), slotOffset, pipeInstance.transform, v1, v2, pipeInstance)
  32784. : pipeInstance.transform(v1, v2);
  32785. }
  32786. /**
  32787. * Invokes a pipe with 3 arguments.
  32788. *
  32789. * This instruction acts as a guard to {@link PipeTransform#transform} invoking
  32790. * the pipe only when an input to the pipe changes.
  32791. *
  32792. * @param index Pipe index where the pipe was stored on creation.
  32793. * @param slotOffset the offset in the reserved slot space
  32794. * @param v1 1st argument to {@link PipeTransform#transform}.
  32795. * @param v2 2nd argument to {@link PipeTransform#transform}.
  32796. * @param v3 4rd argument to {@link PipeTransform#transform}.
  32797. *
  32798. * @codeGenApi
  32799. */
  32800. function ɵɵpipeBind3(index, slotOffset, v1, v2, v3) {
  32801. const adjustedIndex = index + HEADER_OFFSET;
  32802. const lView = getLView();
  32803. const pipeInstance = load(lView, adjustedIndex);
  32804. return isPure(lView, adjustedIndex)
  32805. ? pureFunction3Internal(lView, getBindingRoot(), slotOffset, pipeInstance.transform, v1, v2, v3, pipeInstance)
  32806. : pipeInstance.transform(v1, v2, v3);
  32807. }
  32808. /**
  32809. * Invokes a pipe with 4 arguments.
  32810. *
  32811. * This instruction acts as a guard to {@link PipeTransform#transform} invoking
  32812. * the pipe only when an input to the pipe changes.
  32813. *
  32814. * @param index Pipe index where the pipe was stored on creation.
  32815. * @param slotOffset the offset in the reserved slot space
  32816. * @param v1 1st argument to {@link PipeTransform#transform}.
  32817. * @param v2 2nd argument to {@link PipeTransform#transform}.
  32818. * @param v3 3rd argument to {@link PipeTransform#transform}.
  32819. * @param v4 4th argument to {@link PipeTransform#transform}.
  32820. *
  32821. * @codeGenApi
  32822. */
  32823. function ɵɵpipeBind4(index, slotOffset, v1, v2, v3, v4) {
  32824. const adjustedIndex = index + HEADER_OFFSET;
  32825. const lView = getLView();
  32826. const pipeInstance = load(lView, adjustedIndex);
  32827. return isPure(lView, adjustedIndex)
  32828. ? pureFunction4Internal(lView, getBindingRoot(), slotOffset, pipeInstance.transform, v1, v2, v3, v4, pipeInstance)
  32829. : pipeInstance.transform(v1, v2, v3, v4);
  32830. }
  32831. /**
  32832. * Invokes a pipe with variable number of arguments.
  32833. *
  32834. * This instruction acts as a guard to {@link PipeTransform#transform} invoking
  32835. * the pipe only when an input to the pipe changes.
  32836. *
  32837. * @param index Pipe index where the pipe was stored on creation.
  32838. * @param slotOffset the offset in the reserved slot space
  32839. * @param values Array of arguments to pass to {@link PipeTransform#transform} method.
  32840. *
  32841. * @codeGenApi
  32842. */
  32843. function ɵɵpipeBindV(index, slotOffset, values) {
  32844. const adjustedIndex = index + HEADER_OFFSET;
  32845. const lView = getLView();
  32846. const pipeInstance = load(lView, adjustedIndex);
  32847. return isPure(lView, adjustedIndex)
  32848. ? pureFunctionVInternal(lView, getBindingRoot(), slotOffset, pipeInstance.transform, values, pipeInstance)
  32849. : pipeInstance.transform.apply(pipeInstance, values);
  32850. }
  32851. function isPure(lView, index) {
  32852. return lView[TVIEW].data[index].pure;
  32853. }
  32854. /**
  32855. * Retrieves `TemplateRef` instance from `Injector` when a local reference is placed on the
  32856. * `<ng-template>` element.
  32857. *
  32858. * @codeGenApi
  32859. */
  32860. function ɵɵtemplateRefExtractor(tNode, lView) {
  32861. return createTemplateRef(tNode, lView);
  32862. }
  32863. function ɵɵgetComponentDepsFactory(type, rawImports) {
  32864. return () => {
  32865. try {
  32866. return depsTracker.getComponentDependencies(type, rawImports).dependencies;
  32867. }
  32868. catch (e) {
  32869. console.error(`Computing dependencies in local compilation mode for the component "${type.name}" failed with the exception:`, e);
  32870. throw e;
  32871. }
  32872. };
  32873. }
  32874. /**
  32875. * Sets the debug info for an Angular class.
  32876. *
  32877. * This runtime is guarded by ngDevMode flag.
  32878. */
  32879. function ɵsetClassDebugInfo(type, debugInfo) {
  32880. const def = getComponentDef(type);
  32881. if (def !== null) {
  32882. def.debugInfo = debugInfo;
  32883. }
  32884. }
  32885. /*!
  32886. * @license
  32887. * Copyright Google LLC All Rights Reserved.
  32888. *
  32889. * Use of this source code is governed by an MIT-style license that can be
  32890. * found in the LICENSE file at https://angular.dev/license
  32891. */
  32892. /**
  32893. * Replaces the metadata of a component type and re-renders all live instances of the component.
  32894. * @param type Class whose metadata will be replaced.
  32895. * @param applyMetadata Callback that will apply a new set of metadata on the `type` when invoked.
  32896. * @param environment Syntehtic namespace imports that need to be passed along to the callback.
  32897. * @param locals Local symbols from the source location that have to be exposed to the callback.
  32898. * @param importMeta `import.meta` from the call site of the replacement function. Optional since
  32899. * it isn't used internally.
  32900. * @param id ID to the class being replaced. **Not** the same as the component definition ID.
  32901. * Optional since the ID might not be available internally.
  32902. * @codeGenApi
  32903. */
  32904. function ɵɵreplaceMetadata(type, applyMetadata, namespaces, locals, importMeta = null, id = null) {
  32905. ngDevMode && assertComponentDef(type);
  32906. const currentDef = getComponentDef(type);
  32907. // The reason `applyMetadata` is a callback that is invoked (almost) immediately is because
  32908. // the compiler usually produces more code than just the component definition, e.g. there
  32909. // can be functions for embedded views, the variables for the constant pool and `setClassMetadata`
  32910. // calls. The callback allows us to keep them isolate from the rest of the app and to invoke
  32911. // them at the right time.
  32912. applyMetadata.apply(null, [type, namespaces, ...locals]);
  32913. const { newDef, oldDef } = mergeWithExistingDefinition(currentDef, getComponentDef(type));
  32914. // TODO(crisbeto): the `applyMetadata` call above will replace the definition on the type.
  32915. // Ideally we should adjust the compiler output so the metadata is returned, however that'll
  32916. // require some internal changes. We re-add the metadata here manually.
  32917. type[NG_COMP_DEF] = newDef;
  32918. // If a `tView` hasn't been created yet, it means that this component hasn't been instantianted
  32919. // before. In this case there's nothing left for us to do aside from patching it in.
  32920. if (oldDef.tView) {
  32921. const trackedViews = getTrackedLViews().values();
  32922. for (const root of trackedViews) {
  32923. // Note: we have the additional check, because `IsRoot` can also indicate
  32924. // a component created through something like `createComponent`.
  32925. if (isRootView(root) && root[PARENT] === null) {
  32926. recreateMatchingLViews(importMeta, id, newDef, oldDef, root);
  32927. }
  32928. }
  32929. }
  32930. }
  32931. /**
  32932. * Merges two component definitions while preseving the original one in place.
  32933. * @param currentDef Definition that should receive the new metadata.
  32934. * @param newDef Source of the new metadata.
  32935. */
  32936. function mergeWithExistingDefinition(currentDef, newDef) {
  32937. // Clone the current definition since we reference its original data further
  32938. // down in the replacement process (e.g. when destroying the renderer).
  32939. const clone = { ...currentDef };
  32940. // Assign the new metadata in place while preserving the object literal. It's important to
  32941. // Keep the object in place, because there can be references to it, for example in the
  32942. // `directiveDefs` of another definition.
  32943. const replacement = Object.assign(currentDef, newDef, {
  32944. // We need to keep the existing directive and pipe defs, because they can get patched on
  32945. // by a call to `setComponentScope` from a module file. That call won't make it into the
  32946. // HMR replacement function, because it lives in an entirely different file.
  32947. directiveDefs: clone.directiveDefs,
  32948. pipeDefs: clone.pipeDefs,
  32949. // Preserve the old `setInput` function, because it has some state.
  32950. // This is fine, because the component instance is preserved as well.
  32951. setInput: clone.setInput,
  32952. // Externally this is redundant since we redeclare the definition using the original type.
  32953. // Internally we may receive a definition with an alternate, but identical, type so we have
  32954. // to ensure that the original one is preserved.
  32955. type: clone.type,
  32956. });
  32957. ngDevMode && assertEqual(replacement, currentDef, 'Expected definition to be merged in place');
  32958. return { newDef: replacement, oldDef: clone };
  32959. }
  32960. /**
  32961. * Finds all LViews matching a specific component definition and recreates them.
  32962. * @param importMeta `import.meta` information.
  32963. * @param id HMR ID of the component.
  32964. * @param oldDef Component definition to search for.
  32965. * @param rootLView View from which to start the search.
  32966. */
  32967. function recreateMatchingLViews(importMeta, id, newDef, oldDef, rootLView) {
  32968. ngDevMode &&
  32969. assertDefined(oldDef.tView, 'Expected a component definition that has been instantiated at least once');
  32970. const tView = rootLView[TVIEW];
  32971. // Use `tView` to match the LView since `instanceof` can
  32972. // produce false positives when using inheritance.
  32973. if (tView === oldDef.tView) {
  32974. ngDevMode && assertComponentDef(oldDef.type);
  32975. recreateLView(importMeta, id, newDef, oldDef, rootLView);
  32976. return;
  32977. }
  32978. for (let i = HEADER_OFFSET; i < tView.bindingStartIndex; i++) {
  32979. const current = rootLView[i];
  32980. if (isLContainer(current)) {
  32981. // The host can be an LView if a component is injecting `ViewContainerRef`.
  32982. if (isLView(current[HOST])) {
  32983. recreateMatchingLViews(importMeta, id, newDef, oldDef, current[HOST]);
  32984. }
  32985. for (let j = CONTAINER_HEADER_OFFSET; j < current.length; j++) {
  32986. recreateMatchingLViews(importMeta, id, newDef, oldDef, current[j]);
  32987. }
  32988. }
  32989. else if (isLView(current)) {
  32990. recreateMatchingLViews(importMeta, id, newDef, oldDef, current);
  32991. }
  32992. }
  32993. }
  32994. /**
  32995. * Removes any cached renderers from the factory for the provided type.
  32996. * This is currently used by the HMR logic to ensure Renderers are kept
  32997. * synchronized with any definition metadata updates.
  32998. * @param factory A RendererFactory2 instance.
  32999. * @param def A ComponentDef instance.
  33000. */
  33001. function clearRendererCache(factory, def) {
  33002. // Cast to read a private field.
  33003. // NOTE: This must be kept synchronized with the renderer factory implementation in
  33004. // platform-browser and platform-browser/animations.
  33005. factory.componentReplaced?.(def.id);
  33006. }
  33007. /**
  33008. * Recreates an LView in-place from a new component definition.
  33009. * @param importMeta `import.meta` information.
  33010. * @param id HMR ID for the component.
  33011. * @param newDef Definition from which to recreate the view.
  33012. * @param oldDef Previous component definition being swapped out.
  33013. * @param lView View to be recreated.
  33014. */
  33015. function recreateLView(importMeta, id, newDef, oldDef, lView) {
  33016. const instance = lView[CONTEXT];
  33017. let host = lView[HOST];
  33018. // In theory the parent can also be an LContainer, but it appears like that's
  33019. // only the case for embedded views which we won't be replacing here.
  33020. const parentLView = lView[PARENT];
  33021. ngDevMode && assertLView(parentLView);
  33022. const tNode = lView[T_HOST];
  33023. ngDevMode && assertTNodeType(tNode, 2 /* TNodeType.Element */);
  33024. ngDevMode && assertNotEqual(newDef, oldDef, 'Expected different component definition');
  33025. const zone = lView[INJECTOR].get(NgZone, null);
  33026. const recreate = () => {
  33027. // If we're recreating a component with shadow DOM encapsulation, it will have attached a
  33028. // shadow root. The browser will throw if we attempt to attach another one and there's no way
  33029. // to detach it. Our only option is to make a clone only of the root node, replace the node
  33030. // with the clone and use it for the newly-created LView.
  33031. if (oldDef.encapsulation === ViewEncapsulation.ShadowDom) {
  33032. const newHost = host.cloneNode(false);
  33033. host.replaceWith(newHost);
  33034. host = newHost;
  33035. }
  33036. // Recreate the TView since the template might've changed.
  33037. const newTView = getOrCreateComponentTView(newDef);
  33038. // Create a new LView from the new TView, but reusing the existing TNode and DOM node.
  33039. const newLView = createLView(parentLView, newTView, instance, getInitialLViewFlagsFromDef(newDef), host, tNode, null, null, // The renderer will be created a bit further down once the old one is destroyed.
  33040. null, null, null);
  33041. // Detach the LView from its current place in the tree so we don't
  33042. // start traversing any siblings and modifying their structure.
  33043. replaceLViewInTree(parentLView, lView, newLView, tNode.index);
  33044. // Destroy the detached LView.
  33045. destroyLView(lView[TVIEW], lView);
  33046. // Always force the creation of a new renderer to ensure state captured during construction
  33047. // stays consistent with the new component definition by clearing any old ached factories.
  33048. const rendererFactory = lView[ENVIRONMENT].rendererFactory;
  33049. clearRendererCache(rendererFactory, oldDef);
  33050. // Patch a brand-new renderer onto the new view only after the old
  33051. // view is destroyed so that the runtime doesn't try to reuse it.
  33052. newLView[RENDERER] = rendererFactory.createRenderer(host, newDef);
  33053. // Remove the nodes associated with the destroyed LView. This removes the
  33054. // descendants, but not the host which we want to stay in place.
  33055. removeViewFromDOM(lView[TVIEW], lView);
  33056. // Reset the content projection state of the TNode before the first render.
  33057. // Note that this has to happen after the LView has been destroyed or we
  33058. // risk some projected nodes not being removed correctly.
  33059. resetProjectionState(tNode);
  33060. // Creation pass for the new view.
  33061. renderView(newTView, newLView, instance);
  33062. // Update pass for the new view.
  33063. refreshView(newTView, newLView, newTView.template, instance);
  33064. };
  33065. // The callback isn't guaranteed to be inside the Zone so we need to bring it in ourselves.
  33066. if (zone === null) {
  33067. executeWithInvalidateFallback(importMeta, id, recreate);
  33068. }
  33069. else {
  33070. zone.run(() => executeWithInvalidateFallback(importMeta, id, recreate));
  33071. }
  33072. }
  33073. /**
  33074. * Runs an HMR-related function and falls back to
  33075. * invalidating the HMR data if it throws an error.
  33076. */
  33077. function executeWithInvalidateFallback(importMeta, id, callback) {
  33078. try {
  33079. callback();
  33080. }
  33081. catch (e) {
  33082. const error = e;
  33083. // If we have all the necessary information and APIs to send off the invalidation
  33084. // request, send it before rethrowing so the dev server can decide what to do.
  33085. if (id !== null && error.message) {
  33086. const toLog = error.message + (error.stack ? '\n' + error.stack : '');
  33087. importMeta?.hot?.send?.('angular:invalidate', { id, message: toLog, error: true });
  33088. }
  33089. // Throw the error in case the page doesn't get refreshed.
  33090. throw e;
  33091. }
  33092. }
  33093. /**
  33094. * Replaces one LView in the tree with another one.
  33095. * @param parentLView Parent of the LView being replaced.
  33096. * @param oldLView LView being replaced.
  33097. * @param newLView Replacement LView to be inserted.
  33098. * @param index Index at which the LView should be inserted.
  33099. */
  33100. function replaceLViewInTree(parentLView, oldLView, newLView, index) {
  33101. // Update the sibling whose `NEXT` pointer refers to the old view.
  33102. for (let i = HEADER_OFFSET; i < parentLView[TVIEW].bindingStartIndex; i++) {
  33103. const current = parentLView[i];
  33104. if ((isLView(current) || isLContainer(current)) && current[NEXT] === oldLView) {
  33105. current[NEXT] = newLView;
  33106. break;
  33107. }
  33108. }
  33109. // Set the new view as the head, if the old view was first.
  33110. if (parentLView[CHILD_HEAD] === oldLView) {
  33111. parentLView[CHILD_HEAD] = newLView;
  33112. }
  33113. // Set the new view as the tail, if the old view was last.
  33114. if (parentLView[CHILD_TAIL] === oldLView) {
  33115. parentLView[CHILD_TAIL] = newLView;
  33116. }
  33117. // Update the `NEXT` pointer to the same as the old view.
  33118. newLView[NEXT] = oldLView[NEXT];
  33119. // Clear out the `NEXT` of the old view.
  33120. oldLView[NEXT] = null;
  33121. // Insert the new LView at the correct index.
  33122. parentLView[index] = newLView;
  33123. }
  33124. /**
  33125. * Child nodes mutate the `projection` state of their parent node as they're being projected.
  33126. * This function resets the `project` back to its initial state.
  33127. * @param tNode
  33128. */
  33129. function resetProjectionState(tNode) {
  33130. // The `projection` is mutated by child nodes as they're being projected. We need to
  33131. // reset it to the initial state so projection works after the template is swapped out.
  33132. if (tNode.projection !== null) {
  33133. for (const current of tNode.projection) {
  33134. if (isTNodeShape(current)) {
  33135. // Reset `projectionNext` since it can affect the traversal order during projection.
  33136. current.projectionNext = null;
  33137. current.flags &= -3 /* TNodeFlags.isProjected */;
  33138. }
  33139. }
  33140. tNode.projection = null;
  33141. }
  33142. }
  33143. /**
  33144. * A mapping of the @angular/core API surface used in generated expressions to the actual symbols.
  33145. *
  33146. * This should be kept up to date with the public exports of @angular/core.
  33147. */
  33148. const angularCoreEnv = (() => ({
  33149. 'ɵɵattribute': ɵɵattribute,
  33150. 'ɵɵattributeInterpolate1': ɵɵattributeInterpolate1,
  33151. 'ɵɵattributeInterpolate2': ɵɵattributeInterpolate2,
  33152. 'ɵɵattributeInterpolate3': ɵɵattributeInterpolate3,
  33153. 'ɵɵattributeInterpolate4': ɵɵattributeInterpolate4,
  33154. 'ɵɵattributeInterpolate5': ɵɵattributeInterpolate5,
  33155. 'ɵɵattributeInterpolate6': ɵɵattributeInterpolate6,
  33156. 'ɵɵattributeInterpolate7': ɵɵattributeInterpolate7,
  33157. 'ɵɵattributeInterpolate8': ɵɵattributeInterpolate8,
  33158. 'ɵɵattributeInterpolateV': ɵɵattributeInterpolateV,
  33159. 'ɵɵdefineComponent': ɵɵdefineComponent,
  33160. 'ɵɵdefineDirective': ɵɵdefineDirective,
  33161. 'ɵɵdefineInjectable': ɵɵdefineInjectable,
  33162. 'ɵɵdefineInjector': ɵɵdefineInjector,
  33163. 'ɵɵdefineNgModule': ɵɵdefineNgModule,
  33164. 'ɵɵdefinePipe': ɵɵdefinePipe,
  33165. 'ɵɵdirectiveInject': ɵɵdirectiveInject,
  33166. 'ɵɵgetInheritedFactory': ɵɵgetInheritedFactory,
  33167. 'ɵɵinject': ɵɵinject,
  33168. 'ɵɵinjectAttribute': ɵɵinjectAttribute,
  33169. 'ɵɵinvalidFactory': ɵɵinvalidFactory,
  33170. 'ɵɵinvalidFactoryDep': ɵɵinvalidFactoryDep,
  33171. 'ɵɵtemplateRefExtractor': ɵɵtemplateRefExtractor,
  33172. 'ɵɵresetView': ɵɵresetView,
  33173. 'ɵɵHostDirectivesFeature': ɵɵHostDirectivesFeature,
  33174. 'ɵɵNgOnChangesFeature': ɵɵNgOnChangesFeature,
  33175. 'ɵɵProvidersFeature': ɵɵProvidersFeature,
  33176. 'ɵɵCopyDefinitionFeature': ɵɵCopyDefinitionFeature,
  33177. 'ɵɵInheritDefinitionFeature': ɵɵInheritDefinitionFeature,
  33178. 'ɵɵExternalStylesFeature': ɵɵExternalStylesFeature,
  33179. 'ɵɵnextContext': ɵɵnextContext,
  33180. 'ɵɵnamespaceHTML': ɵɵnamespaceHTML,
  33181. 'ɵɵnamespaceMathML': ɵɵnamespaceMathML,
  33182. 'ɵɵnamespaceSVG': ɵɵnamespaceSVG,
  33183. 'ɵɵenableBindings': ɵɵenableBindings,
  33184. 'ɵɵdisableBindings': ɵɵdisableBindings,
  33185. 'ɵɵelementStart': ɵɵelementStart,
  33186. 'ɵɵelementEnd': ɵɵelementEnd,
  33187. 'ɵɵelement': ɵɵelement,
  33188. 'ɵɵelementContainerStart': ɵɵelementContainerStart,
  33189. 'ɵɵelementContainerEnd': ɵɵelementContainerEnd,
  33190. 'ɵɵelementContainer': ɵɵelementContainer,
  33191. 'ɵɵpureFunction0': ɵɵpureFunction0,
  33192. 'ɵɵpureFunction1': ɵɵpureFunction1,
  33193. 'ɵɵpureFunction2': ɵɵpureFunction2,
  33194. 'ɵɵpureFunction3': ɵɵpureFunction3,
  33195. 'ɵɵpureFunction4': ɵɵpureFunction4,
  33196. 'ɵɵpureFunction5': ɵɵpureFunction5,
  33197. 'ɵɵpureFunction6': ɵɵpureFunction6,
  33198. 'ɵɵpureFunction7': ɵɵpureFunction7,
  33199. 'ɵɵpureFunction8': ɵɵpureFunction8,
  33200. 'ɵɵpureFunctionV': ɵɵpureFunctionV,
  33201. 'ɵɵgetCurrentView': ɵɵgetCurrentView,
  33202. 'ɵɵrestoreView': ɵɵrestoreView,
  33203. 'ɵɵlistener': ɵɵlistener,
  33204. 'ɵɵprojection': ɵɵprojection,
  33205. 'ɵɵsyntheticHostProperty': ɵɵsyntheticHostProperty,
  33206. 'ɵɵsyntheticHostListener': ɵɵsyntheticHostListener,
  33207. 'ɵɵpipeBind1': ɵɵpipeBind1,
  33208. 'ɵɵpipeBind2': ɵɵpipeBind2,
  33209. 'ɵɵpipeBind3': ɵɵpipeBind3,
  33210. 'ɵɵpipeBind4': ɵɵpipeBind4,
  33211. 'ɵɵpipeBindV': ɵɵpipeBindV,
  33212. 'ɵɵprojectionDef': ɵɵprojectionDef,
  33213. 'ɵɵhostProperty': ɵɵhostProperty,
  33214. 'ɵɵproperty': ɵɵproperty,
  33215. 'ɵɵpropertyInterpolate': ɵɵpropertyInterpolate,
  33216. 'ɵɵpropertyInterpolate1': ɵɵpropertyInterpolate1,
  33217. 'ɵɵpropertyInterpolate2': ɵɵpropertyInterpolate2,
  33218. 'ɵɵpropertyInterpolate3': ɵɵpropertyInterpolate3,
  33219. 'ɵɵpropertyInterpolate4': ɵɵpropertyInterpolate4,
  33220. 'ɵɵpropertyInterpolate5': ɵɵpropertyInterpolate5,
  33221. 'ɵɵpropertyInterpolate6': ɵɵpropertyInterpolate6,
  33222. 'ɵɵpropertyInterpolate7': ɵɵpropertyInterpolate7,
  33223. 'ɵɵpropertyInterpolate8': ɵɵpropertyInterpolate8,
  33224. 'ɵɵpropertyInterpolateV': ɵɵpropertyInterpolateV,
  33225. 'ɵɵpipe': ɵɵpipe,
  33226. 'ɵɵqueryRefresh': ɵɵqueryRefresh,
  33227. 'ɵɵqueryAdvance': ɵɵqueryAdvance,
  33228. 'ɵɵviewQuery': ɵɵviewQuery,
  33229. 'ɵɵviewQuerySignal': ɵɵviewQuerySignal,
  33230. 'ɵɵloadQuery': ɵɵloadQuery,
  33231. 'ɵɵcontentQuery': ɵɵcontentQuery,
  33232. 'ɵɵcontentQuerySignal': ɵɵcontentQuerySignal,
  33233. 'ɵɵreference': ɵɵreference,
  33234. 'ɵɵclassMap': ɵɵclassMap,
  33235. 'ɵɵclassMapInterpolate1': ɵɵclassMapInterpolate1,
  33236. 'ɵɵclassMapInterpolate2': ɵɵclassMapInterpolate2,
  33237. 'ɵɵclassMapInterpolate3': ɵɵclassMapInterpolate3,
  33238. 'ɵɵclassMapInterpolate4': ɵɵclassMapInterpolate4,
  33239. 'ɵɵclassMapInterpolate5': ɵɵclassMapInterpolate5,
  33240. 'ɵɵclassMapInterpolate6': ɵɵclassMapInterpolate6,
  33241. 'ɵɵclassMapInterpolate7': ɵɵclassMapInterpolate7,
  33242. 'ɵɵclassMapInterpolate8': ɵɵclassMapInterpolate8,
  33243. 'ɵɵclassMapInterpolateV': ɵɵclassMapInterpolateV,
  33244. 'ɵɵstyleMap': ɵɵstyleMap,
  33245. 'ɵɵstyleMapInterpolate1': ɵɵstyleMapInterpolate1,
  33246. 'ɵɵstyleMapInterpolate2': ɵɵstyleMapInterpolate2,
  33247. 'ɵɵstyleMapInterpolate3': ɵɵstyleMapInterpolate3,
  33248. 'ɵɵstyleMapInterpolate4': ɵɵstyleMapInterpolate4,
  33249. 'ɵɵstyleMapInterpolate5': ɵɵstyleMapInterpolate5,
  33250. 'ɵɵstyleMapInterpolate6': ɵɵstyleMapInterpolate6,
  33251. 'ɵɵstyleMapInterpolate7': ɵɵstyleMapInterpolate7,
  33252. 'ɵɵstyleMapInterpolate8': ɵɵstyleMapInterpolate8,
  33253. 'ɵɵstyleMapInterpolateV': ɵɵstyleMapInterpolateV,
  33254. 'ɵɵstyleProp': ɵɵstyleProp,
  33255. 'ɵɵstylePropInterpolate1': ɵɵstylePropInterpolate1,
  33256. 'ɵɵstylePropInterpolate2': ɵɵstylePropInterpolate2,
  33257. 'ɵɵstylePropInterpolate3': ɵɵstylePropInterpolate3,
  33258. 'ɵɵstylePropInterpolate4': ɵɵstylePropInterpolate4,
  33259. 'ɵɵstylePropInterpolate5': ɵɵstylePropInterpolate5,
  33260. 'ɵɵstylePropInterpolate6': ɵɵstylePropInterpolate6,
  33261. 'ɵɵstylePropInterpolate7': ɵɵstylePropInterpolate7,
  33262. 'ɵɵstylePropInterpolate8': ɵɵstylePropInterpolate8,
  33263. 'ɵɵstylePropInterpolateV': ɵɵstylePropInterpolateV,
  33264. 'ɵɵclassProp': ɵɵclassProp,
  33265. 'ɵɵadvance': ɵɵadvance,
  33266. 'ɵɵtemplate': ɵɵtemplate,
  33267. 'ɵɵconditional': ɵɵconditional,
  33268. 'ɵɵdefer': ɵɵdefer,
  33269. 'ɵɵdeferWhen': ɵɵdeferWhen,
  33270. 'ɵɵdeferOnIdle': ɵɵdeferOnIdle,
  33271. 'ɵɵdeferOnImmediate': ɵɵdeferOnImmediate,
  33272. 'ɵɵdeferOnTimer': ɵɵdeferOnTimer,
  33273. 'ɵɵdeferOnHover': ɵɵdeferOnHover,
  33274. 'ɵɵdeferOnInteraction': ɵɵdeferOnInteraction,
  33275. 'ɵɵdeferOnViewport': ɵɵdeferOnViewport,
  33276. 'ɵɵdeferPrefetchWhen': ɵɵdeferPrefetchWhen,
  33277. 'ɵɵdeferPrefetchOnIdle': ɵɵdeferPrefetchOnIdle,
  33278. 'ɵɵdeferPrefetchOnImmediate': ɵɵdeferPrefetchOnImmediate,
  33279. 'ɵɵdeferPrefetchOnTimer': ɵɵdeferPrefetchOnTimer,
  33280. 'ɵɵdeferPrefetchOnHover': ɵɵdeferPrefetchOnHover,
  33281. 'ɵɵdeferPrefetchOnInteraction': ɵɵdeferPrefetchOnInteraction,
  33282. 'ɵɵdeferPrefetchOnViewport': ɵɵdeferPrefetchOnViewport,
  33283. 'ɵɵdeferHydrateWhen': ɵɵdeferHydrateWhen,
  33284. 'ɵɵdeferHydrateNever': ɵɵdeferHydrateNever,
  33285. 'ɵɵdeferHydrateOnIdle': ɵɵdeferHydrateOnIdle,
  33286. 'ɵɵdeferHydrateOnImmediate': ɵɵdeferHydrateOnImmediate,
  33287. 'ɵɵdeferHydrateOnTimer': ɵɵdeferHydrateOnTimer,
  33288. 'ɵɵdeferHydrateOnHover': ɵɵdeferHydrateOnHover,
  33289. 'ɵɵdeferHydrateOnInteraction': ɵɵdeferHydrateOnInteraction,
  33290. 'ɵɵdeferHydrateOnViewport': ɵɵdeferHydrateOnViewport,
  33291. 'ɵɵdeferEnableTimerScheduling': ɵɵdeferEnableTimerScheduling,
  33292. 'ɵɵrepeater': ɵɵrepeater,
  33293. 'ɵɵrepeaterCreate': ɵɵrepeaterCreate,
  33294. 'ɵɵrepeaterTrackByIndex': ɵɵrepeaterTrackByIndex,
  33295. 'ɵɵrepeaterTrackByIdentity': ɵɵrepeaterTrackByIdentity,
  33296. 'ɵɵcomponentInstance': ɵɵcomponentInstance,
  33297. 'ɵɵtext': ɵɵtext,
  33298. 'ɵɵtextInterpolate': ɵɵtextInterpolate,
  33299. 'ɵɵtextInterpolate1': ɵɵtextInterpolate1,
  33300. 'ɵɵtextInterpolate2': ɵɵtextInterpolate2,
  33301. 'ɵɵtextInterpolate3': ɵɵtextInterpolate3,
  33302. 'ɵɵtextInterpolate4': ɵɵtextInterpolate4,
  33303. 'ɵɵtextInterpolate5': ɵɵtextInterpolate5,
  33304. 'ɵɵtextInterpolate6': ɵɵtextInterpolate6,
  33305. 'ɵɵtextInterpolate7': ɵɵtextInterpolate7,
  33306. 'ɵɵtextInterpolate8': ɵɵtextInterpolate8,
  33307. 'ɵɵtextInterpolateV': ɵɵtextInterpolateV,
  33308. 'ɵɵi18n': ɵɵi18n,
  33309. 'ɵɵi18nAttributes': ɵɵi18nAttributes,
  33310. 'ɵɵi18nExp': ɵɵi18nExp,
  33311. 'ɵɵi18nStart': ɵɵi18nStart,
  33312. 'ɵɵi18nEnd': ɵɵi18nEnd,
  33313. 'ɵɵi18nApply': ɵɵi18nApply,
  33314. 'ɵɵi18nPostprocess': ɵɵi18nPostprocess,
  33315. 'ɵɵresolveWindow': ɵɵresolveWindow,
  33316. 'ɵɵresolveDocument': ɵɵresolveDocument,
  33317. 'ɵɵresolveBody': ɵɵresolveBody,
  33318. 'ɵɵsetComponentScope': ɵɵsetComponentScope,
  33319. 'ɵɵsetNgModuleScope': ɵɵsetNgModuleScope,
  33320. 'ɵɵregisterNgModuleType': registerNgModuleType,
  33321. 'ɵɵgetComponentDepsFactory': ɵɵgetComponentDepsFactory,
  33322. 'ɵsetClassDebugInfo': ɵsetClassDebugInfo,
  33323. 'ɵɵdeclareLet': ɵɵdeclareLet,
  33324. 'ɵɵstoreLet': ɵɵstoreLet,
  33325. 'ɵɵreadContextLet': ɵɵreadContextLet,
  33326. 'ɵɵattachSourceLocations': ɵɵattachSourceLocations,
  33327. 'ɵɵsanitizeHtml': ɵɵsanitizeHtml,
  33328. 'ɵɵsanitizeStyle': ɵɵsanitizeStyle,
  33329. 'ɵɵsanitizeResourceUrl': ɵɵsanitizeResourceUrl,
  33330. 'ɵɵsanitizeScript': ɵɵsanitizeScript,
  33331. 'ɵɵsanitizeUrl': ɵɵsanitizeUrl,
  33332. 'ɵɵsanitizeUrlOrResourceUrl': ɵɵsanitizeUrlOrResourceUrl,
  33333. 'ɵɵtrustConstantHtml': ɵɵtrustConstantHtml,
  33334. 'ɵɵtrustConstantResourceUrl': ɵɵtrustConstantResourceUrl,
  33335. 'ɵɵvalidateIframeAttribute': ɵɵvalidateIframeAttribute,
  33336. 'forwardRef': forwardRef,
  33337. 'resolveForwardRef': resolveForwardRef,
  33338. 'ɵɵtwoWayProperty': ɵɵtwoWayProperty,
  33339. 'ɵɵtwoWayBindingSet': ɵɵtwoWayBindingSet,
  33340. 'ɵɵtwoWayListener': ɵɵtwoWayListener,
  33341. 'ɵɵreplaceMetadata': ɵɵreplaceMetadata,
  33342. }))();
  33343. let jitOptions = null;
  33344. function setJitOptions(options) {
  33345. if (jitOptions !== null) {
  33346. if (options.defaultEncapsulation !== jitOptions.defaultEncapsulation) {
  33347. ngDevMode &&
  33348. console.error('Provided value for `defaultEncapsulation` can not be changed once it has been set.');
  33349. return;
  33350. }
  33351. if (options.preserveWhitespaces !== jitOptions.preserveWhitespaces) {
  33352. ngDevMode &&
  33353. console.error('Provided value for `preserveWhitespaces` can not be changed once it has been set.');
  33354. return;
  33355. }
  33356. }
  33357. jitOptions = options;
  33358. }
  33359. function getJitOptions() {
  33360. return jitOptions;
  33361. }
  33362. function resetJitOptions() {
  33363. jitOptions = null;
  33364. }
  33365. const moduleQueue = [];
  33366. /**
  33367. * Enqueues moduleDef to be checked later to see if scope can be set on its
  33368. * component declarations.
  33369. */
  33370. function enqueueModuleForDelayedScoping(moduleType, ngModule) {
  33371. moduleQueue.push({ moduleType, ngModule });
  33372. }
  33373. let flushingModuleQueue = false;
  33374. /**
  33375. * Loops over queued module definitions, if a given module definition has all of its
  33376. * declarations resolved, it dequeues that module definition and sets the scope on
  33377. * its declarations.
  33378. */
  33379. function flushModuleScopingQueueAsMuchAsPossible() {
  33380. if (!flushingModuleQueue) {
  33381. flushingModuleQueue = true;
  33382. try {
  33383. for (let i = moduleQueue.length - 1; i >= 0; i--) {
  33384. const { moduleType, ngModule } = moduleQueue[i];
  33385. if (ngModule.declarations && ngModule.declarations.every(isResolvedDeclaration)) {
  33386. // dequeue
  33387. moduleQueue.splice(i, 1);
  33388. setScopeOnDeclaredComponents(moduleType, ngModule);
  33389. }
  33390. }
  33391. }
  33392. finally {
  33393. flushingModuleQueue = false;
  33394. }
  33395. }
  33396. }
  33397. /**
  33398. * Returns truthy if a declaration has resolved. If the declaration happens to be
  33399. * an array of declarations, it will recurse to check each declaration in that array
  33400. * (which may also be arrays).
  33401. */
  33402. function isResolvedDeclaration(declaration) {
  33403. if (Array.isArray(declaration)) {
  33404. return declaration.every(isResolvedDeclaration);
  33405. }
  33406. return !!resolveForwardRef(declaration);
  33407. }
  33408. /**
  33409. * Compiles a module in JIT mode.
  33410. *
  33411. * This function automatically gets called when a class has a `@NgModule` decorator.
  33412. */
  33413. function compileNgModule(moduleType, ngModule = {}) {
  33414. compileNgModuleDefs(moduleType, ngModule);
  33415. if (ngModule.id !== undefined) {
  33416. registerNgModuleType(moduleType, ngModule.id);
  33417. }
  33418. // Because we don't know if all declarations have resolved yet at the moment the
  33419. // NgModule decorator is executing, we're enqueueing the setting of module scope
  33420. // on its declarations to be run at a later time when all declarations for the module,
  33421. // including forward refs, have resolved.
  33422. enqueueModuleForDelayedScoping(moduleType, ngModule);
  33423. }
  33424. /**
  33425. * Compiles and adds the `ɵmod`, `ɵfac` and `ɵinj` properties to the module class.
  33426. *
  33427. * It's possible to compile a module via this API which will allow duplicate declarations in its
  33428. * root.
  33429. */
  33430. function compileNgModuleDefs(moduleType, ngModule, allowDuplicateDeclarationsInRoot = false) {
  33431. ngDevMode && assertDefined(moduleType, 'Required value moduleType');
  33432. ngDevMode && assertDefined(ngModule, 'Required value ngModule');
  33433. const declarations = flatten(ngModule.declarations || EMPTY_ARRAY);
  33434. let ngModuleDef = null;
  33435. Object.defineProperty(moduleType, NG_MOD_DEF, {
  33436. configurable: true,
  33437. get: () => {
  33438. if (ngModuleDef === null) {
  33439. if (ngDevMode && ngModule.imports && ngModule.imports.indexOf(moduleType) > -1) {
  33440. // We need to assert this immediately, because allowing it to continue will cause it to
  33441. // go into an infinite loop before we've reached the point where we throw all the errors.
  33442. throw new Error(`'${stringifyForError(moduleType)}' module can't import itself`);
  33443. }
  33444. const compiler = getCompilerFacade({
  33445. usage: 0 /* JitCompilerUsage.Decorator */,
  33446. kind: 'NgModule',
  33447. type: moduleType,
  33448. });
  33449. ngModuleDef = compiler.compileNgModule(angularCoreEnv, `ng:///${moduleType.name}/ɵmod.js`, {
  33450. type: moduleType,
  33451. bootstrap: flatten(ngModule.bootstrap || EMPTY_ARRAY).map(resolveForwardRef),
  33452. declarations: declarations.map(resolveForwardRef),
  33453. imports: flatten(ngModule.imports || EMPTY_ARRAY)
  33454. .map(resolveForwardRef)
  33455. .map(expandModuleWithProviders),
  33456. exports: flatten(ngModule.exports || EMPTY_ARRAY)
  33457. .map(resolveForwardRef)
  33458. .map(expandModuleWithProviders),
  33459. schemas: ngModule.schemas ? flatten(ngModule.schemas) : null,
  33460. id: ngModule.id || null,
  33461. });
  33462. // Set `schemas` on ngModuleDef to an empty array in JIT mode to indicate that runtime
  33463. // should verify that there are no unknown elements in a template. In AOT mode, that check
  33464. // happens at compile time and `schemas` information is not present on Component and Module
  33465. // defs after compilation (so the check doesn't happen the second time at runtime).
  33466. if (!ngModuleDef.schemas) {
  33467. ngModuleDef.schemas = [];
  33468. }
  33469. }
  33470. return ngModuleDef;
  33471. },
  33472. });
  33473. let ngFactoryDef = null;
  33474. Object.defineProperty(moduleType, NG_FACTORY_DEF, {
  33475. get: () => {
  33476. if (ngFactoryDef === null) {
  33477. const compiler = getCompilerFacade({
  33478. usage: 0 /* JitCompilerUsage.Decorator */,
  33479. kind: 'NgModule',
  33480. type: moduleType,
  33481. });
  33482. ngFactoryDef = compiler.compileFactory(angularCoreEnv, `ng:///${moduleType.name}/ɵfac.js`, {
  33483. name: moduleType.name,
  33484. type: moduleType,
  33485. deps: reflectDependencies(moduleType),
  33486. target: compiler.FactoryTarget.NgModule,
  33487. typeArgumentCount: 0,
  33488. });
  33489. }
  33490. return ngFactoryDef;
  33491. },
  33492. // Make the property configurable in dev mode to allow overriding in tests
  33493. configurable: !!ngDevMode,
  33494. });
  33495. let ngInjectorDef = null;
  33496. Object.defineProperty(moduleType, NG_INJ_DEF, {
  33497. get: () => {
  33498. if (ngInjectorDef === null) {
  33499. ngDevMode && verifySemanticsOfNgModuleDef(moduleType, allowDuplicateDeclarationsInRoot);
  33500. const meta = {
  33501. name: moduleType.name,
  33502. type: moduleType,
  33503. providers: ngModule.providers || EMPTY_ARRAY,
  33504. imports: [
  33505. (ngModule.imports || EMPTY_ARRAY).map(resolveForwardRef),
  33506. (ngModule.exports || EMPTY_ARRAY).map(resolveForwardRef),
  33507. ],
  33508. };
  33509. const compiler = getCompilerFacade({
  33510. usage: 0 /* JitCompilerUsage.Decorator */,
  33511. kind: 'NgModule',
  33512. type: moduleType,
  33513. });
  33514. ngInjectorDef = compiler.compileInjector(angularCoreEnv, `ng:///${moduleType.name}/ɵinj.js`, meta);
  33515. }
  33516. return ngInjectorDef;
  33517. },
  33518. // Make the property configurable in dev mode to allow overriding in tests
  33519. configurable: !!ngDevMode,
  33520. });
  33521. }
  33522. function generateStandaloneInDeclarationsError(type, location) {
  33523. const prefix = `Unexpected "${stringifyForError(type)}" found in the "declarations" array of the`;
  33524. const suffix = `"${stringifyForError(type)}" is marked as standalone and can't be declared ` +
  33525. 'in any NgModule - did you intend to import it instead (by adding it to the "imports" array)?';
  33526. return `${prefix} ${location}, ${suffix}`;
  33527. }
  33528. function verifySemanticsOfNgModuleDef(moduleType, allowDuplicateDeclarationsInRoot, importingModule) {
  33529. if (verifiedNgModule.get(moduleType))
  33530. return;
  33531. // skip verifications of standalone components, directives, and pipes
  33532. if (isStandalone(moduleType))
  33533. return;
  33534. verifiedNgModule.set(moduleType, true);
  33535. moduleType = resolveForwardRef(moduleType);
  33536. let ngModuleDef;
  33537. if (importingModule) {
  33538. ngModuleDef = getNgModuleDef(moduleType);
  33539. if (!ngModuleDef) {
  33540. throw new Error(`Unexpected value '${moduleType.name}' imported by the module '${importingModule.name}'. Please add an @NgModule annotation.`);
  33541. }
  33542. }
  33543. else {
  33544. ngModuleDef = getNgModuleDef(moduleType, true);
  33545. }
  33546. const errors = [];
  33547. const declarations = maybeUnwrapFn(ngModuleDef.declarations);
  33548. const imports = maybeUnwrapFn(ngModuleDef.imports);
  33549. flatten(imports)
  33550. .map(unwrapModuleWithProvidersImports)
  33551. .forEach((modOrStandaloneCmpt) => {
  33552. verifySemanticsOfNgModuleImport(modOrStandaloneCmpt, moduleType);
  33553. verifySemanticsOfNgModuleDef(modOrStandaloneCmpt, false, moduleType);
  33554. });
  33555. const exports = maybeUnwrapFn(ngModuleDef.exports);
  33556. declarations.forEach(verifyDeclarationsHaveDefinitions);
  33557. declarations.forEach(verifyDirectivesHaveSelector);
  33558. declarations.forEach((declarationType) => verifyNotStandalone(declarationType, moduleType));
  33559. const combinedDeclarations = [
  33560. ...declarations.map(resolveForwardRef),
  33561. ...flatten(imports.map(computeCombinedExports)).map(resolveForwardRef),
  33562. ];
  33563. exports.forEach(verifyExportsAreDeclaredOrReExported);
  33564. declarations.forEach((decl) => verifyDeclarationIsUnique(decl, allowDuplicateDeclarationsInRoot));
  33565. const ngModule = getAnnotation(moduleType, 'NgModule');
  33566. if (ngModule) {
  33567. ngModule.imports &&
  33568. flatten(ngModule.imports)
  33569. .map(unwrapModuleWithProvidersImports)
  33570. .forEach((mod) => {
  33571. verifySemanticsOfNgModuleImport(mod, moduleType);
  33572. verifySemanticsOfNgModuleDef(mod, false, moduleType);
  33573. });
  33574. ngModule.bootstrap && deepForEach(ngModule.bootstrap, verifyCorrectBootstrapType);
  33575. ngModule.bootstrap && deepForEach(ngModule.bootstrap, verifyComponentIsPartOfNgModule);
  33576. }
  33577. // Throw Error if any errors were detected.
  33578. if (errors.length) {
  33579. throw new Error(errors.join('\n'));
  33580. }
  33581. ////////////////////////////////////////////////////////////////////////////////////////////////
  33582. function verifyDeclarationsHaveDefinitions(type) {
  33583. type = resolveForwardRef(type);
  33584. const def = getComponentDef(type) || getDirectiveDef(type) || getPipeDef$1(type);
  33585. if (!def) {
  33586. errors.push(`Unexpected value '${stringifyForError(type)}' declared by the module '${stringifyForError(moduleType)}'. Please add a @Pipe/@Directive/@Component annotation.`);
  33587. }
  33588. }
  33589. function verifyDirectivesHaveSelector(type) {
  33590. type = resolveForwardRef(type);
  33591. const def = getDirectiveDef(type);
  33592. if (!getComponentDef(type) && def && def.selectors.length == 0) {
  33593. errors.push(`Directive ${stringifyForError(type)} has no selector, please add it!`);
  33594. }
  33595. }
  33596. function verifyNotStandalone(type, moduleType) {
  33597. type = resolveForwardRef(type);
  33598. const def = getComponentDef(type) || getDirectiveDef(type) || getPipeDef$1(type);
  33599. if (def?.standalone) {
  33600. const location = `"${stringifyForError(moduleType)}" NgModule`;
  33601. errors.push(generateStandaloneInDeclarationsError(type, location));
  33602. }
  33603. }
  33604. function verifyExportsAreDeclaredOrReExported(type) {
  33605. type = resolveForwardRef(type);
  33606. const kind = (getComponentDef(type) && 'component') ||
  33607. (getDirectiveDef(type) && 'directive') ||
  33608. (getPipeDef$1(type) && 'pipe');
  33609. if (kind) {
  33610. // only checked if we are declared as Component, Directive, or Pipe
  33611. // Modules don't need to be declared or imported.
  33612. if (combinedDeclarations.lastIndexOf(type) === -1) {
  33613. // We are exporting something which we don't explicitly declare or import.
  33614. errors.push(`Can't export ${kind} ${stringifyForError(type)} from ${stringifyForError(moduleType)} as it was neither declared nor imported!`);
  33615. }
  33616. }
  33617. }
  33618. function verifyDeclarationIsUnique(type, suppressErrors) {
  33619. type = resolveForwardRef(type);
  33620. const existingModule = ownerNgModule.get(type);
  33621. if (existingModule && existingModule !== moduleType) {
  33622. if (!suppressErrors) {
  33623. const modules = [existingModule, moduleType].map(stringifyForError).sort();
  33624. errors.push(`Type ${stringifyForError(type)} is part of the declarations of 2 modules: ${modules[0]} and ${modules[1]}! ` +
  33625. `Please consider moving ${stringifyForError(type)} to a higher module that imports ${modules[0]} and ${modules[1]}. ` +
  33626. `You can also create a new NgModule that exports and includes ${stringifyForError(type)} then import that NgModule in ${modules[0]} and ${modules[1]}.`);
  33627. }
  33628. }
  33629. else {
  33630. // Mark type as having owner.
  33631. ownerNgModule.set(type, moduleType);
  33632. }
  33633. }
  33634. function verifyComponentIsPartOfNgModule(type) {
  33635. type = resolveForwardRef(type);
  33636. const existingModule = ownerNgModule.get(type);
  33637. if (!existingModule && !isStandalone(type)) {
  33638. errors.push(`Component ${stringifyForError(type)} is not part of any NgModule or the module has not been imported into your module.`);
  33639. }
  33640. }
  33641. function verifyCorrectBootstrapType(type) {
  33642. type = resolveForwardRef(type);
  33643. if (!getComponentDef(type)) {
  33644. errors.push(`${stringifyForError(type)} cannot be used as an entry component.`);
  33645. }
  33646. if (isStandalone(type)) {
  33647. // Note: this error should be the same as the
  33648. // `NGMODULE_BOOTSTRAP_IS_STANDALONE` one in AOT compiler.
  33649. errors.push(`The \`${stringifyForError(type)}\` class is a standalone component, which can ` +
  33650. `not be used in the \`@NgModule.bootstrap\` array. Use the \`bootstrapApplication\` ` +
  33651. `function for bootstrap instead.`);
  33652. }
  33653. }
  33654. function verifySemanticsOfNgModuleImport(type, importingModule) {
  33655. type = resolveForwardRef(type);
  33656. const directiveDef = getComponentDef(type) || getDirectiveDef(type);
  33657. if (directiveDef !== null && !directiveDef.standalone) {
  33658. throw new Error(`Unexpected directive '${type.name}' imported by the module '${importingModule.name}'. Please add an @NgModule annotation.`);
  33659. }
  33660. const pipeDef = getPipeDef$1(type);
  33661. if (pipeDef !== null && !pipeDef.standalone) {
  33662. throw new Error(`Unexpected pipe '${type.name}' imported by the module '${importingModule.name}'. Please add an @NgModule annotation.`);
  33663. }
  33664. }
  33665. }
  33666. function unwrapModuleWithProvidersImports(typeOrWithProviders) {
  33667. typeOrWithProviders = resolveForwardRef(typeOrWithProviders);
  33668. return typeOrWithProviders.ngModule || typeOrWithProviders;
  33669. }
  33670. function getAnnotation(type, name) {
  33671. let annotation = null;
  33672. collect(type.__annotations__);
  33673. collect(type.decorators);
  33674. return annotation;
  33675. function collect(annotations) {
  33676. if (annotations) {
  33677. annotations.forEach(readAnnotation);
  33678. }
  33679. }
  33680. function readAnnotation(decorator) {
  33681. if (!annotation) {
  33682. const proto = Object.getPrototypeOf(decorator);
  33683. if (proto.ngMetadataName == name) {
  33684. annotation = decorator;
  33685. }
  33686. else if (decorator.type) {
  33687. const proto = Object.getPrototypeOf(decorator.type);
  33688. if (proto.ngMetadataName == name) {
  33689. annotation = decorator.args[0];
  33690. }
  33691. }
  33692. }
  33693. }
  33694. }
  33695. /**
  33696. * Keep track of compiled components. This is needed because in tests we often want to compile the
  33697. * same component with more than one NgModule. This would cause an error unless we reset which
  33698. * NgModule the component belongs to. We keep the list of compiled components here so that the
  33699. * TestBed can reset it later.
  33700. */
  33701. let ownerNgModule = new WeakMap();
  33702. let verifiedNgModule = new WeakMap();
  33703. function resetCompiledComponents() {
  33704. ownerNgModule = new WeakMap();
  33705. verifiedNgModule = new WeakMap();
  33706. moduleQueue.length = 0;
  33707. GENERATED_COMP_IDS.clear();
  33708. }
  33709. /**
  33710. * Computes the combined declarations of explicit declarations, as well as declarations inherited by
  33711. * traversing the exports of imported modules.
  33712. * @param type
  33713. */
  33714. function computeCombinedExports(type) {
  33715. type = resolveForwardRef(type);
  33716. const ngModuleDef = getNgModuleDef(type);
  33717. // a standalone component, directive or pipe
  33718. if (ngModuleDef === null) {
  33719. return [type];
  33720. }
  33721. return flatten(maybeUnwrapFn(ngModuleDef.exports).map((type) => {
  33722. const ngModuleDef = getNgModuleDef(type);
  33723. if (ngModuleDef) {
  33724. verifySemanticsOfNgModuleDef(type, false);
  33725. return computeCombinedExports(type);
  33726. }
  33727. else {
  33728. return type;
  33729. }
  33730. }));
  33731. }
  33732. /**
  33733. * Some declared components may be compiled asynchronously, and thus may not have their
  33734. * ɵcmp set yet. If this is the case, then a reference to the module is written into
  33735. * the `ngSelectorScope` property of the declared type.
  33736. */
  33737. function setScopeOnDeclaredComponents(moduleType, ngModule) {
  33738. const declarations = flatten(ngModule.declarations || EMPTY_ARRAY);
  33739. const transitiveScopes = transitiveScopesFor(moduleType);
  33740. declarations.forEach((declaration) => {
  33741. declaration = resolveForwardRef(declaration);
  33742. if (declaration.hasOwnProperty(NG_COMP_DEF)) {
  33743. // A `ɵcmp` field exists - go ahead and patch the component directly.
  33744. const component = declaration;
  33745. const componentDef = getComponentDef(component);
  33746. patchComponentDefWithScope(componentDef, transitiveScopes);
  33747. }
  33748. else if (!declaration.hasOwnProperty(NG_DIR_DEF) &&
  33749. !declaration.hasOwnProperty(NG_PIPE_DEF)) {
  33750. // Set `ngSelectorScope` for future reference when the component compilation finishes.
  33751. declaration.ngSelectorScope = moduleType;
  33752. }
  33753. });
  33754. }
  33755. /**
  33756. * Patch the definition of a component with directives and pipes from the compilation scope of
  33757. * a given module.
  33758. */
  33759. function patchComponentDefWithScope(componentDef, transitiveScopes) {
  33760. componentDef.directiveDefs = () => Array.from(transitiveScopes.compilation.directives)
  33761. .map((dir) => dir.hasOwnProperty(NG_COMP_DEF) ? getComponentDef(dir) : getDirectiveDef(dir))
  33762. .filter((def) => !!def);
  33763. componentDef.pipeDefs = () => Array.from(transitiveScopes.compilation.pipes).map((pipe) => getPipeDef$1(pipe));
  33764. componentDef.schemas = transitiveScopes.schemas;
  33765. // Since we avoid Components/Directives/Pipes recompiling in case there are no overrides, we
  33766. // may face a problem where previously compiled defs available to a given Component/Directive
  33767. // are cached in TView and may become stale (in case any of these defs gets recompiled). In
  33768. // order to avoid this problem, we force fresh TView to be created.
  33769. componentDef.tView = null;
  33770. }
  33771. /**
  33772. * Compute the pair of transitive scopes (compilation scope and exported scope) for a given type
  33773. * (either a NgModule or a standalone component / directive / pipe).
  33774. */
  33775. function transitiveScopesFor(type) {
  33776. if (isNgModule(type)) {
  33777. {
  33778. const scope = depsTracker.getNgModuleScope(type);
  33779. const def = getNgModuleDef(type, true);
  33780. return {
  33781. schemas: def.schemas || null,
  33782. ...scope,
  33783. };
  33784. }
  33785. }
  33786. else if (isStandalone(type)) {
  33787. const directiveDef = getComponentDef(type) || getDirectiveDef(type);
  33788. if (directiveDef !== null) {
  33789. return {
  33790. schemas: null,
  33791. compilation: {
  33792. directives: new Set(),
  33793. pipes: new Set(),
  33794. },
  33795. exported: {
  33796. directives: new Set([type]),
  33797. pipes: new Set(),
  33798. },
  33799. };
  33800. }
  33801. const pipeDef = getPipeDef$1(type);
  33802. if (pipeDef !== null) {
  33803. return {
  33804. schemas: null,
  33805. compilation: {
  33806. directives: new Set(),
  33807. pipes: new Set(),
  33808. },
  33809. exported: {
  33810. directives: new Set(),
  33811. pipes: new Set([type]),
  33812. },
  33813. };
  33814. }
  33815. }
  33816. // TODO: change the error message to be more user-facing and take standalone into account
  33817. throw new Error(`${type.name} does not have a module def (ɵmod property)`);
  33818. }
  33819. function expandModuleWithProviders(value) {
  33820. if (isModuleWithProviders(value)) {
  33821. return value.ngModule;
  33822. }
  33823. return value;
  33824. }
  33825. /**
  33826. * Keep track of the compilation depth to avoid reentrancy issues during JIT compilation. This
  33827. * matters in the following scenario:
  33828. *
  33829. * Consider a component 'A' that extends component 'B', both declared in module 'M'. During
  33830. * the compilation of 'A' the definition of 'B' is requested to capture the inheritance chain,
  33831. * potentially triggering compilation of 'B'. If this nested compilation were to trigger
  33832. * `flushModuleScopingQueueAsMuchAsPossible` it may happen that module 'M' is still pending in the
  33833. * queue, resulting in 'A' and 'B' to be patched with the NgModule scope. As the compilation of
  33834. * 'A' is still in progress, this would introduce a circular dependency on its compilation. To avoid
  33835. * this issue, the module scope queue is only flushed for compilations at the depth 0, to ensure
  33836. * all compilations have finished.
  33837. */
  33838. let compilationDepth = 0;
  33839. /**
  33840. * Compile an Angular component according to its decorator metadata, and patch the resulting
  33841. * component def (ɵcmp) onto the component type.
  33842. *
  33843. * Compilation may be asynchronous (due to the need to resolve URLs for the component template or
  33844. * other resources, for example). In the event that compilation is not immediate, `compileComponent`
  33845. * will enqueue resource resolution into a global queue and will fail to return the `ɵcmp`
  33846. * until the global queue has been resolved with a call to `resolveComponentResources`.
  33847. */
  33848. function compileComponent(type, metadata) {
  33849. // Initialize ngDevMode. This must be the first statement in compileComponent.
  33850. // See the `initNgDevMode` docstring for more information.
  33851. (typeof ngDevMode === 'undefined' || ngDevMode) && initNgDevMode();
  33852. let ngComponentDef = null;
  33853. // Metadata may have resources which need to be resolved.
  33854. maybeQueueResolutionOfComponentResources(type, metadata);
  33855. // Note that we're using the same function as `Directive`, because that's only subset of metadata
  33856. // that we need to create the ngFactoryDef. We're avoiding using the component metadata
  33857. // because we'd have to resolve the asynchronous templates.
  33858. addDirectiveFactoryDef(type, metadata);
  33859. Object.defineProperty(type, NG_COMP_DEF, {
  33860. get: () => {
  33861. if (ngComponentDef === null) {
  33862. const compiler = getCompilerFacade({
  33863. usage: 0 /* JitCompilerUsage.Decorator */,
  33864. kind: 'component',
  33865. type: type,
  33866. });
  33867. if (componentNeedsResolution(metadata)) {
  33868. const error = [`Component '${type.name}' is not resolved:`];
  33869. if (metadata.templateUrl) {
  33870. error.push(` - templateUrl: ${metadata.templateUrl}`);
  33871. }
  33872. if (metadata.styleUrls && metadata.styleUrls.length) {
  33873. error.push(` - styleUrls: ${JSON.stringify(metadata.styleUrls)}`);
  33874. }
  33875. if (metadata.styleUrl) {
  33876. error.push(` - styleUrl: ${metadata.styleUrl}`);
  33877. }
  33878. error.push(`Did you run and wait for 'resolveComponentResources()'?`);
  33879. throw new Error(error.join('\n'));
  33880. }
  33881. // This const was called `jitOptions` previously but had to be renamed to `options` because
  33882. // of a bug with Terser that caused optimized JIT builds to throw a `ReferenceError`.
  33883. // This bug was investigated in https://github.com/angular/angular-cli/issues/17264.
  33884. // We should not rename it back until https://github.com/terser/terser/issues/615 is fixed.
  33885. const options = getJitOptions();
  33886. let preserveWhitespaces = metadata.preserveWhitespaces;
  33887. if (preserveWhitespaces === undefined) {
  33888. if (options !== null && options.preserveWhitespaces !== undefined) {
  33889. preserveWhitespaces = options.preserveWhitespaces;
  33890. }
  33891. else {
  33892. preserveWhitespaces = false;
  33893. }
  33894. }
  33895. let encapsulation = metadata.encapsulation;
  33896. if (encapsulation === undefined) {
  33897. if (options !== null && options.defaultEncapsulation !== undefined) {
  33898. encapsulation = options.defaultEncapsulation;
  33899. }
  33900. else {
  33901. encapsulation = ViewEncapsulation.Emulated;
  33902. }
  33903. }
  33904. const templateUrl = metadata.templateUrl || `ng:///${type.name}/template.html`;
  33905. const meta = {
  33906. ...directiveMetadata(type, metadata),
  33907. typeSourceSpan: compiler.createParseSourceSpan('Component', type.name, templateUrl),
  33908. template: metadata.template || '',
  33909. preserveWhitespaces,
  33910. styles: typeof metadata.styles === 'string'
  33911. ? [metadata.styles]
  33912. : metadata.styles || EMPTY_ARRAY,
  33913. animations: metadata.animations,
  33914. // JIT components are always compiled against an empty set of `declarations`. Instead, the
  33915. // `directiveDefs` and `pipeDefs` are updated at a later point:
  33916. // * for NgModule-based components, they're set when the NgModule which declares the
  33917. // component resolves in the module scoping queue
  33918. // * for standalone components, they're set just below, after `compileComponent`.
  33919. declarations: [],
  33920. changeDetection: metadata.changeDetection,
  33921. encapsulation,
  33922. interpolation: metadata.interpolation,
  33923. viewProviders: metadata.viewProviders || null,
  33924. };
  33925. compilationDepth++;
  33926. try {
  33927. if (meta.usesInheritance) {
  33928. addDirectiveDefToUndecoratedParents(type);
  33929. }
  33930. ngComponentDef = compiler.compileComponent(angularCoreEnv, templateUrl, meta);
  33931. if (meta.isStandalone) {
  33932. // Patch the component definition for standalone components with `directiveDefs` and
  33933. // `pipeDefs` functions which lazily compute the directives/pipes available in the
  33934. // standalone component. Also set `dependencies` to the lazily resolved list of imports.
  33935. const imports = flatten(metadata.imports || EMPTY_ARRAY);
  33936. const { directiveDefs, pipeDefs } = getStandaloneDefFunctions(type, imports);
  33937. ngComponentDef.directiveDefs = directiveDefs;
  33938. ngComponentDef.pipeDefs = pipeDefs;
  33939. ngComponentDef.dependencies = () => imports.map(resolveForwardRef);
  33940. }
  33941. }
  33942. finally {
  33943. // Ensure that the compilation depth is decremented even when the compilation failed.
  33944. compilationDepth--;
  33945. }
  33946. if (compilationDepth === 0) {
  33947. // When NgModule decorator executed, we enqueued the module definition such that
  33948. // it would only dequeue and add itself as module scope to all of its declarations,
  33949. // but only if if all of its declarations had resolved. This call runs the check
  33950. // to see if any modules that are in the queue can be dequeued and add scope to
  33951. // their declarations.
  33952. flushModuleScopingQueueAsMuchAsPossible();
  33953. }
  33954. // If component compilation is async, then the @NgModule annotation which declares the
  33955. // component may execute and set an ngSelectorScope property on the component type. This
  33956. // allows the component to patch itself with directiveDefs from the module after it
  33957. // finishes compiling.
  33958. if (hasSelectorScope(type)) {
  33959. const scopes = transitiveScopesFor(type.ngSelectorScope);
  33960. patchComponentDefWithScope(ngComponentDef, scopes);
  33961. }
  33962. if (metadata.schemas) {
  33963. if (meta.isStandalone) {
  33964. ngComponentDef.schemas = metadata.schemas;
  33965. }
  33966. else {
  33967. throw new Error(`The 'schemas' was specified for the ${stringifyForError(type)} but is only valid on a component that is standalone.`);
  33968. }
  33969. }
  33970. else if (meta.isStandalone) {
  33971. ngComponentDef.schemas = [];
  33972. }
  33973. }
  33974. return ngComponentDef;
  33975. },
  33976. set: (def) => {
  33977. ngComponentDef = def;
  33978. },
  33979. // Make the property configurable in dev mode to allow overriding in tests
  33980. configurable: !!ngDevMode,
  33981. });
  33982. }
  33983. /**
  33984. * Build memoized `directiveDefs` and `pipeDefs` functions for the component definition of a
  33985. * standalone component, which process `imports` and filter out directives and pipes. The use of
  33986. * memoized functions here allows for the delayed resolution of any `forwardRef`s present in the
  33987. * component's `imports`.
  33988. */
  33989. function getStandaloneDefFunctions(type, imports) {
  33990. const directiveDefs = () => {
  33991. {
  33992. if (ngDevMode) {
  33993. for (const rawDep of imports) {
  33994. verifyStandaloneImport(rawDep, type);
  33995. }
  33996. }
  33997. if (!isComponent(type)) {
  33998. return [];
  33999. }
  34000. const scope = depsTracker.getStandaloneComponentScope(type, imports);
  34001. return [...scope.compilation.directives]
  34002. .map((p) => (getComponentDef(p) || getDirectiveDef(p)))
  34003. .filter((d) => d !== null);
  34004. }
  34005. };
  34006. const pipeDefs = () => {
  34007. {
  34008. if (ngDevMode) {
  34009. for (const rawDep of imports) {
  34010. verifyStandaloneImport(rawDep, type);
  34011. }
  34012. }
  34013. if (!isComponent(type)) {
  34014. return [];
  34015. }
  34016. const scope = depsTracker.getStandaloneComponentScope(type, imports);
  34017. return [...scope.compilation.pipes].map((p) => getPipeDef$1(p)).filter((d) => d !== null);
  34018. }
  34019. };
  34020. return {
  34021. directiveDefs,
  34022. pipeDefs,
  34023. };
  34024. }
  34025. function hasSelectorScope(component) {
  34026. return component.ngSelectorScope !== undefined;
  34027. }
  34028. /**
  34029. * Compile an Angular directive according to its decorator metadata, and patch the resulting
  34030. * directive def onto the component type.
  34031. *
  34032. * In the event that compilation is not immediate, `compileDirective` will return a `Promise` which
  34033. * will resolve when compilation completes and the directive becomes usable.
  34034. */
  34035. function compileDirective(type, directive) {
  34036. let ngDirectiveDef = null;
  34037. addDirectiveFactoryDef(type, directive || {});
  34038. Object.defineProperty(type, NG_DIR_DEF, {
  34039. get: () => {
  34040. if (ngDirectiveDef === null) {
  34041. // `directive` can be null in the case of abstract directives as a base class
  34042. // that use `@Directive()` with no selector. In that case, pass empty object to the
  34043. // `directiveMetadata` function instead of null.
  34044. const meta = getDirectiveMetadata(type, directive || {});
  34045. const compiler = getCompilerFacade({
  34046. usage: 0 /* JitCompilerUsage.Decorator */,
  34047. kind: 'directive',
  34048. type,
  34049. });
  34050. ngDirectiveDef = compiler.compileDirective(angularCoreEnv, meta.sourceMapUrl, meta.metadata);
  34051. }
  34052. return ngDirectiveDef;
  34053. },
  34054. // Make the property configurable in dev mode to allow overriding in tests
  34055. configurable: !!ngDevMode,
  34056. });
  34057. }
  34058. function getDirectiveMetadata(type, metadata) {
  34059. const name = type && type.name;
  34060. const sourceMapUrl = `ng:///${name}/ɵdir.js`;
  34061. const compiler = getCompilerFacade({ usage: 0 /* JitCompilerUsage.Decorator */, kind: 'directive', type });
  34062. const facade = directiveMetadata(type, metadata);
  34063. facade.typeSourceSpan = compiler.createParseSourceSpan('Directive', name, sourceMapUrl);
  34064. if (facade.usesInheritance) {
  34065. addDirectiveDefToUndecoratedParents(type);
  34066. }
  34067. return { metadata: facade, sourceMapUrl };
  34068. }
  34069. function addDirectiveFactoryDef(type, metadata) {
  34070. let ngFactoryDef = null;
  34071. Object.defineProperty(type, NG_FACTORY_DEF, {
  34072. get: () => {
  34073. if (ngFactoryDef === null) {
  34074. const meta = getDirectiveMetadata(type, metadata);
  34075. const compiler = getCompilerFacade({
  34076. usage: 0 /* JitCompilerUsage.Decorator */,
  34077. kind: 'directive',
  34078. type,
  34079. });
  34080. ngFactoryDef = compiler.compileFactory(angularCoreEnv, `ng:///${type.name}/ɵfac.js`, {
  34081. name: meta.metadata.name,
  34082. type: meta.metadata.type,
  34083. typeArgumentCount: 0,
  34084. deps: reflectDependencies(type),
  34085. target: compiler.FactoryTarget.Directive,
  34086. });
  34087. }
  34088. return ngFactoryDef;
  34089. },
  34090. // Make the property configurable in dev mode to allow overriding in tests
  34091. configurable: !!ngDevMode,
  34092. });
  34093. }
  34094. function extendsDirectlyFromObject(type) {
  34095. return Object.getPrototypeOf(type.prototype) === Object.prototype;
  34096. }
  34097. /**
  34098. * Extract the `R3DirectiveMetadata` for a particular directive (either a `Directive` or a
  34099. * `Component`).
  34100. */
  34101. function directiveMetadata(type, metadata) {
  34102. // Reflect inputs and outputs.
  34103. const reflect = getReflect();
  34104. const propMetadata = reflect.ownPropMetadata(type);
  34105. return {
  34106. name: type.name,
  34107. type: type,
  34108. selector: metadata.selector !== undefined ? metadata.selector : null,
  34109. host: metadata.host || EMPTY_OBJ,
  34110. propMetadata: propMetadata,
  34111. inputs: metadata.inputs || EMPTY_ARRAY,
  34112. outputs: metadata.outputs || EMPTY_ARRAY,
  34113. queries: extractQueriesMetadata(type, propMetadata, isContentQuery),
  34114. lifecycle: { usesOnChanges: reflect.hasLifecycleHook(type, 'ngOnChanges') },
  34115. typeSourceSpan: null,
  34116. usesInheritance: !extendsDirectlyFromObject(type),
  34117. exportAs: extractExportAs(metadata.exportAs),
  34118. providers: metadata.providers || null,
  34119. viewQueries: extractQueriesMetadata(type, propMetadata, isViewQuery),
  34120. isStandalone: metadata.standalone === undefined ? true : !!metadata.standalone,
  34121. isSignal: !!metadata.signals,
  34122. hostDirectives: metadata.hostDirectives?.map((directive) => typeof directive === 'function' ? { directive } : directive) || null,
  34123. };
  34124. }
  34125. /**
  34126. * Adds a directive definition to all parent classes of a type that don't have an Angular decorator.
  34127. */
  34128. function addDirectiveDefToUndecoratedParents(type) {
  34129. const objPrototype = Object.prototype;
  34130. let parent = Object.getPrototypeOf(type.prototype).constructor;
  34131. // Go up the prototype until we hit `Object`.
  34132. while (parent && parent !== objPrototype) {
  34133. // Since inheritance works if the class was annotated already, we only need to add
  34134. // the def if there are no annotations and the def hasn't been created already.
  34135. if (!getDirectiveDef(parent) &&
  34136. !getComponentDef(parent) &&
  34137. shouldAddAbstractDirective(parent)) {
  34138. compileDirective(parent, null);
  34139. }
  34140. parent = Object.getPrototypeOf(parent);
  34141. }
  34142. }
  34143. function convertToR3QueryPredicate(selector) {
  34144. return typeof selector === 'string' ? splitByComma(selector) : resolveForwardRef(selector);
  34145. }
  34146. function convertToR3QueryMetadata(propertyName, ann) {
  34147. return {
  34148. propertyName: propertyName,
  34149. predicate: convertToR3QueryPredicate(ann.selector),
  34150. descendants: ann.descendants,
  34151. first: ann.first,
  34152. read: ann.read ? ann.read : null,
  34153. static: !!ann.static,
  34154. emitDistinctChangesOnly: !!ann.emitDistinctChangesOnly,
  34155. isSignal: !!ann.isSignal,
  34156. };
  34157. }
  34158. function extractQueriesMetadata(type, propMetadata, isQueryAnn) {
  34159. const queriesMeta = [];
  34160. for (const field in propMetadata) {
  34161. if (propMetadata.hasOwnProperty(field)) {
  34162. const annotations = propMetadata[field];
  34163. annotations.forEach((ann) => {
  34164. if (isQueryAnn(ann)) {
  34165. if (!ann.selector) {
  34166. throw new Error(`Can't construct a query for the property "${field}" of ` +
  34167. `"${stringifyForError(type)}" since the query selector wasn't defined.`);
  34168. }
  34169. if (annotations.some(isInputAnnotation)) {
  34170. throw new Error(`Cannot combine @Input decorators with query decorators`);
  34171. }
  34172. queriesMeta.push(convertToR3QueryMetadata(field, ann));
  34173. }
  34174. });
  34175. }
  34176. }
  34177. return queriesMeta;
  34178. }
  34179. function extractExportAs(exportAs) {
  34180. return exportAs === undefined ? null : splitByComma(exportAs);
  34181. }
  34182. function isContentQuery(value) {
  34183. const name = value.ngMetadataName;
  34184. return name === 'ContentChild' || name === 'ContentChildren';
  34185. }
  34186. function isViewQuery(value) {
  34187. const name = value.ngMetadataName;
  34188. return name === 'ViewChild' || name === 'ViewChildren';
  34189. }
  34190. function isInputAnnotation(value) {
  34191. return value.ngMetadataName === 'Input';
  34192. }
  34193. function splitByComma(value) {
  34194. return value.split(',').map((piece) => piece.trim());
  34195. }
  34196. const LIFECYCLE_HOOKS = [
  34197. 'ngOnChanges',
  34198. 'ngOnInit',
  34199. 'ngOnDestroy',
  34200. 'ngDoCheck',
  34201. 'ngAfterViewInit',
  34202. 'ngAfterViewChecked',
  34203. 'ngAfterContentInit',
  34204. 'ngAfterContentChecked',
  34205. ];
  34206. function shouldAddAbstractDirective(type) {
  34207. const reflect = getReflect();
  34208. if (LIFECYCLE_HOOKS.some((hookName) => reflect.hasLifecycleHook(type, hookName))) {
  34209. return true;
  34210. }
  34211. const propMetadata = reflect.propMetadata(type);
  34212. for (const field in propMetadata) {
  34213. const annotations = propMetadata[field];
  34214. for (let i = 0; i < annotations.length; i++) {
  34215. const current = annotations[i];
  34216. const metadataName = current.ngMetadataName;
  34217. if (isInputAnnotation(current) ||
  34218. isContentQuery(current) ||
  34219. isViewQuery(current) ||
  34220. metadataName === 'Output' ||
  34221. metadataName === 'HostBinding' ||
  34222. metadataName === 'HostListener') {
  34223. return true;
  34224. }
  34225. }
  34226. }
  34227. return false;
  34228. }
  34229. function compilePipe(type, meta) {
  34230. let ngPipeDef = null;
  34231. let ngFactoryDef = null;
  34232. Object.defineProperty(type, NG_FACTORY_DEF, {
  34233. get: () => {
  34234. if (ngFactoryDef === null) {
  34235. const metadata = getPipeMetadata(type, meta);
  34236. const compiler = getCompilerFacade({
  34237. usage: 0 /* JitCompilerUsage.Decorator */,
  34238. kind: 'pipe',
  34239. type: metadata.type,
  34240. });
  34241. ngFactoryDef = compiler.compileFactory(angularCoreEnv, `ng:///${metadata.name}/ɵfac.js`, {
  34242. name: metadata.name,
  34243. type: metadata.type,
  34244. typeArgumentCount: 0,
  34245. deps: reflectDependencies(type),
  34246. target: compiler.FactoryTarget.Pipe,
  34247. });
  34248. }
  34249. return ngFactoryDef;
  34250. },
  34251. // Make the property configurable in dev mode to allow overriding in tests
  34252. configurable: !!ngDevMode,
  34253. });
  34254. Object.defineProperty(type, NG_PIPE_DEF, {
  34255. get: () => {
  34256. if (ngPipeDef === null) {
  34257. const metadata = getPipeMetadata(type, meta);
  34258. const compiler = getCompilerFacade({
  34259. usage: 0 /* JitCompilerUsage.Decorator */,
  34260. kind: 'pipe',
  34261. type: metadata.type,
  34262. });
  34263. ngPipeDef = compiler.compilePipe(angularCoreEnv, `ng:///${metadata.name}/ɵpipe.js`, metadata);
  34264. }
  34265. return ngPipeDef;
  34266. },
  34267. // Make the property configurable in dev mode to allow overriding in tests
  34268. configurable: !!ngDevMode,
  34269. });
  34270. }
  34271. function getPipeMetadata(type, meta) {
  34272. return {
  34273. type: type,
  34274. name: type.name,
  34275. pipeName: meta.name,
  34276. pure: meta.pure !== undefined ? meta.pure : true,
  34277. isStandalone: meta.standalone === undefined ? true : !!meta.standalone,
  34278. };
  34279. }
  34280. /**
  34281. * Type of the Directive metadata.
  34282. *
  34283. * @publicApi
  34284. */
  34285. const Directive = makeDecorator('Directive', (dir = {}) => dir, undefined, undefined, (type, meta) => compileDirective(type, meta));
  34286. /**
  34287. * Component decorator and metadata.
  34288. *
  34289. * @Annotation
  34290. * @publicApi
  34291. */
  34292. const Component = makeDecorator('Component', (c = {}) => ({ changeDetection: ChangeDetectionStrategy.Default, ...c }), Directive, undefined, (type, meta) => compileComponent(type, meta));
  34293. /**
  34294. * @Annotation
  34295. * @publicApi
  34296. */
  34297. const Pipe = makeDecorator('Pipe', (p) => ({ pure: true, ...p }), undefined, undefined, (type, meta) => compilePipe(type, meta));
  34298. /**
  34299. * @Annotation
  34300. * @publicApi
  34301. */
  34302. const Input = makePropDecorator('Input', (arg) => {
  34303. if (!arg) {
  34304. return {};
  34305. }
  34306. return typeof arg === 'string' ? { alias: arg } : arg;
  34307. });
  34308. /**
  34309. * @Annotation
  34310. * @publicApi
  34311. */
  34312. const Output = makePropDecorator('Output', (alias) => ({ alias }));
  34313. /**
  34314. * @Annotation
  34315. * @publicApi
  34316. */
  34317. const HostBinding = makePropDecorator('HostBinding', (hostPropertyName) => ({ hostPropertyName }));
  34318. /**
  34319. * @Annotation
  34320. * @publicApi
  34321. */
  34322. const HostListener = makePropDecorator('HostListener', (eventName, args) => ({ eventName, args }));
  34323. /**
  34324. * @Annotation
  34325. */
  34326. const NgModule = makeDecorator('NgModule', (ngModule) => ngModule, undefined, undefined,
  34327. /**
  34328. * Decorator that marks the following class as an NgModule, and supplies
  34329. * configuration metadata for it.
  34330. *
  34331. * * The `declarations` option configures the compiler
  34332. * with information about what belongs to the NgModule.
  34333. * * The `providers` options configures the NgModule's injector to provide
  34334. * dependencies the NgModule members.
  34335. * * The `imports` and `exports` options bring in members from other modules, and make
  34336. * this module's members available to others.
  34337. */
  34338. (type, meta) => compileNgModule(type, meta));
  34339. /**
  34340. * @description Represents the version of Angular
  34341. *
  34342. * @publicApi
  34343. */
  34344. class Version {
  34345. full;
  34346. major;
  34347. minor;
  34348. patch;
  34349. constructor(full) {
  34350. this.full = full;
  34351. const parts = full.split('.');
  34352. this.major = parts[0];
  34353. this.minor = parts[1];
  34354. this.patch = parts.slice(2).join('.');
  34355. }
  34356. }
  34357. /**
  34358. * @publicApi
  34359. */
  34360. const VERSION = new Version('19.2.4');
  34361. /**
  34362. * Combination of NgModuleFactory and ComponentFactories.
  34363. *
  34364. * @publicApi
  34365. *
  34366. * @deprecated
  34367. * Ivy JIT mode doesn't require accessing this symbol.
  34368. */
  34369. class ModuleWithComponentFactories {
  34370. ngModuleFactory;
  34371. componentFactories;
  34372. constructor(ngModuleFactory, componentFactories) {
  34373. this.ngModuleFactory = ngModuleFactory;
  34374. this.componentFactories = componentFactories;
  34375. }
  34376. }
  34377. /**
  34378. * Low-level service for running the angular compiler during runtime
  34379. * to create {@link ComponentFactory}s, which
  34380. * can later be used to create and render a Component instance.
  34381. *
  34382. * Each `@NgModule` provides an own `Compiler` to its injector,
  34383. * that will use the directives/pipes of the ng module for compilation
  34384. * of components.
  34385. *
  34386. * @publicApi
  34387. *
  34388. * @deprecated
  34389. * Ivy JIT mode doesn't require accessing this symbol.
  34390. */
  34391. class Compiler {
  34392. /**
  34393. * Compiles the given NgModule and all of its components. All templates of the components
  34394. * have to be inlined.
  34395. */
  34396. compileModuleSync(moduleType) {
  34397. return new NgModuleFactory(moduleType);
  34398. }
  34399. /**
  34400. * Compiles the given NgModule and all of its components
  34401. */
  34402. compileModuleAsync(moduleType) {
  34403. return Promise.resolve(this.compileModuleSync(moduleType));
  34404. }
  34405. /**
  34406. * Same as {@link Compiler#compileModuleSync compileModuleSync} but also creates ComponentFactories for all components.
  34407. */
  34408. compileModuleAndAllComponentsSync(moduleType) {
  34409. const ngModuleFactory = this.compileModuleSync(moduleType);
  34410. const moduleDef = getNgModuleDef(moduleType);
  34411. const componentFactories = maybeUnwrapFn(moduleDef.declarations).reduce((factories, declaration) => {
  34412. const componentDef = getComponentDef(declaration);
  34413. componentDef && factories.push(new ComponentFactory(componentDef));
  34414. return factories;
  34415. }, []);
  34416. return new ModuleWithComponentFactories(ngModuleFactory, componentFactories);
  34417. }
  34418. /**
  34419. * Same as {@link Compiler#compileModuleAsync compileModuleAsync} but also creates ComponentFactories for all components.
  34420. */
  34421. compileModuleAndAllComponentsAsync(moduleType) {
  34422. return Promise.resolve(this.compileModuleAndAllComponentsSync(moduleType));
  34423. }
  34424. /**
  34425. * Clears all caches.
  34426. */
  34427. clearCache() { }
  34428. /**
  34429. * Clears the cache for the given component/ngModule.
  34430. */
  34431. clearCacheFor(type) { }
  34432. /**
  34433. * Returns the id for a given NgModule, if one is defined and known to the compiler.
  34434. */
  34435. getModuleId(moduleType) {
  34436. return undefined;
  34437. }
  34438. static ɵfac = function Compiler_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || Compiler)(); };
  34439. static ɵprov = /*@__PURE__*/ ɵɵdefineInjectable({ token: Compiler, factory: Compiler.ɵfac, providedIn: 'root' });
  34440. }
  34441. (() => { (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(Compiler, [{
  34442. type: Injectable,
  34443. args: [{ providedIn: 'root' }]
  34444. }], null, null); })();
  34445. /**
  34446. * Token to provide CompilerOptions in the platform injector.
  34447. *
  34448. * @publicApi
  34449. */
  34450. const COMPILER_OPTIONS = new InjectionToken(ngDevMode ? 'compilerOptions' : '');
  34451. /**
  34452. * A factory for creating a Compiler
  34453. *
  34454. * @publicApi
  34455. *
  34456. * @deprecated
  34457. * Ivy JIT mode doesn't require accessing this symbol.
  34458. */
  34459. class CompilerFactory {
  34460. }
  34461. function compileNgModuleFactory(injector, options, moduleType) {
  34462. ngDevMode && assertNgModuleType(moduleType);
  34463. const moduleFactory = new NgModuleFactory(moduleType);
  34464. // All of the logic below is irrelevant for AOT-compiled code.
  34465. if (typeof ngJitMode !== 'undefined' && !ngJitMode) {
  34466. return Promise.resolve(moduleFactory);
  34467. }
  34468. const compilerOptions = injector.get(COMPILER_OPTIONS, []).concat(options);
  34469. // Configure the compiler to use the provided options. This call may fail when multiple modules
  34470. // are bootstrapped with incompatible options, as a component can only be compiled according to
  34471. // a single set of options.
  34472. setJitOptions({
  34473. defaultEncapsulation: _lastDefined(compilerOptions.map((opts) => opts.defaultEncapsulation)),
  34474. preserveWhitespaces: _lastDefined(compilerOptions.map((opts) => opts.preserveWhitespaces)),
  34475. });
  34476. if (isComponentResourceResolutionQueueEmpty()) {
  34477. return Promise.resolve(moduleFactory);
  34478. }
  34479. const compilerProviders = compilerOptions.flatMap((option) => option.providers ?? []);
  34480. // In case there are no compiler providers, we just return the module factory as
  34481. // there won't be any resource loader. This can happen with Ivy, because AOT compiled
  34482. // modules can be still passed through "bootstrapModule". In that case we shouldn't
  34483. // unnecessarily require the JIT compiler.
  34484. if (compilerProviders.length === 0) {
  34485. return Promise.resolve(moduleFactory);
  34486. }
  34487. const compiler = getCompilerFacade({
  34488. usage: 0 /* JitCompilerUsage.Decorator */,
  34489. kind: 'NgModule',
  34490. type: moduleType,
  34491. });
  34492. const compilerInjector = Injector.create({ providers: compilerProviders });
  34493. const resourceLoader = compilerInjector.get(compiler.ResourceLoader);
  34494. // The resource loader can also return a string while the "resolveComponentResources"
  34495. // always expects a promise. Therefore we need to wrap the returned value in a promise.
  34496. return resolveComponentResources((url) => Promise.resolve(resourceLoader.get(url))).then(() => moduleFactory);
  34497. }
  34498. function _lastDefined(args) {
  34499. for (let i = args.length - 1; i >= 0; i--) {
  34500. if (args[i] !== undefined) {
  34501. return args[i];
  34502. }
  34503. }
  34504. return undefined;
  34505. }
  34506. class NgZoneChangeDetectionScheduler {
  34507. zone = inject(NgZone);
  34508. changeDetectionScheduler = inject(ChangeDetectionScheduler);
  34509. applicationRef = inject(ApplicationRef);
  34510. _onMicrotaskEmptySubscription;
  34511. initialize() {
  34512. if (this._onMicrotaskEmptySubscription) {
  34513. return;
  34514. }
  34515. this._onMicrotaskEmptySubscription = this.zone.onMicrotaskEmpty.subscribe({
  34516. next: () => {
  34517. // `onMicroTaskEmpty` can happen _during_ the zoneless scheduler change detection because
  34518. // zone.run(() => {}) will result in `checkStable` at the end of the `zone.run` closure
  34519. // and emit `onMicrotaskEmpty` synchronously if run coalsecing is false.
  34520. if (this.changeDetectionScheduler.runningTick) {
  34521. return;
  34522. }
  34523. this.zone.run(() => {
  34524. this.applicationRef.tick();
  34525. });
  34526. },
  34527. });
  34528. }
  34529. ngOnDestroy() {
  34530. this._onMicrotaskEmptySubscription?.unsubscribe();
  34531. }
  34532. static ɵfac = function NgZoneChangeDetectionScheduler_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || NgZoneChangeDetectionScheduler)(); };
  34533. static ɵprov = /*@__PURE__*/ ɵɵdefineInjectable({ token: NgZoneChangeDetectionScheduler, factory: NgZoneChangeDetectionScheduler.ɵfac, providedIn: 'root' });
  34534. }
  34535. (() => { (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(NgZoneChangeDetectionScheduler, [{
  34536. type: Injectable,
  34537. args: [{ providedIn: 'root' }]
  34538. }], null, null); })();
  34539. /**
  34540. * Internal token used to verify that `provideZoneChangeDetection` is not used
  34541. * with the bootstrapModule API.
  34542. */
  34543. const PROVIDED_NG_ZONE = new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'provideZoneChangeDetection token' : '', { factory: () => false });
  34544. function internalProvideZoneChangeDetection({ ngZoneFactory, ignoreChangesOutsideZone, scheduleInRootZone, }) {
  34545. ngZoneFactory ??= () => new NgZone({ ...getNgZoneOptions(), scheduleInRootZone });
  34546. return [
  34547. { provide: NgZone, useFactory: ngZoneFactory },
  34548. {
  34549. provide: ENVIRONMENT_INITIALIZER,
  34550. multi: true,
  34551. useFactory: () => {
  34552. const ngZoneChangeDetectionScheduler = inject(NgZoneChangeDetectionScheduler, {
  34553. optional: true,
  34554. });
  34555. if ((typeof ngDevMode === 'undefined' || ngDevMode) &&
  34556. ngZoneChangeDetectionScheduler === null) {
  34557. throw new RuntimeError(402 /* RuntimeErrorCode.MISSING_REQUIRED_INJECTABLE_IN_BOOTSTRAP */, `A required Injectable was not found in the dependency injection tree. ` +
  34558. 'If you are bootstrapping an NgModule, make sure that the `BrowserModule` is imported.');
  34559. }
  34560. return () => ngZoneChangeDetectionScheduler.initialize();
  34561. },
  34562. },
  34563. {
  34564. provide: ENVIRONMENT_INITIALIZER,
  34565. multi: true,
  34566. useFactory: () => {
  34567. const service = inject(ZoneStablePendingTask);
  34568. return () => {
  34569. service.initialize();
  34570. };
  34571. },
  34572. },
  34573. // Always disable scheduler whenever explicitly disabled, even if another place called
  34574. // `provideZoneChangeDetection` without the 'ignore' option.
  34575. ignoreChangesOutsideZone === true ? { provide: ZONELESS_SCHEDULER_DISABLED, useValue: true } : [],
  34576. {
  34577. provide: SCHEDULE_IN_ROOT_ZONE,
  34578. useValue: scheduleInRootZone ?? SCHEDULE_IN_ROOT_ZONE_DEFAULT,
  34579. },
  34580. ];
  34581. }
  34582. /**
  34583. * Provides `NgZone`-based change detection for the application bootstrapped using
  34584. * `bootstrapApplication`.
  34585. *
  34586. * `NgZone` is already provided in applications by default. This provider allows you to configure
  34587. * options like `eventCoalescing` in the `NgZone`.
  34588. * This provider is not available for `platformBrowser().bootstrapModule`, which uses
  34589. * `BootstrapOptions` instead.
  34590. *
  34591. * @usageNotes
  34592. * ```ts
  34593. * bootstrapApplication(MyApp, {providers: [
  34594. * provideZoneChangeDetection({eventCoalescing: true}),
  34595. * ]});
  34596. * ```
  34597. *
  34598. * @publicApi
  34599. * @see {@link /api/platform-browser/bootstrapApplication bootstrapApplication}
  34600. * @see {@link NgZoneOptions}
  34601. */
  34602. function provideZoneChangeDetection(options) {
  34603. const ignoreChangesOutsideZone = options?.ignoreChangesOutsideZone;
  34604. const scheduleInRootZone = options?.scheduleInRootZone;
  34605. const zoneProviders = internalProvideZoneChangeDetection({
  34606. ngZoneFactory: () => {
  34607. const ngZoneOptions = getNgZoneOptions(options);
  34608. ngZoneOptions.scheduleInRootZone = scheduleInRootZone;
  34609. if (ngZoneOptions.shouldCoalesceEventChangeDetection) {
  34610. performanceMarkFeature('NgZone_CoalesceEvent');
  34611. }
  34612. return new NgZone(ngZoneOptions);
  34613. },
  34614. ignoreChangesOutsideZone,
  34615. scheduleInRootZone,
  34616. });
  34617. return makeEnvironmentProviders([
  34618. { provide: PROVIDED_NG_ZONE, useValue: true },
  34619. { provide: ZONELESS_ENABLED, useValue: false },
  34620. zoneProviders,
  34621. ]);
  34622. }
  34623. // Transforms a set of `BootstrapOptions` (supported by the NgModule-based bootstrap APIs) ->
  34624. // `NgZoneOptions` that are recognized by the NgZone constructor. Passing no options will result in
  34625. // a set of default options returned.
  34626. function getNgZoneOptions(options) {
  34627. return {
  34628. enableLongStackTrace: typeof ngDevMode === 'undefined' ? false : !!ngDevMode,
  34629. shouldCoalesceEventChangeDetection: options?.eventCoalescing ?? false,
  34630. shouldCoalesceRunChangeDetection: options?.runCoalescing ?? false,
  34631. };
  34632. }
  34633. class ZoneStablePendingTask {
  34634. subscription = new Subscription();
  34635. initialized = false;
  34636. zone = inject(NgZone);
  34637. pendingTasks = inject(PendingTasksInternal);
  34638. initialize() {
  34639. if (this.initialized) {
  34640. return;
  34641. }
  34642. this.initialized = true;
  34643. let task = null;
  34644. if (!this.zone.isStable && !this.zone.hasPendingMacrotasks && !this.zone.hasPendingMicrotasks) {
  34645. task = this.pendingTasks.add();
  34646. }
  34647. this.zone.runOutsideAngular(() => {
  34648. this.subscription.add(this.zone.onStable.subscribe(() => {
  34649. NgZone.assertNotInAngularZone();
  34650. // Check whether there are no pending macro/micro tasks in the next tick
  34651. // to allow for NgZone to update the state.
  34652. queueMicrotask(() => {
  34653. if (task !== null &&
  34654. !this.zone.hasPendingMacrotasks &&
  34655. !this.zone.hasPendingMicrotasks) {
  34656. this.pendingTasks.remove(task);
  34657. task = null;
  34658. }
  34659. });
  34660. }));
  34661. });
  34662. this.subscription.add(this.zone.onUnstable.subscribe(() => {
  34663. NgZone.assertInAngularZone();
  34664. task ??= this.pendingTasks.add();
  34665. }));
  34666. }
  34667. ngOnDestroy() {
  34668. this.subscription.unsubscribe();
  34669. }
  34670. static ɵfac = function ZoneStablePendingTask_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || ZoneStablePendingTask)(); };
  34671. static ɵprov = /*@__PURE__*/ ɵɵdefineInjectable({ token: ZoneStablePendingTask, factory: ZoneStablePendingTask.ɵfac, providedIn: 'root' });
  34672. }
  34673. (() => { (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(ZoneStablePendingTask, [{
  34674. type: Injectable,
  34675. args: [{ providedIn: 'root' }]
  34676. }], null, null); })();
  34677. const CONSECUTIVE_MICROTASK_NOTIFICATION_LIMIT = 100;
  34678. let consecutiveMicrotaskNotifications = 0;
  34679. let stackFromLastFewNotifications = [];
  34680. function trackMicrotaskNotificationForDebugging() {
  34681. consecutiveMicrotaskNotifications++;
  34682. if (CONSECUTIVE_MICROTASK_NOTIFICATION_LIMIT - consecutiveMicrotaskNotifications < 5) {
  34683. const stack = new Error().stack;
  34684. if (stack) {
  34685. stackFromLastFewNotifications.push(stack);
  34686. }
  34687. }
  34688. if (consecutiveMicrotaskNotifications === CONSECUTIVE_MICROTASK_NOTIFICATION_LIMIT) {
  34689. throw new RuntimeError(103 /* RuntimeErrorCode.INFINITE_CHANGE_DETECTION */, 'Angular could not stabilize because there were endless change notifications within the browser event loop. ' +
  34690. 'The stack from the last several notifications: \n' +
  34691. stackFromLastFewNotifications.join('\n'));
  34692. }
  34693. }
  34694. class ChangeDetectionSchedulerImpl {
  34695. appRef = inject(ApplicationRef);
  34696. taskService = inject(PendingTasksInternal);
  34697. ngZone = inject(NgZone);
  34698. zonelessEnabled = inject(ZONELESS_ENABLED);
  34699. tracing = inject(TracingService, { optional: true });
  34700. disableScheduling = inject(ZONELESS_SCHEDULER_DISABLED, { optional: true }) ?? false;
  34701. zoneIsDefined = typeof Zone !== 'undefined' && !!Zone.root.run;
  34702. schedulerTickApplyArgs = [{ data: { '__scheduler_tick__': true } }];
  34703. subscriptions = new Subscription();
  34704. angularZoneId = this.zoneIsDefined
  34705. ? this.ngZone._inner?.get(angularZoneInstanceIdProperty)
  34706. : null;
  34707. scheduleInRootZone = !this.zonelessEnabled &&
  34708. this.zoneIsDefined &&
  34709. (inject(SCHEDULE_IN_ROOT_ZONE, { optional: true }) ?? false);
  34710. cancelScheduledCallback = null;
  34711. useMicrotaskScheduler = false;
  34712. runningTick = false;
  34713. pendingRenderTaskId = null;
  34714. constructor() {
  34715. this.subscriptions.add(this.appRef.afterTick.subscribe(() => {
  34716. // If the scheduler isn't running a tick but the application ticked, that means
  34717. // someone called ApplicationRef.tick manually. In this case, we should cancel
  34718. // any change detections that had been scheduled so we don't run an extra one.
  34719. if (!this.runningTick) {
  34720. this.cleanup();
  34721. }
  34722. }));
  34723. this.subscriptions.add(this.ngZone.onUnstable.subscribe(() => {
  34724. // If the zone becomes unstable when we're not running tick (this happens from the zone.run),
  34725. // we should cancel any scheduled change detection here because at this point we
  34726. // know that the zone will stabilize at some point and run change detection itself.
  34727. if (!this.runningTick) {
  34728. this.cleanup();
  34729. }
  34730. }));
  34731. // TODO(atscott): These conditions will need to change when zoneless is the default
  34732. // Instead, they should flip to checking if ZoneJS scheduling is provided
  34733. this.disableScheduling ||=
  34734. !this.zonelessEnabled &&
  34735. // NoopNgZone without enabling zoneless means no scheduling whatsoever
  34736. (this.ngZone instanceof NoopNgZone ||
  34737. // The same goes for the lack of Zone without enabling zoneless scheduling
  34738. !this.zoneIsDefined);
  34739. }
  34740. notify(source) {
  34741. if (!this.zonelessEnabled && source === 5 /* NotificationSource.Listener */) {
  34742. // When the notification comes from a listener, we skip the notification unless the
  34743. // application has enabled zoneless. Ideally, listeners wouldn't notify the scheduler at all
  34744. // automatically. We do not know that a developer made a change in the listener callback that
  34745. // requires an `ApplicationRef.tick` (synchronize templates / run render hooks). We do this
  34746. // only for an easier migration from OnPush components to zoneless. Because listeners are
  34747. // usually executed inside the Angular zone and listeners automatically call `markViewDirty`,
  34748. // developers never needed to manually use `ChangeDetectorRef.markForCheck` or some other API
  34749. // to make listener callbacks work correctly with `OnPush` components.
  34750. return;
  34751. }
  34752. let force = false;
  34753. switch (source) {
  34754. case 0 /* NotificationSource.MarkAncestorsForTraversal */: {
  34755. this.appRef.dirtyFlags |= 2 /* ApplicationRefDirtyFlags.ViewTreeTraversal */;
  34756. break;
  34757. }
  34758. case 3 /* NotificationSource.DebugApplyChanges */:
  34759. case 2 /* NotificationSource.DeferBlockStateUpdate */:
  34760. case 4 /* NotificationSource.MarkForCheck */:
  34761. case 5 /* NotificationSource.Listener */:
  34762. case 1 /* NotificationSource.SetInput */: {
  34763. this.appRef.dirtyFlags |= 4 /* ApplicationRefDirtyFlags.ViewTreeCheck */;
  34764. break;
  34765. }
  34766. case 6 /* NotificationSource.CustomElement */: {
  34767. // We use `ViewTreeTraversal` to ensure we refresh the element even if this is triggered
  34768. // during CD. In practice this is a no-op since the elements code also calls via a
  34769. // `markForRefresh()` API which sends `NotificationSource.MarkAncestorsForTraversal` anyway.
  34770. this.appRef.dirtyFlags |= 2 /* ApplicationRefDirtyFlags.ViewTreeTraversal */;
  34771. force = true;
  34772. break;
  34773. }
  34774. case 12 /* NotificationSource.RootEffect */: {
  34775. this.appRef.dirtyFlags |= 16 /* ApplicationRefDirtyFlags.RootEffects */;
  34776. // Root effects still force a CD, even if the scheduler is disabled. This ensures that
  34777. // effects always run, even when triggered from outside the zone when the scheduler is
  34778. // otherwise disabled.
  34779. force = true;
  34780. break;
  34781. }
  34782. case 13 /* NotificationSource.ViewEffect */: {
  34783. // This is technically a no-op, since view effects will also send a
  34784. // `MarkAncestorsForTraversal` notification. Still, we set this for logical consistency.
  34785. this.appRef.dirtyFlags |= 2 /* ApplicationRefDirtyFlags.ViewTreeTraversal */;
  34786. // View effects still force a CD, even if the scheduler is disabled. This ensures that
  34787. // effects always run, even when triggered from outside the zone when the scheduler is
  34788. // otherwise disabled.
  34789. force = true;
  34790. break;
  34791. }
  34792. case 11 /* NotificationSource.PendingTaskRemoved */: {
  34793. // Removing a pending task via the public API forces a scheduled tick, ensuring that
  34794. // stability is async and delayed until there was at least an opportunity to run
  34795. // application synchronization. This prevents some footguns when working with the
  34796. // public API for pending tasks where developers attempt to update application state
  34797. // immediately after removing the last task.
  34798. force = true;
  34799. break;
  34800. }
  34801. case 9 /* NotificationSource.ViewDetachedFromDOM */:
  34802. case 8 /* NotificationSource.ViewAttached */:
  34803. case 7 /* NotificationSource.RenderHook */:
  34804. case 10 /* NotificationSource.AsyncAnimationsLoaded */:
  34805. default: {
  34806. // These notifications only schedule a tick but do not change whether we should refresh
  34807. // views. Instead, we only need to run render hooks unless another notification from the
  34808. // other set is also received before `tick` happens.
  34809. this.appRef.dirtyFlags |= 8 /* ApplicationRefDirtyFlags.AfterRender */;
  34810. }
  34811. }
  34812. // If not already defined, attempt to capture a tracing snapshot of this
  34813. // notification so that the resulting CD run can be attributed to the
  34814. // context which produced the notification.
  34815. this.appRef.tracingSnapshot = this.tracing?.snapshot(this.appRef.tracingSnapshot) ?? null;
  34816. if (!this.shouldScheduleTick(force)) {
  34817. return;
  34818. }
  34819. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  34820. if (this.useMicrotaskScheduler) {
  34821. trackMicrotaskNotificationForDebugging();
  34822. }
  34823. else {
  34824. consecutiveMicrotaskNotifications = 0;
  34825. stackFromLastFewNotifications.length = 0;
  34826. }
  34827. }
  34828. const scheduleCallback = this.useMicrotaskScheduler
  34829. ? scheduleCallbackWithMicrotask
  34830. : scheduleCallbackWithRafRace;
  34831. this.pendingRenderTaskId = this.taskService.add();
  34832. if (this.scheduleInRootZone) {
  34833. this.cancelScheduledCallback = Zone.root.run(() => scheduleCallback(() => this.tick()));
  34834. }
  34835. else {
  34836. this.cancelScheduledCallback = this.ngZone.runOutsideAngular(() => scheduleCallback(() => this.tick()));
  34837. }
  34838. }
  34839. shouldScheduleTick(force) {
  34840. if ((this.disableScheduling && !force) || this.appRef.destroyed) {
  34841. return false;
  34842. }
  34843. // already scheduled or running
  34844. if (this.pendingRenderTaskId !== null || this.runningTick || this.appRef._runningTick) {
  34845. return false;
  34846. }
  34847. // If we're inside the zone don't bother with scheduler. Zone will stabilize
  34848. // eventually and run change detection.
  34849. if (!this.zonelessEnabled &&
  34850. this.zoneIsDefined &&
  34851. Zone.current.get(angularZoneInstanceIdProperty + this.angularZoneId)) {
  34852. return false;
  34853. }
  34854. return true;
  34855. }
  34856. /**
  34857. * Calls ApplicationRef._tick inside the `NgZone`.
  34858. *
  34859. * Calling `tick` directly runs change detection and cancels any change detection that had been
  34860. * scheduled previously.
  34861. *
  34862. * @param shouldRefreshViews Passed directly to `ApplicationRef._tick` and skips straight to
  34863. * render hooks when `false`.
  34864. */
  34865. tick() {
  34866. // When ngZone.run below exits, onMicrotaskEmpty may emit if the zone is
  34867. // stable. We want to prevent double ticking so we track whether the tick is
  34868. // already running and skip it if so.
  34869. if (this.runningTick || this.appRef.destroyed) {
  34870. return;
  34871. }
  34872. // If we reach the tick and there is no work to be done in ApplicationRef.tick,
  34873. // skip it altogether and clean up. There may be no work if, for example, the only
  34874. // event that notified the scheduler was the removal of a pending task.
  34875. if (this.appRef.dirtyFlags === 0 /* ApplicationRefDirtyFlags.None */) {
  34876. this.cleanup();
  34877. return;
  34878. }
  34879. // The scheduler used to pass "whether to check views" as a boolean flag instead of setting
  34880. // fine-grained dirtiness flags, and global checking was always used on the first pass. This
  34881. // created an interesting edge case: if a notification made a view dirty and then ticked via the
  34882. // scheduler (and not the zone) a global check was still performed.
  34883. //
  34884. // Ideally, this would not be the case, and only zone-based ticks would do global passes.
  34885. // However this is a breaking change and requires fixes in g3. Until this cleanup can be done,
  34886. // we add the `ViewTreeGlobal` flag to request a global check if any views are dirty in a
  34887. // scheduled tick (unless zoneless is enabled, in which case global checks aren't really a
  34888. // thing).
  34889. //
  34890. // TODO(alxhub): clean up and remove this workaround as a breaking change.
  34891. if (!this.zonelessEnabled && this.appRef.dirtyFlags & 7 /* ApplicationRefDirtyFlags.ViewTreeAny */) {
  34892. this.appRef.dirtyFlags |= 1 /* ApplicationRefDirtyFlags.ViewTreeGlobal */;
  34893. }
  34894. const task = this.taskService.add();
  34895. try {
  34896. this.ngZone.run(() => {
  34897. this.runningTick = true;
  34898. this.appRef._tick();
  34899. }, undefined, this.schedulerTickApplyArgs);
  34900. }
  34901. catch (e) {
  34902. this.taskService.remove(task);
  34903. throw e;
  34904. }
  34905. finally {
  34906. this.cleanup();
  34907. }
  34908. // If we're notified of a change within 1 microtask of running change
  34909. // detection, run another round in the same event loop. This allows code
  34910. // which uses Promise.resolve (see NgModel) to avoid
  34911. // ExpressionChanged...Error to still be reflected in a single browser
  34912. // paint, even if that spans multiple rounds of change detection.
  34913. this.useMicrotaskScheduler = true;
  34914. scheduleCallbackWithMicrotask(() => {
  34915. this.useMicrotaskScheduler = false;
  34916. this.taskService.remove(task);
  34917. });
  34918. }
  34919. ngOnDestroy() {
  34920. this.subscriptions.unsubscribe();
  34921. this.cleanup();
  34922. }
  34923. cleanup() {
  34924. this.runningTick = false;
  34925. this.cancelScheduledCallback?.();
  34926. this.cancelScheduledCallback = null;
  34927. // If this is the last task, the service will synchronously emit a stable
  34928. // notification. If there is a subscriber that then acts in a way that
  34929. // tries to notify the scheduler again, we need to be able to respond to
  34930. // schedule a new change detection. Therefore, we should clear the task ID
  34931. // before removing it from the pending tasks (or the tasks service should
  34932. // not synchronously emit stable, similar to how Zone stableness only
  34933. // happens if it's still stable after a microtask).
  34934. if (this.pendingRenderTaskId !== null) {
  34935. const taskId = this.pendingRenderTaskId;
  34936. this.pendingRenderTaskId = null;
  34937. this.taskService.remove(taskId);
  34938. }
  34939. }
  34940. static ɵfac = function ChangeDetectionSchedulerImpl_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || ChangeDetectionSchedulerImpl)(); };
  34941. static ɵprov = /*@__PURE__*/ ɵɵdefineInjectable({ token: ChangeDetectionSchedulerImpl, factory: ChangeDetectionSchedulerImpl.ɵfac, providedIn: 'root' });
  34942. }
  34943. (() => { (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(ChangeDetectionSchedulerImpl, [{
  34944. type: Injectable,
  34945. args: [{ providedIn: 'root' }]
  34946. }], () => [], null); })();
  34947. /**
  34948. * Provides change detection without ZoneJS for the application bootstrapped using
  34949. * `bootstrapApplication`.
  34950. *
  34951. * This function allows you to configure the application to not use the state/state changes of
  34952. * ZoneJS to schedule change detection in the application. This will work when ZoneJS is not present
  34953. * on the page at all or if it exists because something else is using it (either another Angular
  34954. * application which uses ZoneJS for scheduling or some other library that relies on ZoneJS).
  34955. *
  34956. * This can also be added to the `TestBed` providers to configure the test environment to more
  34957. * closely match production behavior. This will help give higher confidence that components are
  34958. * compatible with zoneless change detection.
  34959. *
  34960. * ZoneJS uses browser events to trigger change detection. When using this provider, Angular will
  34961. * instead use Angular APIs to schedule change detection. These APIs include:
  34962. *
  34963. * - `ChangeDetectorRef.markForCheck`
  34964. * - `ComponentRef.setInput`
  34965. * - updating a signal that is read in a template
  34966. * - when bound host or template listeners are triggered
  34967. * - attaching a view that was marked dirty by one of the above
  34968. * - removing a view
  34969. * - registering a render hook (templates are only refreshed if render hooks do one of the above)
  34970. *
  34971. * @usageNotes
  34972. * ```ts
  34973. * bootstrapApplication(MyApp, {providers: [
  34974. * provideExperimentalZonelessChangeDetection(),
  34975. * ]});
  34976. * ```
  34977. *
  34978. * This API is experimental. Neither the shape, nor the underlying behavior is stable and can change
  34979. * in patch versions. There are known feature gaps and API ergonomic considerations. We will iterate
  34980. * on the exact API based on the feedback and our understanding of the problem and solution space.
  34981. *
  34982. * @publicApi
  34983. * @experimental
  34984. * @see {@link /api/platform-browser/bootstrapApplication bootstrapApplication}
  34985. */
  34986. function provideExperimentalZonelessChangeDetection() {
  34987. performanceMarkFeature('NgZoneless');
  34988. if ((typeof ngDevMode === 'undefined' || ngDevMode) && typeof Zone !== 'undefined' && Zone) {
  34989. const message = formatRuntimeError(914 /* RuntimeErrorCode.UNEXPECTED_ZONEJS_PRESENT_IN_ZONELESS_MODE */, `The application is using zoneless change detection, but is still loading Zone.js. ` +
  34990. `Consider removing Zone.js to get the full benefits of zoneless. ` +
  34991. `In applications using the Angular CLI, Zone.js is typically included in the "polyfills" section of the angular.json file.`);
  34992. console.warn(message);
  34993. }
  34994. return makeEnvironmentProviders([
  34995. { provide: ChangeDetectionScheduler, useExisting: ChangeDetectionSchedulerImpl },
  34996. { provide: NgZone, useClass: NoopNgZone },
  34997. { provide: ZONELESS_ENABLED, useValue: true },
  34998. { provide: SCHEDULE_IN_ROOT_ZONE, useValue: false },
  34999. typeof ngDevMode === 'undefined' || ngDevMode
  35000. ? [{ provide: PROVIDED_ZONELESS, useValue: true }]
  35001. : [],
  35002. ]);
  35003. }
  35004. /**
  35005. * Work out the locale from the potential global properties.
  35006. *
  35007. * * Closure Compiler: use `goog.LOCALE`.
  35008. * * Ivy enabled: use `$localize.locale`
  35009. */
  35010. function getGlobalLocale() {
  35011. if (typeof ngI18nClosureMode !== 'undefined' &&
  35012. ngI18nClosureMode &&
  35013. typeof goog !== 'undefined' &&
  35014. goog.LOCALE !== 'en') {
  35015. // * The default `goog.LOCALE` value is `en`, while Angular used `en-US`.
  35016. // * In order to preserve backwards compatibility, we use Angular default value over
  35017. // Closure Compiler's one.
  35018. return goog.LOCALE;
  35019. }
  35020. else {
  35021. // KEEP `typeof $localize !== 'undefined' && $localize.locale` IN SYNC WITH THE LOCALIZE
  35022. // COMPILE-TIME INLINER.
  35023. //
  35024. // * During compile time inlining of translations the expression will be replaced
  35025. // with a string literal that is the current locale. Other forms of this expression are not
  35026. // guaranteed to be replaced.
  35027. //
  35028. // * During runtime translation evaluation, the developer is required to set `$localize.locale`
  35029. // if required, or just to provide their own `LOCALE_ID` provider.
  35030. return (typeof $localize !== 'undefined' && $localize.locale) || DEFAULT_LOCALE_ID;
  35031. }
  35032. }
  35033. /**
  35034. * Provide this token to set the locale of your application.
  35035. * It is used for i18n extraction, by i18n pipes (DatePipe, I18nPluralPipe, CurrencyPipe,
  35036. * DecimalPipe and PercentPipe) and by ICU expressions.
  35037. *
  35038. * See the [i18n guide](guide/i18n/locale-id) for more information.
  35039. *
  35040. * @usageNotes
  35041. * ### Example
  35042. *
  35043. * ```ts
  35044. * import { LOCALE_ID } from '@angular/core';
  35045. * import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
  35046. * import { AppModule } from './app/app.module';
  35047. *
  35048. * platformBrowserDynamic().bootstrapModule(AppModule, {
  35049. * providers: [{provide: LOCALE_ID, useValue: 'en-US' }]
  35050. * });
  35051. * ```
  35052. *
  35053. * @publicApi
  35054. */
  35055. const LOCALE_ID = new InjectionToken(ngDevMode ? 'LocaleId' : '', {
  35056. providedIn: 'root',
  35057. factory: () => inject(LOCALE_ID, InjectFlags.Optional | InjectFlags.SkipSelf) || getGlobalLocale(),
  35058. });
  35059. /**
  35060. * Provide this token to set the default currency code your application uses for
  35061. * CurrencyPipe when there is no currency code passed into it. This is only used by
  35062. * CurrencyPipe and has no relation to locale currency. Defaults to USD if not configured.
  35063. *
  35064. * See the [i18n guide](guide/i18n/locale-id) for more information.
  35065. *
  35066. * <div class="docs-alert docs-alert-helpful">
  35067. *
  35068. * The default currency code is currently always `USD`.
  35069. *
  35070. * If you need the previous behavior then set it by creating a `DEFAULT_CURRENCY_CODE` provider in
  35071. * your application `NgModule`:
  35072. *
  35073. * ```ts
  35074. * {provide: DEFAULT_CURRENCY_CODE, useValue: 'USD'}
  35075. * ```
  35076. *
  35077. * </div>
  35078. *
  35079. * @usageNotes
  35080. * ### Example
  35081. *
  35082. * ```ts
  35083. * import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
  35084. * import { AppModule } from './app/app.module';
  35085. *
  35086. * platformBrowserDynamic().bootstrapModule(AppModule, {
  35087. * providers: [{provide: DEFAULT_CURRENCY_CODE, useValue: 'EUR' }]
  35088. * });
  35089. * ```
  35090. *
  35091. * @publicApi
  35092. */
  35093. const DEFAULT_CURRENCY_CODE = new InjectionToken(ngDevMode ? 'DefaultCurrencyCode' : '', {
  35094. providedIn: 'root',
  35095. factory: () => USD_CURRENCY_CODE,
  35096. });
  35097. /**
  35098. * Use this token at bootstrap to provide the content of your translation file (`xtb`,
  35099. * `xlf` or `xlf2`) when you want to translate your application in another language.
  35100. *
  35101. * See the [i18n guide](guide/i18n/merge) for more information.
  35102. *
  35103. * @usageNotes
  35104. * ### Example
  35105. *
  35106. * ```ts
  35107. * import { TRANSLATIONS } from '@angular/core';
  35108. * import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
  35109. * import { AppModule } from './app/app.module';
  35110. *
  35111. * // content of your translation file
  35112. * const translations = '....';
  35113. *
  35114. * platformBrowserDynamic().bootstrapModule(AppModule, {
  35115. * providers: [{provide: TRANSLATIONS, useValue: translations }]
  35116. * });
  35117. * ```
  35118. *
  35119. * @publicApi
  35120. */
  35121. const TRANSLATIONS = new InjectionToken(ngDevMode ? 'Translations' : '');
  35122. /**
  35123. * Provide this token at bootstrap to set the format of your {@link TRANSLATIONS}: `xtb`,
  35124. * `xlf` or `xlf2`.
  35125. *
  35126. * See the [i18n guide](guide/i18n/merge) for more information.
  35127. *
  35128. * @usageNotes
  35129. * ### Example
  35130. *
  35131. * ```ts
  35132. * import { TRANSLATIONS_FORMAT } from '@angular/core';
  35133. * import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
  35134. * import { AppModule } from './app/app.module';
  35135. *
  35136. * platformBrowserDynamic().bootstrapModule(AppModule, {
  35137. * providers: [{provide: TRANSLATIONS_FORMAT, useValue: 'xlf' }]
  35138. * });
  35139. * ```
  35140. *
  35141. * @publicApi
  35142. */
  35143. const TRANSLATIONS_FORMAT = new InjectionToken(ngDevMode ? 'TranslationsFormat' : '');
  35144. /**
  35145. * Use this enum at bootstrap as an option of `bootstrapModule` to define the strategy
  35146. * that the compiler should use in case of missing translations:
  35147. * - Error: throw if you have missing translations.
  35148. * - Warning (default): show a warning in the console and/or shell.
  35149. * - Ignore: do nothing.
  35150. *
  35151. * See the [i18n guide](guide/i18n/merge#report-missing-translations) for more information.
  35152. *
  35153. * @usageNotes
  35154. * ### Example
  35155. * ```ts
  35156. * import { MissingTranslationStrategy } from '@angular/core';
  35157. * import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
  35158. * import { AppModule } from './app/app.module';
  35159. *
  35160. * platformBrowserDynamic().bootstrapModule(AppModule, {
  35161. * missingTranslation: MissingTranslationStrategy.Error
  35162. * });
  35163. * ```
  35164. *
  35165. * @publicApi
  35166. */
  35167. var MissingTranslationStrategy;
  35168. (function (MissingTranslationStrategy) {
  35169. MissingTranslationStrategy[MissingTranslationStrategy["Error"] = 0] = "Error";
  35170. MissingTranslationStrategy[MissingTranslationStrategy["Warning"] = 1] = "Warning";
  35171. MissingTranslationStrategy[MissingTranslationStrategy["Ignore"] = 2] = "Ignore";
  35172. })(MissingTranslationStrategy || (MissingTranslationStrategy = {}));
  35173. // A delay in milliseconds before the scan is run after onLoad, to avoid any
  35174. // potential race conditions with other LCP-related functions. This delay
  35175. // happens outside of the main JavaScript execution and will only effect the timing
  35176. // on when the warning becomes visible in the console.
  35177. const SCAN_DELAY = 200;
  35178. const OVERSIZED_IMAGE_TOLERANCE = 1200;
  35179. class ImagePerformanceWarning {
  35180. // Map of full image URLs -> original `ngSrc` values.
  35181. window = null;
  35182. observer = null;
  35183. options = inject(IMAGE_CONFIG);
  35184. lcpImageUrl;
  35185. start() {
  35186. if ((typeof ngServerMode !== 'undefined' && ngServerMode) ||
  35187. typeof PerformanceObserver === 'undefined' ||
  35188. (this.options?.disableImageSizeWarning && this.options?.disableImageLazyLoadWarning)) {
  35189. return;
  35190. }
  35191. this.observer = this.initPerformanceObserver();
  35192. const doc = getDocument();
  35193. const win = doc.defaultView;
  35194. if (win) {
  35195. this.window = win;
  35196. // Wait to avoid race conditions where LCP image triggers
  35197. // load event before it's recorded by the performance observer
  35198. const waitToScan = () => {
  35199. setTimeout(this.scanImages.bind(this), SCAN_DELAY);
  35200. };
  35201. const setup = () => {
  35202. // Consider the case when the application is created and destroyed multiple times.
  35203. // Typically, applications are created instantly once the page is loaded, and the
  35204. // `window.load` listener is always triggered. However, the `window.load` event will never
  35205. // be fired if the page is loaded, and the application is created later. Checking for
  35206. // `readyState` is the easiest way to determine whether the page has been loaded or not.
  35207. if (doc.readyState === 'complete') {
  35208. waitToScan();
  35209. }
  35210. else {
  35211. this.window?.addEventListener('load', waitToScan, { once: true });
  35212. }
  35213. };
  35214. // Angular doesn't have to run change detection whenever any asynchronous tasks are invoked in
  35215. // the scope of this functionality.
  35216. if (typeof Zone !== 'undefined') {
  35217. Zone.root.run(() => setup());
  35218. }
  35219. else {
  35220. setup();
  35221. }
  35222. }
  35223. }
  35224. ngOnDestroy() {
  35225. this.observer?.disconnect();
  35226. }
  35227. initPerformanceObserver() {
  35228. if (typeof PerformanceObserver === 'undefined') {
  35229. return null;
  35230. }
  35231. const observer = new PerformanceObserver((entryList) => {
  35232. const entries = entryList.getEntries();
  35233. if (entries.length === 0)
  35234. return;
  35235. // We use the latest entry produced by the `PerformanceObserver` as the best
  35236. // signal on which element is actually an LCP one. As an example, the first image to load on
  35237. // a page, by virtue of being the only thing on the page so far, is often a LCP candidate
  35238. // and gets reported by PerformanceObserver, but isn't necessarily the LCP element.
  35239. const lcpElement = entries[entries.length - 1];
  35240. // Cast to `any` due to missing `element` on the `LargestContentfulPaint` type of entry.
  35241. // See https://developer.mozilla.org/en-US/docs/Web/API/LargestContentfulPaint
  35242. const imgSrc = lcpElement.element?.src ?? '';
  35243. // Exclude `data:` and `blob:` URLs, since they are fetched resources.
  35244. if (imgSrc.startsWith('data:') || imgSrc.startsWith('blob:'))
  35245. return;
  35246. this.lcpImageUrl = imgSrc;
  35247. });
  35248. observer.observe({ type: 'largest-contentful-paint', buffered: true });
  35249. return observer;
  35250. }
  35251. scanImages() {
  35252. const images = getDocument().querySelectorAll('img');
  35253. let lcpElementFound, lcpElementLoadedCorrectly = false;
  35254. images.forEach((image) => {
  35255. if (!this.options?.disableImageSizeWarning) {
  35256. // Image elements using the NgOptimizedImage directive are excluded,
  35257. // as that directive has its own version of this check.
  35258. if (!image.getAttribute('ng-img') && this.isOversized(image)) {
  35259. logOversizedImageWarning(image.src);
  35260. }
  35261. }
  35262. if (!this.options?.disableImageLazyLoadWarning && this.lcpImageUrl) {
  35263. if (image.src === this.lcpImageUrl) {
  35264. lcpElementFound = true;
  35265. if (image.loading !== 'lazy' || image.getAttribute('ng-img')) {
  35266. // This variable is set to true and never goes back to false to account
  35267. // for the case where multiple images have the same src url, and some
  35268. // have lazy loading while others don't.
  35269. // Also ignore NgOptimizedImage because there's a different warning for that.
  35270. lcpElementLoadedCorrectly = true;
  35271. }
  35272. }
  35273. }
  35274. });
  35275. if (lcpElementFound &&
  35276. !lcpElementLoadedCorrectly &&
  35277. this.lcpImageUrl &&
  35278. !this.options?.disableImageLazyLoadWarning) {
  35279. logLazyLCPWarning(this.lcpImageUrl);
  35280. }
  35281. }
  35282. isOversized(image) {
  35283. if (!this.window) {
  35284. return false;
  35285. }
  35286. // The `isOversized` check may not be applicable or may require adjustments
  35287. // for several types of image formats or scenarios. Currently, we specify only
  35288. // `svg`, but this may also include `gif` since their quality isn’t tied to
  35289. // dimensions in the same way as raster images.
  35290. const nonOversizedImageExtentions = [
  35291. // SVG images are vector-based, which means they can scale
  35292. // to any size without losing quality.
  35293. '.svg',
  35294. ];
  35295. // Convert it to lowercase because this may have uppercase
  35296. // extensions, such as `IMAGE.SVG`.
  35297. // We fallback to an empty string because `src` may be `undefined`
  35298. // if it is explicitly set to `null` by some third-party code
  35299. // (e.g., `image.src = null`).
  35300. const imageSource = (image.src || '').toLowerCase();
  35301. if (nonOversizedImageExtentions.some((extension) => imageSource.endsWith(extension))) {
  35302. return false;
  35303. }
  35304. const computedStyle = this.window.getComputedStyle(image);
  35305. let renderedWidth = parseFloat(computedStyle.getPropertyValue('width'));
  35306. let renderedHeight = parseFloat(computedStyle.getPropertyValue('height'));
  35307. const boxSizing = computedStyle.getPropertyValue('box-sizing');
  35308. const objectFit = computedStyle.getPropertyValue('object-fit');
  35309. if (objectFit === `cover`) {
  35310. // Object fit cover may indicate a use case such as a sprite sheet where
  35311. // this warning does not apply.
  35312. return false;
  35313. }
  35314. if (boxSizing === 'border-box') {
  35315. // If the image `box-sizing` is set to `border-box`, we adjust the rendered
  35316. // dimensions by subtracting padding values.
  35317. const paddingTop = computedStyle.getPropertyValue('padding-top');
  35318. const paddingRight = computedStyle.getPropertyValue('padding-right');
  35319. const paddingBottom = computedStyle.getPropertyValue('padding-bottom');
  35320. const paddingLeft = computedStyle.getPropertyValue('padding-left');
  35321. renderedWidth -= parseFloat(paddingRight) + parseFloat(paddingLeft);
  35322. renderedHeight -= parseFloat(paddingTop) + parseFloat(paddingBottom);
  35323. }
  35324. const intrinsicWidth = image.naturalWidth;
  35325. const intrinsicHeight = image.naturalHeight;
  35326. const recommendedWidth = this.window.devicePixelRatio * renderedWidth;
  35327. const recommendedHeight = this.window.devicePixelRatio * renderedHeight;
  35328. const oversizedWidth = intrinsicWidth - recommendedWidth >= OVERSIZED_IMAGE_TOLERANCE;
  35329. const oversizedHeight = intrinsicHeight - recommendedHeight >= OVERSIZED_IMAGE_TOLERANCE;
  35330. return oversizedWidth || oversizedHeight;
  35331. }
  35332. static ɵfac = function ImagePerformanceWarning_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || ImagePerformanceWarning)(); };
  35333. static ɵprov = /*@__PURE__*/ ɵɵdefineInjectable({ token: ImagePerformanceWarning, factory: ImagePerformanceWarning.ɵfac, providedIn: 'root' });
  35334. }
  35335. (() => { (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(ImagePerformanceWarning, [{
  35336. type: Injectable,
  35337. args: [{ providedIn: 'root' }]
  35338. }], null, null); })();
  35339. function logLazyLCPWarning(src) {
  35340. console.warn(formatRuntimeError(-913 /* RuntimeErrorCode.IMAGE_PERFORMANCE_WARNING */, `An image with src ${src} is the Largest Contentful Paint (LCP) element ` +
  35341. `but was given a "loading" value of "lazy", which can negatively impact ` +
  35342. `application loading performance. This warning can be addressed by ` +
  35343. `changing the loading value of the LCP image to "eager", or by using the ` +
  35344. `NgOptimizedImage directive's prioritization utilities. For more ` +
  35345. `information about addressing or disabling this warning, see ` +
  35346. `https://angular.dev/errors/NG0913`));
  35347. }
  35348. function logOversizedImageWarning(src) {
  35349. console.warn(formatRuntimeError(-913 /* RuntimeErrorCode.IMAGE_PERFORMANCE_WARNING */, `An image with src ${src} has intrinsic file dimensions much larger than its ` +
  35350. `rendered size. This can negatively impact application loading performance. ` +
  35351. `For more information about addressing or disabling this warning, see ` +
  35352. `https://angular.dev/errors/NG0913`));
  35353. }
  35354. /**
  35355. * Internal token that allows to register extra callbacks that should be invoked during the
  35356. * `PlatformRef.destroy` operation. This token is needed to avoid a direct reference to the
  35357. * `PlatformRef` class (i.e. register the callback via `PlatformRef.onDestroy`), thus making the
  35358. * entire class tree-shakeable.
  35359. */
  35360. const PLATFORM_DESTROY_LISTENERS = new InjectionToken(ngDevMode ? 'PlatformDestroyListeners' : '');
  35361. /**
  35362. * InjectionToken to control root component bootstrap behavior.
  35363. *
  35364. * This token is primarily used in Angular's server-side rendering (SSR) scenarios,
  35365. * particularly by the `@angular/ssr` package, to manage whether the root component
  35366. * should be bootstrapped during the application initialization process.
  35367. *
  35368. * ## Purpose:
  35369. * During SSR route extraction, setting this token to `false` prevents Angular from
  35370. * bootstrapping the root component. This avoids unnecessary component rendering,
  35371. * enabling route extraction without requiring additional APIs or triggering
  35372. * component logic.
  35373. *
  35374. * ## Behavior:
  35375. * - **`false`**: Prevents the root component from being bootstrapped.
  35376. * - **`true`** (default): Proceeds with the normal root component bootstrap process.
  35377. *
  35378. * This mechanism ensures SSR can efficiently separate route extraction logic
  35379. * from component rendering.
  35380. */
  35381. const ENABLE_ROOT_COMPONENT_BOOTSTRAP = new InjectionToken(ngDevMode ? 'ENABLE_ROOT_COMPONENT_BOOTSTRAP' : '');
  35382. function isApplicationBootstrapConfig(config) {
  35383. return !config.moduleRef;
  35384. }
  35385. function bootstrap(config) {
  35386. const envInjector = isApplicationBootstrapConfig(config)
  35387. ? config.r3Injector
  35388. : config.moduleRef.injector;
  35389. const ngZone = envInjector.get(NgZone);
  35390. return ngZone.run(() => {
  35391. if (isApplicationBootstrapConfig(config)) {
  35392. config.r3Injector.resolveInjectorInitializers();
  35393. }
  35394. else {
  35395. config.moduleRef.resolveInjectorInitializers();
  35396. }
  35397. const exceptionHandler = envInjector.get(ErrorHandler, null);
  35398. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  35399. if (exceptionHandler === null) {
  35400. const errorMessage = isApplicationBootstrapConfig(config)
  35401. ? 'No `ErrorHandler` found in the Dependency Injection tree.'
  35402. : 'No ErrorHandler. Is platform module (BrowserModule) included';
  35403. throw new RuntimeError(402 /* RuntimeErrorCode.MISSING_REQUIRED_INJECTABLE_IN_BOOTSTRAP */, errorMessage);
  35404. }
  35405. if (envInjector.get(PROVIDED_ZONELESS) && envInjector.get(PROVIDED_NG_ZONE)) {
  35406. throw new RuntimeError(408 /* RuntimeErrorCode.PROVIDED_BOTH_ZONE_AND_ZONELESS */, 'Invalid change detection configuration: ' +
  35407. 'provideZoneChangeDetection and provideExperimentalZonelessChangeDetection cannot be used together.');
  35408. }
  35409. }
  35410. let onErrorSubscription;
  35411. ngZone.runOutsideAngular(() => {
  35412. onErrorSubscription = ngZone.onError.subscribe({
  35413. next: (error) => {
  35414. exceptionHandler.handleError(error);
  35415. },
  35416. });
  35417. });
  35418. // If the whole platform is destroyed, invoke the `destroy` method
  35419. // for all bootstrapped applications as well.
  35420. if (isApplicationBootstrapConfig(config)) {
  35421. const destroyListener = () => envInjector.destroy();
  35422. const onPlatformDestroyListeners = config.platformInjector.get(PLATFORM_DESTROY_LISTENERS);
  35423. onPlatformDestroyListeners.add(destroyListener);
  35424. envInjector.onDestroy(() => {
  35425. onErrorSubscription.unsubscribe();
  35426. onPlatformDestroyListeners.delete(destroyListener);
  35427. });
  35428. }
  35429. else {
  35430. const destroyListener = () => config.moduleRef.destroy();
  35431. const onPlatformDestroyListeners = config.platformInjector.get(PLATFORM_DESTROY_LISTENERS);
  35432. onPlatformDestroyListeners.add(destroyListener);
  35433. config.moduleRef.onDestroy(() => {
  35434. remove(config.allPlatformModules, config.moduleRef);
  35435. onErrorSubscription.unsubscribe();
  35436. onPlatformDestroyListeners.delete(destroyListener);
  35437. });
  35438. }
  35439. return _callAndReportToErrorHandler(exceptionHandler, ngZone, () => {
  35440. const initStatus = envInjector.get(ApplicationInitStatus);
  35441. initStatus.runInitializers();
  35442. return initStatus.donePromise.then(() => {
  35443. // If the `LOCALE_ID` provider is defined at bootstrap then we set the value for ivy
  35444. const localeId = envInjector.get(LOCALE_ID, DEFAULT_LOCALE_ID);
  35445. setLocaleId(localeId || DEFAULT_LOCALE_ID);
  35446. const enableRootComponentBoostrap = envInjector.get(ENABLE_ROOT_COMPONENT_BOOTSTRAP, true);
  35447. if (!enableRootComponentBoostrap) {
  35448. if (isApplicationBootstrapConfig(config)) {
  35449. return envInjector.get(ApplicationRef);
  35450. }
  35451. config.allPlatformModules.push(config.moduleRef);
  35452. return config.moduleRef;
  35453. }
  35454. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  35455. const imagePerformanceService = envInjector.get(ImagePerformanceWarning);
  35456. imagePerformanceService.start();
  35457. }
  35458. if (isApplicationBootstrapConfig(config)) {
  35459. const appRef = envInjector.get(ApplicationRef);
  35460. if (config.rootComponent !== undefined) {
  35461. appRef.bootstrap(config.rootComponent);
  35462. }
  35463. return appRef;
  35464. }
  35465. else {
  35466. moduleDoBootstrap(config.moduleRef, config.allPlatformModules);
  35467. return config.moduleRef;
  35468. }
  35469. });
  35470. });
  35471. });
  35472. }
  35473. function moduleDoBootstrap(moduleRef, allPlatformModules) {
  35474. const appRef = moduleRef.injector.get(ApplicationRef);
  35475. if (moduleRef._bootstrapComponents.length > 0) {
  35476. moduleRef._bootstrapComponents.forEach((f) => appRef.bootstrap(f));
  35477. }
  35478. else if (moduleRef.instance.ngDoBootstrap) {
  35479. moduleRef.instance.ngDoBootstrap(appRef);
  35480. }
  35481. else {
  35482. throw new RuntimeError(-403 /* RuntimeErrorCode.BOOTSTRAP_COMPONENTS_NOT_FOUND */, ngDevMode &&
  35483. `The module ${stringify(moduleRef.instance.constructor)} was bootstrapped, ` +
  35484. `but it does not declare "@NgModule.bootstrap" components nor a "ngDoBootstrap" method. ` +
  35485. `Please define one of these.`);
  35486. }
  35487. allPlatformModules.push(moduleRef);
  35488. }
  35489. function _callAndReportToErrorHandler(errorHandler, ngZone, callback) {
  35490. try {
  35491. const result = callback();
  35492. if (isPromise(result)) {
  35493. return result.catch((e) => {
  35494. ngZone.runOutsideAngular(() => errorHandler.handleError(e));
  35495. // rethrow as the exception handler might not do it
  35496. throw e;
  35497. });
  35498. }
  35499. return result;
  35500. }
  35501. catch (e) {
  35502. ngZone.runOutsideAngular(() => errorHandler.handleError(e));
  35503. // rethrow as the exception handler might not do it
  35504. throw e;
  35505. }
  35506. }
  35507. /**
  35508. * The Angular platform is the entry point for Angular on a web page.
  35509. * Each page has exactly one platform. Services (such as reflection) which are common
  35510. * to every Angular application running on the page are bound in its scope.
  35511. * A page's platform is initialized implicitly when a platform is created using a platform
  35512. * factory such as `PlatformBrowser`, or explicitly by calling the `createPlatform()` function.
  35513. *
  35514. * @publicApi
  35515. */
  35516. class PlatformRef {
  35517. _injector;
  35518. _modules = [];
  35519. _destroyListeners = [];
  35520. _destroyed = false;
  35521. /** @internal */
  35522. constructor(_injector) {
  35523. this._injector = _injector;
  35524. }
  35525. /**
  35526. * Creates an instance of an `@NgModule` for the given platform.
  35527. *
  35528. * @deprecated Passing NgModule factories as the `PlatformRef.bootstrapModuleFactory` function
  35529. * argument is deprecated. Use the `PlatformRef.bootstrapModule` API instead.
  35530. */
  35531. bootstrapModuleFactory(moduleFactory, options) {
  35532. const scheduleInRootZone = options?.scheduleInRootZone;
  35533. const ngZoneFactory = () => getNgZone(options?.ngZone, {
  35534. ...getNgZoneOptions({
  35535. eventCoalescing: options?.ngZoneEventCoalescing,
  35536. runCoalescing: options?.ngZoneRunCoalescing,
  35537. }),
  35538. scheduleInRootZone,
  35539. });
  35540. const ignoreChangesOutsideZone = options?.ignoreChangesOutsideZone;
  35541. const allAppProviders = [
  35542. internalProvideZoneChangeDetection({
  35543. ngZoneFactory,
  35544. ignoreChangesOutsideZone,
  35545. }),
  35546. { provide: ChangeDetectionScheduler, useExisting: ChangeDetectionSchedulerImpl },
  35547. ];
  35548. const moduleRef = createNgModuleRefWithProviders(moduleFactory.moduleType, this.injector, allAppProviders);
  35549. return bootstrap({
  35550. moduleRef,
  35551. allPlatformModules: this._modules,
  35552. platformInjector: this.injector,
  35553. });
  35554. }
  35555. /**
  35556. * Creates an instance of an `@NgModule` for a given platform.
  35557. *
  35558. * @usageNotes
  35559. * ### Simple Example
  35560. *
  35561. * ```ts
  35562. * @NgModule({
  35563. * imports: [BrowserModule]
  35564. * })
  35565. * class MyModule {}
  35566. *
  35567. * let moduleRef = platformBrowser().bootstrapModule(MyModule);
  35568. * ```
  35569. *
  35570. */
  35571. bootstrapModule(moduleType, compilerOptions = []) {
  35572. const options = optionsReducer({}, compilerOptions);
  35573. return compileNgModuleFactory(this.injector, options, moduleType).then((moduleFactory) => this.bootstrapModuleFactory(moduleFactory, options));
  35574. }
  35575. /**
  35576. * Registers a listener to be called when the platform is destroyed.
  35577. */
  35578. onDestroy(callback) {
  35579. this._destroyListeners.push(callback);
  35580. }
  35581. /**
  35582. * Retrieves the platform {@link Injector}, which is the parent injector for
  35583. * every Angular application on the page and provides singleton providers.
  35584. */
  35585. get injector() {
  35586. return this._injector;
  35587. }
  35588. /**
  35589. * Destroys the current Angular platform and all Angular applications on the page.
  35590. * Destroys all modules and listeners registered with the platform.
  35591. */
  35592. destroy() {
  35593. if (this._destroyed) {
  35594. throw new RuntimeError(404 /* RuntimeErrorCode.PLATFORM_ALREADY_DESTROYED */, ngDevMode && 'The platform has already been destroyed!');
  35595. }
  35596. this._modules.slice().forEach((module) => module.destroy());
  35597. this._destroyListeners.forEach((listener) => listener());
  35598. const destroyListeners = this._injector.get(PLATFORM_DESTROY_LISTENERS, null);
  35599. if (destroyListeners) {
  35600. destroyListeners.forEach((listener) => listener());
  35601. destroyListeners.clear();
  35602. }
  35603. this._destroyed = true;
  35604. }
  35605. /**
  35606. * Indicates whether this instance was destroyed.
  35607. */
  35608. get destroyed() {
  35609. return this._destroyed;
  35610. }
  35611. static ɵfac = function PlatformRef_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || PlatformRef)(ɵɵinject(Injector)); };
  35612. static ɵprov = /*@__PURE__*/ ɵɵdefineInjectable({ token: PlatformRef, factory: PlatformRef.ɵfac, providedIn: 'platform' });
  35613. }
  35614. (() => { (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(PlatformRef, [{
  35615. type: Injectable,
  35616. args: [{ providedIn: 'platform' }]
  35617. }], () => [{ type: Injector }], null); })();
  35618. let _platformInjector = null;
  35619. /**
  35620. * Internal token to indicate whether having multiple bootstrapped platform should be allowed (only
  35621. * one bootstrapped platform is allowed by default). This token helps to support SSR scenarios.
  35622. */
  35623. const ALLOW_MULTIPLE_PLATFORMS = new InjectionToken(ngDevMode ? 'AllowMultipleToken' : '');
  35624. /**
  35625. * Creates a platform.
  35626. * Platforms must be created on launch using this function.
  35627. *
  35628. * @publicApi
  35629. */
  35630. function createPlatform(injector) {
  35631. if (_platformInjector && !_platformInjector.get(ALLOW_MULTIPLE_PLATFORMS, false)) {
  35632. throw new RuntimeError(400 /* RuntimeErrorCode.MULTIPLE_PLATFORMS */, ngDevMode && 'There can be only one platform. Destroy the previous one to create a new one.');
  35633. }
  35634. publishDefaultGlobalUtils();
  35635. publishSignalConfiguration();
  35636. _platformInjector = injector;
  35637. const platform = injector.get(PlatformRef);
  35638. runPlatformInitializers(injector);
  35639. return platform;
  35640. }
  35641. /**
  35642. * Creates a factory for a platform. Can be used to provide or override `Providers` specific to
  35643. * your application's runtime needs, such as `PLATFORM_INITIALIZER` and `PLATFORM_ID`.
  35644. * @param parentPlatformFactory Another platform factory to modify. Allows you to compose factories
  35645. * to build up configurations that might be required by different libraries or parts of the
  35646. * application.
  35647. * @param name Identifies the new platform factory.
  35648. * @param providers A set of dependency providers for platforms created with the new factory.
  35649. *
  35650. * @publicApi
  35651. */
  35652. function createPlatformFactory(parentPlatformFactory, name, providers = []) {
  35653. const desc = `Platform: ${name}`;
  35654. const marker = new InjectionToken(desc);
  35655. return (extraProviders = []) => {
  35656. let platform = getPlatform();
  35657. if (!platform || platform.injector.get(ALLOW_MULTIPLE_PLATFORMS, false)) {
  35658. const platformProviders = [
  35659. ...providers,
  35660. ...extraProviders,
  35661. { provide: marker, useValue: true },
  35662. ];
  35663. if (parentPlatformFactory) {
  35664. parentPlatformFactory(platformProviders);
  35665. }
  35666. else {
  35667. createPlatform(createPlatformInjector(platformProviders, desc));
  35668. }
  35669. }
  35670. return assertPlatform(marker);
  35671. };
  35672. }
  35673. /**
  35674. * Helper function to create an instance of a platform injector (that maintains the 'platform'
  35675. * scope).
  35676. */
  35677. function createPlatformInjector(providers = [], name) {
  35678. return Injector.create({
  35679. name,
  35680. providers: [
  35681. { provide: INJECTOR_SCOPE, useValue: 'platform' },
  35682. { provide: PLATFORM_DESTROY_LISTENERS, useValue: new Set([() => (_platformInjector = null)]) },
  35683. ...providers,
  35684. ],
  35685. });
  35686. }
  35687. /**
  35688. * Checks that there is currently a platform that contains the given token as a provider.
  35689. *
  35690. * @publicApi
  35691. */
  35692. function assertPlatform(requiredToken) {
  35693. const platform = getPlatform();
  35694. if (!platform) {
  35695. throw new RuntimeError(401 /* RuntimeErrorCode.PLATFORM_NOT_FOUND */, ngDevMode && 'No platform exists!');
  35696. }
  35697. if ((typeof ngDevMode === 'undefined' || ngDevMode) &&
  35698. !platform.injector.get(requiredToken, null)) {
  35699. throw new RuntimeError(400 /* RuntimeErrorCode.MULTIPLE_PLATFORMS */, 'A platform with a different configuration has been created. Please destroy it first.');
  35700. }
  35701. return platform;
  35702. }
  35703. /**
  35704. * Returns the current platform.
  35705. *
  35706. * @publicApi
  35707. */
  35708. function getPlatform() {
  35709. return _platformInjector?.get(PlatformRef) ?? null;
  35710. }
  35711. /**
  35712. * Destroys the current Angular platform and all Angular applications on the page.
  35713. * Destroys all modules and listeners registered with the platform.
  35714. *
  35715. * @publicApi
  35716. */
  35717. function destroyPlatform() {
  35718. getPlatform()?.destroy();
  35719. }
  35720. /**
  35721. * The goal of this function is to bootstrap a platform injector,
  35722. * but avoid referencing `PlatformRef` class.
  35723. * This function is needed for bootstrapping a Standalone Component.
  35724. */
  35725. function createOrReusePlatformInjector(providers = []) {
  35726. // If a platform injector already exists, it means that the platform
  35727. // is already bootstrapped and no additional actions are required.
  35728. if (_platformInjector)
  35729. return _platformInjector;
  35730. publishDefaultGlobalUtils();
  35731. // Otherwise, setup a new platform injector and run platform initializers.
  35732. const injector = createPlatformInjector(providers);
  35733. _platformInjector = injector;
  35734. publishSignalConfiguration();
  35735. runPlatformInitializers(injector);
  35736. return injector;
  35737. }
  35738. /**
  35739. * @description
  35740. * This function is used to provide initialization functions that will be executed upon
  35741. * initialization of the platform injector.
  35742. *
  35743. * Note that the provided initializer is run in the injection context.
  35744. *
  35745. * Previously, this was achieved using the `PLATFORM_INITIALIZER` token which is now deprecated.
  35746. *
  35747. * @see {@link PLATFORM_INITIALIZER}
  35748. *
  35749. * @publicApi
  35750. */
  35751. function providePlatformInitializer(initializerFn) {
  35752. return makeEnvironmentProviders([
  35753. {
  35754. provide: PLATFORM_INITIALIZER,
  35755. useValue: initializerFn,
  35756. multi: true,
  35757. },
  35758. ]);
  35759. }
  35760. function runPlatformInitializers(injector) {
  35761. const inits = injector.get(PLATFORM_INITIALIZER, null);
  35762. runInInjectionContext(injector, () => {
  35763. inits?.forEach((init) => init());
  35764. });
  35765. }
  35766. /**
  35767. * Used to periodically verify no expressions have changed after they were checked.
  35768. *
  35769. * @param options Used to configure when the check will execute.
  35770. * - `interval` will periodically run exhaustive `checkNoChanges` on application views
  35771. * - `useNgZoneOnStable` will use ZoneJS to determine when change detection might have run
  35772. * in an application using ZoneJS to drive change detection. When the `NgZone.onStable` would
  35773. * have emitted, all views attached to the `ApplicationRef` are checked for changes.
  35774. * - 'exhaustive' means that all views attached to `ApplicationRef` and all the descendants of those views will be
  35775. * checked for changes (excluding those subtrees which are detached via `ChangeDetectorRef.detach()`).
  35776. * This is useful because the check that runs after regular change detection does not work for components using `ChangeDetectionStrategy.OnPush`.
  35777. * This check is will surface any existing errors hidden by `OnPush` components. By default, this check is exhaustive
  35778. * and will always check all views, regardless of their "dirty" state and `ChangeDetectionStrategy`.
  35779. *
  35780. * When the `useNgZoneOnStable` option is `true`, this function will provide its own `NgZone` implementation and needs
  35781. * to come after any other `NgZone` provider, including `provideZoneChangeDetection()` and `provideExperimentalZonelessChangeDetection()`.
  35782. *
  35783. * @experimental
  35784. * @publicApi
  35785. */
  35786. function provideExperimentalCheckNoChangesForDebug(options) {
  35787. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  35788. if (options.interval === undefined && !options.useNgZoneOnStable) {
  35789. throw new Error('Must provide one of `useNgZoneOnStable` or `interval`');
  35790. }
  35791. const checkNoChangesMode = options?.exhaustive === false
  35792. ? CheckNoChangesMode.OnlyDirtyViews
  35793. : CheckNoChangesMode.Exhaustive;
  35794. return makeEnvironmentProviders([
  35795. options?.useNgZoneOnStable
  35796. ? { provide: NgZone, useFactory: () => new DebugNgZoneForCheckNoChanges(checkNoChangesMode) }
  35797. : [],
  35798. options?.interval !== undefined
  35799. ? exhaustiveCheckNoChangesInterval(options.interval, checkNoChangesMode)
  35800. : [],
  35801. {
  35802. provide: ENVIRONMENT_INITIALIZER,
  35803. multi: true,
  35804. useValue: () => {
  35805. if (options?.useNgZoneOnStable &&
  35806. !(inject(NgZone) instanceof DebugNgZoneForCheckNoChanges)) {
  35807. throw new Error('`provideExperimentalCheckNoChangesForDebug` with `useNgZoneOnStable` must be after any other provider for `NgZone`.');
  35808. }
  35809. },
  35810. },
  35811. ]);
  35812. }
  35813. else {
  35814. return makeEnvironmentProviders([]);
  35815. }
  35816. }
  35817. class DebugNgZoneForCheckNoChanges extends NgZone {
  35818. checkNoChangesMode;
  35819. applicationRef;
  35820. scheduler;
  35821. errorHandler;
  35822. injector = inject(EnvironmentInjector);
  35823. constructor(checkNoChangesMode) {
  35824. const zonelessEnabled = inject(ZONELESS_ENABLED);
  35825. // Use coalescing to ensure we aren't ever running this check synchronously
  35826. super({
  35827. shouldCoalesceEventChangeDetection: true,
  35828. shouldCoalesceRunChangeDetection: zonelessEnabled,
  35829. });
  35830. this.checkNoChangesMode = checkNoChangesMode;
  35831. if (zonelessEnabled) {
  35832. // prevent emits to ensure code doesn't rely on these
  35833. this.onMicrotaskEmpty.emit = () => { };
  35834. this.onStable.emit = () => {
  35835. this.scheduler ||= this.injector.get(ChangeDetectionSchedulerImpl);
  35836. if (this.scheduler.pendingRenderTaskId || this.scheduler.runningTick) {
  35837. return;
  35838. }
  35839. this.checkApplicationViews();
  35840. };
  35841. this.onUnstable.emit = () => { };
  35842. }
  35843. else {
  35844. this.runOutsideAngular(() => {
  35845. this.onStable.subscribe(() => {
  35846. this.checkApplicationViews();
  35847. });
  35848. });
  35849. }
  35850. }
  35851. checkApplicationViews() {
  35852. this.applicationRef ||= this.injector.get(ApplicationRef);
  35853. for (const view of this.applicationRef.allViews) {
  35854. try {
  35855. checkNoChangesInternal(view._lView, this.checkNoChangesMode, view.notifyErrorHandler);
  35856. }
  35857. catch (e) {
  35858. this.errorHandler ||= this.injector.get(ErrorHandler);
  35859. this.errorHandler.handleError(e);
  35860. }
  35861. }
  35862. }
  35863. }
  35864. function exhaustiveCheckNoChangesInterval(interval, checkNoChangesMode) {
  35865. return {
  35866. provide: ENVIRONMENT_INITIALIZER,
  35867. multi: true,
  35868. useFactory: () => {
  35869. const applicationRef = inject(ApplicationRef);
  35870. const errorHandler = inject(ErrorHandler);
  35871. const scheduler = inject(ChangeDetectionSchedulerImpl);
  35872. const ngZone = inject(NgZone);
  35873. return () => {
  35874. function scheduleCheckNoChanges() {
  35875. ngZone.runOutsideAngular(() => {
  35876. setTimeout(() => {
  35877. if (applicationRef.destroyed) {
  35878. return;
  35879. }
  35880. if (scheduler.pendingRenderTaskId || scheduler.runningTick) {
  35881. scheduleCheckNoChanges();
  35882. return;
  35883. }
  35884. for (const view of applicationRef.allViews) {
  35885. try {
  35886. checkNoChangesInternal(view._lView, checkNoChangesMode, view.notifyErrorHandler);
  35887. }
  35888. catch (e) {
  35889. errorHandler.handleError(e);
  35890. }
  35891. }
  35892. scheduleCheckNoChanges();
  35893. }, interval);
  35894. });
  35895. }
  35896. scheduleCheckNoChanges();
  35897. };
  35898. },
  35899. };
  35900. }
  35901. /**
  35902. * Returns whether Angular is in development mode.
  35903. *
  35904. * By default, this is true, unless `enableProdMode` is invoked prior to calling this method or the
  35905. * application is built using the Angular CLI with the `optimization` option.
  35906. * @see {@link /cli/build ng build}
  35907. *
  35908. * @publicApi
  35909. */
  35910. function isDevMode() {
  35911. return typeof ngDevMode === 'undefined' || !!ngDevMode;
  35912. }
  35913. /**
  35914. * Disable Angular's development mode, which turns off assertions and other
  35915. * checks within the framework.
  35916. *
  35917. * One important assertion this disables verifies that a change detection pass
  35918. * does not result in additional changes to any bindings (also known as
  35919. * unidirectional data flow).
  35920. *
  35921. * Using this method is discouraged as the Angular CLI will set production mode when using the
  35922. * `optimization` option.
  35923. * @see {@link /cli/build ng build}
  35924. *
  35925. * @publicApi
  35926. */
  35927. function enableProdMode() {
  35928. // The below check is there so when ngDevMode is set via terser
  35929. // `global['ngDevMode'] = false;` is also dropped.
  35930. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  35931. _global['ngDevMode'] = false;
  35932. }
  35933. }
  35934. /**
  35935. * Returns the NgModuleFactory with the given id (specified using [@NgModule.id
  35936. * field](api/core/NgModule#id)), if it exists and has been loaded. Factories for NgModules that do
  35937. * not specify an `id` cannot be retrieved. Throws if an NgModule cannot be found.
  35938. * @publicApi
  35939. * @deprecated Use `getNgModuleById` instead.
  35940. */
  35941. function getModuleFactory(id) {
  35942. const type = getRegisteredNgModuleType(id);
  35943. if (!type)
  35944. throw noModuleError(id);
  35945. return new NgModuleFactory(type);
  35946. }
  35947. /**
  35948. * Returns the NgModule class with the given id (specified using [@NgModule.id
  35949. * field](api/core/NgModule#id)), if it exists and has been loaded. Classes for NgModules that do
  35950. * not specify an `id` cannot be retrieved. Throws if an NgModule cannot be found.
  35951. * @publicApi
  35952. */
  35953. function getNgModuleById(id) {
  35954. const type = getRegisteredNgModuleType(id);
  35955. if (!type)
  35956. throw noModuleError(id);
  35957. return type;
  35958. }
  35959. function noModuleError(id) {
  35960. return new Error(`No module with ID ${id} loaded`);
  35961. }
  35962. /**
  35963. * Base class that provides change detection functionality.
  35964. * A change-detection tree collects all views that are to be checked for changes.
  35965. * Use the methods to add and remove views from the tree, initiate change-detection,
  35966. * and explicitly mark views as _dirty_, meaning that they have changed and need to be re-rendered.
  35967. *
  35968. * @see [Using change detection hooks](guide/components/lifecycle#using-change-detection-hooks)
  35969. * @see [Defining custom change detection](guide/components/lifecycle#defining-custom-change-detection)
  35970. *
  35971. * @usageNotes
  35972. *
  35973. * The following examples demonstrate how to modify default change-detection behavior
  35974. * to perform explicit detection when needed.
  35975. *
  35976. * ### Use `markForCheck()` with `CheckOnce` strategy
  35977. *
  35978. * The following example sets the `OnPush` change-detection strategy for a component
  35979. * (`CheckOnce`, rather than the default `CheckAlways`), then forces a second check
  35980. * after an interval.
  35981. *
  35982. * {@example core/ts/change_detect/change-detection.ts region='mark-for-check'}
  35983. *
  35984. * ### Detach change detector to limit how often check occurs
  35985. *
  35986. * The following example defines a component with a large list of read-only data
  35987. * that is expected to change constantly, many times per second.
  35988. * To improve performance, we want to check and update the list
  35989. * less often than the changes actually occur. To do that, we detach
  35990. * the component's change detector and perform an explicit local check every five seconds.
  35991. *
  35992. * {@example core/ts/change_detect/change-detection.ts region='detach'}
  35993. *
  35994. *
  35995. * ### Reattaching a detached component
  35996. *
  35997. * The following example creates a component displaying live data.
  35998. * The component detaches its change detector from the main change detector tree
  35999. * when the `live` property is set to false, and reattaches it when the property
  36000. * becomes true.
  36001. *
  36002. * {@example core/ts/change_detect/change-detection.ts region='reattach'}
  36003. *
  36004. * @publicApi
  36005. */
  36006. class ChangeDetectorRef {
  36007. /**
  36008. * @internal
  36009. * @nocollapse
  36010. */
  36011. static __NG_ELEMENT_ID__ = injectChangeDetectorRef;
  36012. }
  36013. /** Returns a ChangeDetectorRef (a.k.a. a ViewRef) */
  36014. function injectChangeDetectorRef(flags) {
  36015. return createViewRef(getCurrentTNode(), getLView(), (flags & 16 /* InternalInjectFlags.ForPipe */) === 16 /* InternalInjectFlags.ForPipe */);
  36016. }
  36017. /**
  36018. * Creates a ViewRef and stores it on the injector as ChangeDetectorRef (public alias).
  36019. *
  36020. * @param tNode The node that is requesting a ChangeDetectorRef
  36021. * @param lView The view to which the node belongs
  36022. * @param isPipe Whether the view is being injected into a pipe.
  36023. * @returns The ChangeDetectorRef to use
  36024. */
  36025. function createViewRef(tNode, lView, isPipe) {
  36026. if (isComponentHost(tNode) && !isPipe) {
  36027. // The LView represents the location where the component is declared.
  36028. // Instead we want the LView for the component View and so we need to look it up.
  36029. const componentView = getComponentLViewByIndex(tNode.index, lView); // look down
  36030. return new ViewRef$1(componentView, componentView);
  36031. }
  36032. else if (tNode.type &
  36033. (3 /* TNodeType.AnyRNode */ | 12 /* TNodeType.AnyContainer */ | 32 /* TNodeType.Icu */ | 128 /* TNodeType.LetDeclaration */)) {
  36034. // The LView represents the location where the injection is requested from.
  36035. // We need to locate the containing LView (in case where the `lView` is an embedded view)
  36036. const hostComponentView = lView[DECLARATION_COMPONENT_VIEW]; // look up
  36037. return new ViewRef$1(hostComponentView, lView);
  36038. }
  36039. return null;
  36040. }
  36041. /**
  36042. * Represents an Angular view.
  36043. *
  36044. * @see {@link /api/core/ChangeDetectorRef?tab=usage-notes Change detection usage}
  36045. *
  36046. * @publicApi
  36047. */
  36048. class ViewRef extends ChangeDetectorRef {
  36049. }
  36050. /**
  36051. * Represents an Angular view in a view container.
  36052. * An embedded view can be referenced from a component
  36053. * other than the hosting component whose template defines it, or it can be defined
  36054. * independently by a `TemplateRef`.
  36055. *
  36056. * Properties of elements in a view can change, but the structure (number and order) of elements in
  36057. * a view cannot. Change the structure of elements by inserting, moving, or
  36058. * removing nested views in a view container.
  36059. *
  36060. * @see {@link ViewContainerRef}
  36061. *
  36062. * @usageNotes
  36063. *
  36064. * The following template breaks down into two separate `TemplateRef` instances,
  36065. * an outer one and an inner one.
  36066. *
  36067. * ```html
  36068. * Count: {{items.length}}
  36069. * <ul>
  36070. * <li *ngFor="let item of items">{{item}}</li>
  36071. * </ul>
  36072. * ```
  36073. *
  36074. * This is the outer `TemplateRef`:
  36075. *
  36076. * ```html
  36077. * Count: {{items.length}}
  36078. * <ul>
  36079. * <ng-template ngFor let-item [ngForOf]="items"></ng-template>
  36080. * </ul>
  36081. * ```
  36082. *
  36083. * This is the inner `TemplateRef`:
  36084. *
  36085. * ```html
  36086. * <li>{{item}}</li>
  36087. * ```
  36088. *
  36089. * The outer and inner `TemplateRef` instances are assembled into views as follows:
  36090. *
  36091. * ```html
  36092. * <!-- ViewRef: outer-0 -->
  36093. * Count: 2
  36094. * <ul>
  36095. * <ng-template view-container-ref></ng-template>
  36096. * <!-- ViewRef: inner-1 --><li>first</li><!-- /ViewRef: inner-1 -->
  36097. * <!-- ViewRef: inner-2 --><li>second</li><!-- /ViewRef: inner-2 -->
  36098. * </ul>
  36099. * <!-- /ViewRef: outer-0 -->
  36100. * ```
  36101. * @publicApi
  36102. */
  36103. class EmbeddedViewRef extends ViewRef {
  36104. }
  36105. /**
  36106. * @publicApi
  36107. */
  36108. class DebugEventListener {
  36109. name;
  36110. callback;
  36111. constructor(name, callback) {
  36112. this.name = name;
  36113. this.callback = callback;
  36114. }
  36115. }
  36116. /**
  36117. * @publicApi
  36118. */
  36119. function asNativeElements(debugEls) {
  36120. return debugEls.map((el) => el.nativeElement);
  36121. }
  36122. /**
  36123. * @publicApi
  36124. */
  36125. class DebugNode {
  36126. /**
  36127. * The underlying DOM node.
  36128. */
  36129. nativeNode;
  36130. constructor(nativeNode) {
  36131. this.nativeNode = nativeNode;
  36132. }
  36133. /**
  36134. * The `DebugElement` parent. Will be `null` if this is the root element.
  36135. */
  36136. get parent() {
  36137. const parent = this.nativeNode.parentNode;
  36138. return parent ? new DebugElement(parent) : null;
  36139. }
  36140. /**
  36141. * The host dependency injector. For example, the root element's component instance injector.
  36142. */
  36143. get injector() {
  36144. return getInjector(this.nativeNode);
  36145. }
  36146. /**
  36147. * The element's own component instance, if it has one.
  36148. */
  36149. get componentInstance() {
  36150. const nativeElement = this.nativeNode;
  36151. return (nativeElement && (getComponent(nativeElement) || getOwningComponent(nativeElement)));
  36152. }
  36153. /**
  36154. * An object that provides parent context for this element. Often an ancestor component instance
  36155. * that governs this element.
  36156. *
  36157. * When an element is repeated within *ngFor, the context is an `NgForOf` whose `$implicit`
  36158. * property is the value of the row instance value. For example, the `hero` in `*ngFor="let hero
  36159. * of heroes"`.
  36160. */
  36161. get context() {
  36162. return getComponent(this.nativeNode) || getContext(this.nativeNode);
  36163. }
  36164. /**
  36165. * The callbacks attached to the component's @Output properties and/or the element's event
  36166. * properties.
  36167. */
  36168. get listeners() {
  36169. return getListeners(this.nativeNode).filter((listener) => listener.type === 'dom');
  36170. }
  36171. /**
  36172. * Dictionary of objects associated with template local variables (e.g. #foo), keyed by the local
  36173. * variable name.
  36174. */
  36175. get references() {
  36176. return getLocalRefs(this.nativeNode);
  36177. }
  36178. /**
  36179. * This component's injector lookup tokens. Includes the component itself plus the tokens that the
  36180. * component lists in its providers metadata.
  36181. */
  36182. get providerTokens() {
  36183. return getInjectionTokens(this.nativeNode);
  36184. }
  36185. }
  36186. /**
  36187. * @publicApi
  36188. *
  36189. * @see [Component testing scenarios](guide/testing/components-scenarios)
  36190. * @see [Basics of testing components](guide/testing/components-basics)
  36191. * @see [Testing utility APIs](guide/testing/utility-apis)
  36192. */
  36193. class DebugElement extends DebugNode {
  36194. constructor(nativeNode) {
  36195. ngDevMode && assertDomNode(nativeNode);
  36196. super(nativeNode);
  36197. }
  36198. /**
  36199. * The underlying DOM element at the root of the component.
  36200. */
  36201. get nativeElement() {
  36202. return this.nativeNode.nodeType == Node.ELEMENT_NODE ? this.nativeNode : null;
  36203. }
  36204. /**
  36205. * The element tag name, if it is an element.
  36206. */
  36207. get name() {
  36208. const context = getLContext(this.nativeNode);
  36209. const lView = context ? context.lView : null;
  36210. if (lView !== null) {
  36211. const tData = lView[TVIEW].data;
  36212. const tNode = tData[context.nodeIndex];
  36213. return tNode.value;
  36214. }
  36215. else {
  36216. return this.nativeNode.nodeName;
  36217. }
  36218. }
  36219. /**
  36220. * Gets a map of property names to property values for an element.
  36221. *
  36222. * This map includes:
  36223. * - Regular property bindings (e.g. `[id]="id"`)
  36224. * - Host property bindings (e.g. `host: { '[id]': "id" }`)
  36225. * - Interpolated property bindings (e.g. `id="{{ value }}")
  36226. *
  36227. * It does not include:
  36228. * - input property bindings (e.g. `[myCustomInput]="value"`)
  36229. * - attribute bindings (e.g. `[attr.role]="menu"`)
  36230. */
  36231. get properties() {
  36232. const context = getLContext(this.nativeNode);
  36233. const lView = context ? context.lView : null;
  36234. if (lView === null) {
  36235. return {};
  36236. }
  36237. const tData = lView[TVIEW].data;
  36238. const tNode = tData[context.nodeIndex];
  36239. const properties = {};
  36240. // Collect properties from the DOM.
  36241. copyDomProperties(this.nativeElement, properties);
  36242. // Collect properties from the bindings. This is needed for animation renderer which has
  36243. // synthetic properties which don't get reflected into the DOM.
  36244. collectPropertyBindings(properties, tNode, lView, tData);
  36245. return properties;
  36246. }
  36247. /**
  36248. * A map of attribute names to attribute values for an element.
  36249. */
  36250. // TODO: replace null by undefined in the return type
  36251. get attributes() {
  36252. const attributes = {};
  36253. const element = this.nativeElement;
  36254. if (!element) {
  36255. return attributes;
  36256. }
  36257. const context = getLContext(element);
  36258. const lView = context ? context.lView : null;
  36259. if (lView === null) {
  36260. return {};
  36261. }
  36262. const tNodeAttrs = lView[TVIEW].data[context.nodeIndex].attrs;
  36263. const lowercaseTNodeAttrs = [];
  36264. // For debug nodes we take the element's attribute directly from the DOM since it allows us
  36265. // to account for ones that weren't set via bindings (e.g. ViewEngine keeps track of the ones
  36266. // that are set through `Renderer2`). The problem is that the browser will lowercase all names,
  36267. // however since we have the attributes already on the TNode, we can preserve the case by going
  36268. // through them once, adding them to the `attributes` map and putting their lower-cased name
  36269. // into an array. Afterwards when we're going through the native DOM attributes, we can check
  36270. // whether we haven't run into an attribute already through the TNode.
  36271. if (tNodeAttrs) {
  36272. let i = 0;
  36273. while (i < tNodeAttrs.length) {
  36274. const attrName = tNodeAttrs[i];
  36275. // Stop as soon as we hit a marker. We only care about the regular attributes. Everything
  36276. // else will be handled below when we read the final attributes off the DOM.
  36277. if (typeof attrName !== 'string')
  36278. break;
  36279. const attrValue = tNodeAttrs[i + 1];
  36280. attributes[attrName] = attrValue;
  36281. lowercaseTNodeAttrs.push(attrName.toLowerCase());
  36282. i += 2;
  36283. }
  36284. }
  36285. for (const attr of element.attributes) {
  36286. // Make sure that we don't assign the same attribute both in its
  36287. // case-sensitive form and the lower-cased one from the browser.
  36288. if (!lowercaseTNodeAttrs.includes(attr.name)) {
  36289. attributes[attr.name] = attr.value;
  36290. }
  36291. }
  36292. return attributes;
  36293. }
  36294. /**
  36295. * The inline styles of the DOM element.
  36296. */
  36297. // TODO: replace null by undefined in the return type
  36298. get styles() {
  36299. const element = this.nativeElement;
  36300. return (element?.style ?? {});
  36301. }
  36302. /**
  36303. * A map containing the class names on the element as keys.
  36304. *
  36305. * This map is derived from the `className` property of the DOM element.
  36306. *
  36307. * Note: The values of this object will always be `true`. The class key will not appear in the KV
  36308. * object if it does not exist on the element.
  36309. *
  36310. * @see [Element.className](https://developer.mozilla.org/en-US/docs/Web/API/Element/className)
  36311. */
  36312. get classes() {
  36313. const result = {};
  36314. const element = this.nativeElement;
  36315. // SVG elements return an `SVGAnimatedString` instead of a plain string for the `className`.
  36316. const className = element.className;
  36317. const classes = typeof className !== 'string' ? className.baseVal.split(' ') : className.split(' ');
  36318. classes.forEach((value) => (result[value] = true));
  36319. return result;
  36320. }
  36321. /**
  36322. * The `childNodes` of the DOM element as a `DebugNode` array.
  36323. *
  36324. * @see [Node.childNodes](https://developer.mozilla.org/en-US/docs/Web/API/Node/childNodes)
  36325. */
  36326. get childNodes() {
  36327. const childNodes = this.nativeNode.childNodes;
  36328. const children = [];
  36329. for (let i = 0; i < childNodes.length; i++) {
  36330. const element = childNodes[i];
  36331. children.push(getDebugNode(element));
  36332. }
  36333. return children;
  36334. }
  36335. /**
  36336. * The immediate `DebugElement` children. Walk the tree by descending through `children`.
  36337. */
  36338. get children() {
  36339. const nativeElement = this.nativeElement;
  36340. if (!nativeElement)
  36341. return [];
  36342. const childNodes = nativeElement.children;
  36343. const children = [];
  36344. for (let i = 0; i < childNodes.length; i++) {
  36345. const element = childNodes[i];
  36346. children.push(getDebugNode(element));
  36347. }
  36348. return children;
  36349. }
  36350. /**
  36351. * @returns the first `DebugElement` that matches the predicate at any depth in the subtree.
  36352. */
  36353. query(predicate) {
  36354. const results = this.queryAll(predicate);
  36355. return results[0] || null;
  36356. }
  36357. /**
  36358. * @returns All `DebugElement` matches for the predicate at any depth in the subtree.
  36359. */
  36360. queryAll(predicate) {
  36361. const matches = [];
  36362. _queryAll(this, predicate, matches, true);
  36363. return matches;
  36364. }
  36365. /**
  36366. * @returns All `DebugNode` matches for the predicate at any depth in the subtree.
  36367. */
  36368. queryAllNodes(predicate) {
  36369. const matches = [];
  36370. _queryAll(this, predicate, matches, false);
  36371. return matches;
  36372. }
  36373. /**
  36374. * Triggers the event by its name if there is a corresponding listener in the element's
  36375. * `listeners` collection.
  36376. *
  36377. * If the event lacks a listener or there's some other problem, consider
  36378. * calling `nativeElement.dispatchEvent(eventObject)`.
  36379. *
  36380. * @param eventName The name of the event to trigger
  36381. * @param eventObj The _event object_ expected by the handler
  36382. *
  36383. * @see [Testing components scenarios](guide/testing/components-scenarios#trigger-event-handler)
  36384. */
  36385. triggerEventHandler(eventName, eventObj) {
  36386. const node = this.nativeNode;
  36387. const invokedListeners = [];
  36388. this.listeners.forEach((listener) => {
  36389. if (listener.name === eventName) {
  36390. const callback = listener.callback;
  36391. callback.call(node, eventObj);
  36392. invokedListeners.push(callback);
  36393. }
  36394. });
  36395. // We need to check whether `eventListeners` exists, because it's something
  36396. // that Zone.js only adds to `EventTarget` in browser environments.
  36397. if (typeof node.eventListeners === 'function') {
  36398. // Note that in Ivy we wrap event listeners with a call to `event.preventDefault` in some
  36399. // cases. We use '__ngUnwrap__' as a special token that gives us access to the actual event
  36400. // listener.
  36401. node.eventListeners(eventName).forEach((listener) => {
  36402. // In order to ensure that we can detect the special __ngUnwrap__ token described above, we
  36403. // use `toString` on the listener and see if it contains the token. We use this approach to
  36404. // ensure that it still worked with compiled code since it cannot remove or rename string
  36405. // literals. We also considered using a special function name (i.e. if(listener.name ===
  36406. // special)) but that was more cumbersome and we were also concerned the compiled code could
  36407. // strip the name, turning the condition in to ("" === "") and always returning true.
  36408. if (listener.toString().indexOf('__ngUnwrap__') !== -1) {
  36409. const unwrappedListener = listener('__ngUnwrap__');
  36410. return (invokedListeners.indexOf(unwrappedListener) === -1 &&
  36411. unwrappedListener.call(node, eventObj));
  36412. }
  36413. });
  36414. }
  36415. }
  36416. }
  36417. function copyDomProperties(element, properties) {
  36418. if (element) {
  36419. // Skip own properties (as those are patched)
  36420. let obj = Object.getPrototypeOf(element);
  36421. const NodePrototype = Node.prototype;
  36422. while (obj !== null && obj !== NodePrototype) {
  36423. const descriptors = Object.getOwnPropertyDescriptors(obj);
  36424. for (let key in descriptors) {
  36425. if (!key.startsWith('__') && !key.startsWith('on')) {
  36426. // don't include properties starting with `__` and `on`.
  36427. // `__` are patched values which should not be included.
  36428. // `on` are listeners which also should not be included.
  36429. const value = element[key];
  36430. if (isPrimitiveValue(value)) {
  36431. properties[key] = value;
  36432. }
  36433. }
  36434. }
  36435. obj = Object.getPrototypeOf(obj);
  36436. }
  36437. }
  36438. }
  36439. function isPrimitiveValue(value) {
  36440. return (typeof value === 'string' ||
  36441. typeof value === 'boolean' ||
  36442. typeof value === 'number' ||
  36443. value === null);
  36444. }
  36445. function _queryAll(parentElement, predicate, matches, elementsOnly) {
  36446. const context = getLContext(parentElement.nativeNode);
  36447. const lView = context ? context.lView : null;
  36448. if (lView !== null) {
  36449. const parentTNode = lView[TVIEW].data[context.nodeIndex];
  36450. _queryNodeChildren(parentTNode, lView, predicate, matches, elementsOnly, parentElement.nativeNode);
  36451. }
  36452. else {
  36453. // If the context is null, then `parentElement` was either created with Renderer2 or native DOM
  36454. // APIs.
  36455. _queryNativeNodeDescendants(parentElement.nativeNode, predicate, matches, elementsOnly);
  36456. }
  36457. }
  36458. /**
  36459. * Recursively match the current TNode against the predicate, and goes on with the next ones.
  36460. *
  36461. * @param tNode the current TNode
  36462. * @param lView the LView of this TNode
  36463. * @param predicate the predicate to match
  36464. * @param matches the list of positive matches
  36465. * @param elementsOnly whether only elements should be searched
  36466. * @param rootNativeNode the root native node on which predicate should not be matched
  36467. */
  36468. function _queryNodeChildren(tNode, lView, predicate, matches, elementsOnly, rootNativeNode) {
  36469. ngDevMode && assertTNodeForLView(tNode, lView);
  36470. const nativeNode = getNativeByTNodeOrNull(tNode, lView);
  36471. // For each type of TNode, specific logic is executed.
  36472. if (tNode.type & (3 /* TNodeType.AnyRNode */ | 8 /* TNodeType.ElementContainer */)) {
  36473. // Case 1: the TNode is an element
  36474. // The native node has to be checked.
  36475. _addQueryMatch(nativeNode, predicate, matches, elementsOnly, rootNativeNode);
  36476. if (isComponentHost(tNode)) {
  36477. // If the element is the host of a component, then all nodes in its view have to be processed.
  36478. // Note: the component's content (tNode.child) will be processed from the insertion points.
  36479. const componentView = getComponentLViewByIndex(tNode.index, lView);
  36480. if (componentView && componentView[TVIEW].firstChild) {
  36481. _queryNodeChildren(componentView[TVIEW].firstChild, componentView, predicate, matches, elementsOnly, rootNativeNode);
  36482. }
  36483. }
  36484. else {
  36485. if (tNode.child) {
  36486. // Otherwise, its children have to be processed.
  36487. _queryNodeChildren(tNode.child, lView, predicate, matches, elementsOnly, rootNativeNode);
  36488. }
  36489. // We also have to query the DOM directly in order to catch elements inserted through
  36490. // Renderer2. Note that this is __not__ optimal, because we're walking similar trees multiple
  36491. // times. ViewEngine could do it more efficiently, because all the insertions go through
  36492. // Renderer2, however that's not the case in Ivy. This approach is being used because:
  36493. // 1. Matching the ViewEngine behavior would mean potentially introducing a dependency
  36494. // from `Renderer2` to Ivy which could bring Ivy code into ViewEngine.
  36495. // 2. It allows us to capture nodes that were inserted directly via the DOM.
  36496. nativeNode && _queryNativeNodeDescendants(nativeNode, predicate, matches, elementsOnly);
  36497. }
  36498. // In all cases, if a dynamic container exists for this node, each view inside it has to be
  36499. // processed.
  36500. const nodeOrContainer = lView[tNode.index];
  36501. if (isLContainer(nodeOrContainer)) {
  36502. _queryNodeChildrenInContainer(nodeOrContainer, predicate, matches, elementsOnly, rootNativeNode);
  36503. }
  36504. }
  36505. else if (tNode.type & 4 /* TNodeType.Container */) {
  36506. // Case 2: the TNode is a container
  36507. // The native node has to be checked.
  36508. const lContainer = lView[tNode.index];
  36509. _addQueryMatch(lContainer[NATIVE], predicate, matches, elementsOnly, rootNativeNode);
  36510. // Each view inside the container has to be processed.
  36511. _queryNodeChildrenInContainer(lContainer, predicate, matches, elementsOnly, rootNativeNode);
  36512. }
  36513. else if (tNode.type & 16 /* TNodeType.Projection */) {
  36514. // Case 3: the TNode is a projection insertion point (i.e. a <ng-content>).
  36515. // The nodes projected at this location all need to be processed.
  36516. const componentView = lView[DECLARATION_COMPONENT_VIEW];
  36517. const componentHost = componentView[T_HOST];
  36518. const head = componentHost.projection[tNode.projection];
  36519. if (Array.isArray(head)) {
  36520. for (let nativeNode of head) {
  36521. _addQueryMatch(nativeNode, predicate, matches, elementsOnly, rootNativeNode);
  36522. }
  36523. }
  36524. else if (head) {
  36525. const nextLView = componentView[PARENT];
  36526. const nextTNode = nextLView[TVIEW].data[head.index];
  36527. _queryNodeChildren(nextTNode, nextLView, predicate, matches, elementsOnly, rootNativeNode);
  36528. }
  36529. }
  36530. else if (tNode.child) {
  36531. // Case 4: the TNode is a view.
  36532. _queryNodeChildren(tNode.child, lView, predicate, matches, elementsOnly, rootNativeNode);
  36533. }
  36534. // We don't want to go to the next sibling of the root node.
  36535. if (rootNativeNode !== nativeNode) {
  36536. // To determine the next node to be processed, we need to use the next or the projectionNext
  36537. // link, depending on whether the current node has been projected.
  36538. const nextTNode = tNode.flags & 2 /* TNodeFlags.isProjected */ ? tNode.projectionNext : tNode.next;
  36539. if (nextTNode) {
  36540. _queryNodeChildren(nextTNode, lView, predicate, matches, elementsOnly, rootNativeNode);
  36541. }
  36542. }
  36543. }
  36544. /**
  36545. * Process all TNodes in a given container.
  36546. *
  36547. * @param lContainer the container to be processed
  36548. * @param predicate the predicate to match
  36549. * @param matches the list of positive matches
  36550. * @param elementsOnly whether only elements should be searched
  36551. * @param rootNativeNode the root native node on which predicate should not be matched
  36552. */
  36553. function _queryNodeChildrenInContainer(lContainer, predicate, matches, elementsOnly, rootNativeNode) {
  36554. for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
  36555. const childView = lContainer[i];
  36556. const firstChild = childView[TVIEW].firstChild;
  36557. if (firstChild) {
  36558. _queryNodeChildren(firstChild, childView, predicate, matches, elementsOnly, rootNativeNode);
  36559. }
  36560. }
  36561. }
  36562. /**
  36563. * Match the current native node against the predicate.
  36564. *
  36565. * @param nativeNode the current native node
  36566. * @param predicate the predicate to match
  36567. * @param matches the list of positive matches
  36568. * @param elementsOnly whether only elements should be searched
  36569. * @param rootNativeNode the root native node on which predicate should not be matched
  36570. */
  36571. function _addQueryMatch(nativeNode, predicate, matches, elementsOnly, rootNativeNode) {
  36572. if (rootNativeNode !== nativeNode) {
  36573. const debugNode = getDebugNode(nativeNode);
  36574. if (!debugNode) {
  36575. return;
  36576. }
  36577. // Type of the "predicate and "matches" array are set based on the value of
  36578. // the "elementsOnly" parameter. TypeScript is not able to properly infer these
  36579. // types with generics, so we manually cast the parameters accordingly.
  36580. if (elementsOnly &&
  36581. debugNode instanceof DebugElement &&
  36582. predicate(debugNode) &&
  36583. matches.indexOf(debugNode) === -1) {
  36584. matches.push(debugNode);
  36585. }
  36586. else if (!elementsOnly &&
  36587. predicate(debugNode) &&
  36588. matches.indexOf(debugNode) === -1) {
  36589. matches.push(debugNode);
  36590. }
  36591. }
  36592. }
  36593. /**
  36594. * Match all the descendants of a DOM node against a predicate.
  36595. *
  36596. * @param nativeNode the current native node
  36597. * @param predicate the predicate to match
  36598. * @param matches the list where matches are stored
  36599. * @param elementsOnly whether only elements should be searched
  36600. */
  36601. function _queryNativeNodeDescendants(parentNode, predicate, matches, elementsOnly) {
  36602. const nodes = parentNode.childNodes;
  36603. const length = nodes.length;
  36604. for (let i = 0; i < length; i++) {
  36605. const node = nodes[i];
  36606. const debugNode = getDebugNode(node);
  36607. if (debugNode) {
  36608. if (elementsOnly &&
  36609. debugNode instanceof DebugElement &&
  36610. predicate(debugNode) &&
  36611. matches.indexOf(debugNode) === -1) {
  36612. matches.push(debugNode);
  36613. }
  36614. else if (!elementsOnly &&
  36615. predicate(debugNode) &&
  36616. matches.indexOf(debugNode) === -1) {
  36617. matches.push(debugNode);
  36618. }
  36619. _queryNativeNodeDescendants(node, predicate, matches, elementsOnly);
  36620. }
  36621. }
  36622. }
  36623. /**
  36624. * Iterates through the property bindings for a given node and generates
  36625. * a map of property names to values. This map only contains property bindings
  36626. * defined in templates, not in host bindings.
  36627. */
  36628. function collectPropertyBindings(properties, tNode, lView, tData) {
  36629. let bindingIndexes = tNode.propertyBindings;
  36630. if (bindingIndexes !== null) {
  36631. for (let i = 0; i < bindingIndexes.length; i++) {
  36632. const bindingIndex = bindingIndexes[i];
  36633. const propMetadata = tData[bindingIndex];
  36634. const metadataParts = propMetadata.split(INTERPOLATION_DELIMITER);
  36635. const propertyName = metadataParts[0];
  36636. if (metadataParts.length > 1) {
  36637. let value = metadataParts[1];
  36638. for (let j = 1; j < metadataParts.length - 1; j++) {
  36639. value += renderStringify(lView[bindingIndex + j - 1]) + metadataParts[j + 1];
  36640. }
  36641. properties[propertyName] = value;
  36642. }
  36643. else {
  36644. properties[propertyName] = lView[bindingIndex];
  36645. }
  36646. }
  36647. }
  36648. }
  36649. const NG_DEBUG_PROPERTY = '__ng_debug__';
  36650. /**
  36651. * @publicApi
  36652. */
  36653. function getDebugNode(nativeNode) {
  36654. if (nativeNode instanceof Node) {
  36655. if (!nativeNode.hasOwnProperty(NG_DEBUG_PROPERTY)) {
  36656. nativeNode[NG_DEBUG_PROPERTY] =
  36657. nativeNode.nodeType == Node.ELEMENT_NODE
  36658. ? new DebugElement(nativeNode)
  36659. : new DebugNode(nativeNode);
  36660. }
  36661. return nativeNode[NG_DEBUG_PROPERTY];
  36662. }
  36663. return null;
  36664. }
  36665. class DefaultIterableDifferFactory {
  36666. constructor() { }
  36667. supports(obj) {
  36668. return isListLikeIterable(obj);
  36669. }
  36670. create(trackByFn) {
  36671. return new DefaultIterableDiffer(trackByFn);
  36672. }
  36673. }
  36674. const trackByIdentity = (index, item) => item;
  36675. /**
  36676. * @deprecated v4.0.0 - Should not be part of public API.
  36677. * @publicApi
  36678. */
  36679. class DefaultIterableDiffer {
  36680. length = 0;
  36681. // TODO: confirm the usage of `collection` as it's unused, readonly and on a non public API.
  36682. collection;
  36683. // Keeps track of the used records at any point in time (during & across `_check()` calls)
  36684. _linkedRecords = null;
  36685. // Keeps track of the removed records at any point in time during `_check()` calls.
  36686. _unlinkedRecords = null;
  36687. _previousItHead = null;
  36688. _itHead = null;
  36689. _itTail = null;
  36690. _additionsHead = null;
  36691. _additionsTail = null;
  36692. _movesHead = null;
  36693. _movesTail = null;
  36694. _removalsHead = null;
  36695. _removalsTail = null;
  36696. // Keeps track of records where custom track by is the same, but item identity has changed
  36697. _identityChangesHead = null;
  36698. _identityChangesTail = null;
  36699. _trackByFn;
  36700. constructor(trackByFn) {
  36701. this._trackByFn = trackByFn || trackByIdentity;
  36702. }
  36703. forEachItem(fn) {
  36704. let record;
  36705. for (record = this._itHead; record !== null; record = record._next) {
  36706. fn(record);
  36707. }
  36708. }
  36709. forEachOperation(fn) {
  36710. let nextIt = this._itHead;
  36711. let nextRemove = this._removalsHead;
  36712. let addRemoveOffset = 0;
  36713. let moveOffsets = null;
  36714. while (nextIt || nextRemove) {
  36715. // Figure out which is the next record to process
  36716. // Order: remove, add, move
  36717. const record = !nextRemove ||
  36718. (nextIt &&
  36719. nextIt.currentIndex < getPreviousIndex(nextRemove, addRemoveOffset, moveOffsets))
  36720. ? nextIt
  36721. : nextRemove;
  36722. const adjPreviousIndex = getPreviousIndex(record, addRemoveOffset, moveOffsets);
  36723. const currentIndex = record.currentIndex;
  36724. // consume the item, and adjust the addRemoveOffset and update moveDistance if necessary
  36725. if (record === nextRemove) {
  36726. addRemoveOffset--;
  36727. nextRemove = nextRemove._nextRemoved;
  36728. }
  36729. else {
  36730. nextIt = nextIt._next;
  36731. if (record.previousIndex == null) {
  36732. addRemoveOffset++;
  36733. }
  36734. else {
  36735. // INVARIANT: currentIndex < previousIndex
  36736. if (!moveOffsets)
  36737. moveOffsets = [];
  36738. const localMovePreviousIndex = adjPreviousIndex - addRemoveOffset;
  36739. const localCurrentIndex = currentIndex - addRemoveOffset;
  36740. if (localMovePreviousIndex != localCurrentIndex) {
  36741. for (let i = 0; i < localMovePreviousIndex; i++) {
  36742. const offset = i < moveOffsets.length ? moveOffsets[i] : (moveOffsets[i] = 0);
  36743. const index = offset + i;
  36744. if (localCurrentIndex <= index && index < localMovePreviousIndex) {
  36745. moveOffsets[i] = offset + 1;
  36746. }
  36747. }
  36748. const previousIndex = record.previousIndex;
  36749. moveOffsets[previousIndex] = localCurrentIndex - localMovePreviousIndex;
  36750. }
  36751. }
  36752. }
  36753. if (adjPreviousIndex !== currentIndex) {
  36754. fn(record, adjPreviousIndex, currentIndex);
  36755. }
  36756. }
  36757. }
  36758. forEachPreviousItem(fn) {
  36759. let record;
  36760. for (record = this._previousItHead; record !== null; record = record._nextPrevious) {
  36761. fn(record);
  36762. }
  36763. }
  36764. forEachAddedItem(fn) {
  36765. let record;
  36766. for (record = this._additionsHead; record !== null; record = record._nextAdded) {
  36767. fn(record);
  36768. }
  36769. }
  36770. forEachMovedItem(fn) {
  36771. let record;
  36772. for (record = this._movesHead; record !== null; record = record._nextMoved) {
  36773. fn(record);
  36774. }
  36775. }
  36776. forEachRemovedItem(fn) {
  36777. let record;
  36778. for (record = this._removalsHead; record !== null; record = record._nextRemoved) {
  36779. fn(record);
  36780. }
  36781. }
  36782. forEachIdentityChange(fn) {
  36783. let record;
  36784. for (record = this._identityChangesHead; record !== null; record = record._nextIdentityChange) {
  36785. fn(record);
  36786. }
  36787. }
  36788. diff(collection) {
  36789. if (collection == null)
  36790. collection = [];
  36791. if (!isListLikeIterable(collection)) {
  36792. throw new RuntimeError(900 /* RuntimeErrorCode.INVALID_DIFFER_INPUT */, ngDevMode &&
  36793. `Error trying to diff '${stringify(collection)}'. Only arrays and iterables are allowed`);
  36794. }
  36795. if (this.check(collection)) {
  36796. return this;
  36797. }
  36798. else {
  36799. return null;
  36800. }
  36801. }
  36802. onDestroy() { }
  36803. check(collection) {
  36804. this._reset();
  36805. let record = this._itHead;
  36806. let mayBeDirty = false;
  36807. let index;
  36808. let item;
  36809. let itemTrackBy;
  36810. if (Array.isArray(collection)) {
  36811. this.length = collection.length;
  36812. for (let index = 0; index < this.length; index++) {
  36813. item = collection[index];
  36814. itemTrackBy = this._trackByFn(index, item);
  36815. if (record === null || !Object.is(record.trackById, itemTrackBy)) {
  36816. record = this._mismatch(record, item, itemTrackBy, index);
  36817. mayBeDirty = true;
  36818. }
  36819. else {
  36820. if (mayBeDirty) {
  36821. // TODO(misko): can we limit this to duplicates only?
  36822. record = this._verifyReinsertion(record, item, itemTrackBy, index);
  36823. }
  36824. if (!Object.is(record.item, item))
  36825. this._addIdentityChange(record, item);
  36826. }
  36827. record = record._next;
  36828. }
  36829. }
  36830. else {
  36831. index = 0;
  36832. iterateListLike(collection, (item) => {
  36833. itemTrackBy = this._trackByFn(index, item);
  36834. if (record === null || !Object.is(record.trackById, itemTrackBy)) {
  36835. record = this._mismatch(record, item, itemTrackBy, index);
  36836. mayBeDirty = true;
  36837. }
  36838. else {
  36839. if (mayBeDirty) {
  36840. // TODO(misko): can we limit this to duplicates only?
  36841. record = this._verifyReinsertion(record, item, itemTrackBy, index);
  36842. }
  36843. if (!Object.is(record.item, item))
  36844. this._addIdentityChange(record, item);
  36845. }
  36846. record = record._next;
  36847. index++;
  36848. });
  36849. this.length = index;
  36850. }
  36851. this._truncate(record);
  36852. this.collection = collection;
  36853. return this.isDirty;
  36854. }
  36855. /* CollectionChanges is considered dirty if it has any additions, moves, removals, or identity
  36856. * changes.
  36857. */
  36858. get isDirty() {
  36859. return (this._additionsHead !== null ||
  36860. this._movesHead !== null ||
  36861. this._removalsHead !== null ||
  36862. this._identityChangesHead !== null);
  36863. }
  36864. /**
  36865. * Reset the state of the change objects to show no changes. This means set previousKey to
  36866. * currentKey, and clear all of the queues (additions, moves, removals).
  36867. * Set the previousIndexes of moved and added items to their currentIndexes
  36868. * Reset the list of additions, moves and removals
  36869. *
  36870. * @internal
  36871. */
  36872. _reset() {
  36873. if (this.isDirty) {
  36874. let record;
  36875. for (record = this._previousItHead = this._itHead; record !== null; record = record._next) {
  36876. record._nextPrevious = record._next;
  36877. }
  36878. for (record = this._additionsHead; record !== null; record = record._nextAdded) {
  36879. record.previousIndex = record.currentIndex;
  36880. }
  36881. this._additionsHead = this._additionsTail = null;
  36882. for (record = this._movesHead; record !== null; record = record._nextMoved) {
  36883. record.previousIndex = record.currentIndex;
  36884. }
  36885. this._movesHead = this._movesTail = null;
  36886. this._removalsHead = this._removalsTail = null;
  36887. this._identityChangesHead = this._identityChangesTail = null;
  36888. // TODO(vicb): when assert gets supported
  36889. // assert(!this.isDirty);
  36890. }
  36891. }
  36892. /**
  36893. * This is the core function which handles differences between collections.
  36894. *
  36895. * - `record` is the record which we saw at this position last time. If null then it is a new
  36896. * item.
  36897. * - `item` is the current item in the collection
  36898. * - `index` is the position of the item in the collection
  36899. *
  36900. * @internal
  36901. */
  36902. _mismatch(record, item, itemTrackBy, index) {
  36903. // The previous record after which we will append the current one.
  36904. let previousRecord;
  36905. if (record === null) {
  36906. previousRecord = this._itTail;
  36907. }
  36908. else {
  36909. previousRecord = record._prev;
  36910. // Remove the record from the collection since we know it does not match the item.
  36911. this._remove(record);
  36912. }
  36913. // See if we have evicted the item, which used to be at some anterior position of _itHead list.
  36914. record = this._unlinkedRecords === null ? null : this._unlinkedRecords.get(itemTrackBy, null);
  36915. if (record !== null) {
  36916. // It is an item which we have evicted earlier: reinsert it back into the list.
  36917. // But first we need to check if identity changed, so we can update in view if necessary.
  36918. if (!Object.is(record.item, item))
  36919. this._addIdentityChange(record, item);
  36920. this._reinsertAfter(record, previousRecord, index);
  36921. }
  36922. else {
  36923. // Attempt to see if the item is at some posterior position of _itHead list.
  36924. record = this._linkedRecords === null ? null : this._linkedRecords.get(itemTrackBy, index);
  36925. if (record !== null) {
  36926. // We have the item in _itHead at/after `index` position. We need to move it forward in the
  36927. // collection.
  36928. // But first we need to check if identity changed, so we can update in view if necessary.
  36929. if (!Object.is(record.item, item))
  36930. this._addIdentityChange(record, item);
  36931. this._moveAfter(record, previousRecord, index);
  36932. }
  36933. else {
  36934. // It is a new item: add it.
  36935. record = this._addAfter(new IterableChangeRecord_(item, itemTrackBy), previousRecord, index);
  36936. }
  36937. }
  36938. return record;
  36939. }
  36940. /**
  36941. * This check is only needed if an array contains duplicates. (Short circuit of nothing dirty)
  36942. *
  36943. * Use case: `[a, a]` => `[b, a, a]`
  36944. *
  36945. * If we did not have this check then the insertion of `b` would:
  36946. * 1) evict first `a`
  36947. * 2) insert `b` at `0` index.
  36948. * 3) leave `a` at index `1` as is. <-- this is wrong!
  36949. * 3) reinsert `a` at index 2. <-- this is wrong!
  36950. *
  36951. * The correct behavior is:
  36952. * 1) evict first `a`
  36953. * 2) insert `b` at `0` index.
  36954. * 3) reinsert `a` at index 1.
  36955. * 3) move `a` at from `1` to `2`.
  36956. *
  36957. *
  36958. * Double check that we have not evicted a duplicate item. We need to check if the item type may
  36959. * have already been removed:
  36960. * The insertion of b will evict the first 'a'. If we don't reinsert it now it will be reinserted
  36961. * at the end. Which will show up as the two 'a's switching position. This is incorrect, since a
  36962. * better way to think of it is as insert of 'b' rather then switch 'a' with 'b' and then add 'a'
  36963. * at the end.
  36964. *
  36965. * @internal
  36966. */
  36967. _verifyReinsertion(record, item, itemTrackBy, index) {
  36968. let reinsertRecord = this._unlinkedRecords === null ? null : this._unlinkedRecords.get(itemTrackBy, null);
  36969. if (reinsertRecord !== null) {
  36970. record = this._reinsertAfter(reinsertRecord, record._prev, index);
  36971. }
  36972. else if (record.currentIndex != index) {
  36973. record.currentIndex = index;
  36974. this._addToMoves(record, index);
  36975. }
  36976. return record;
  36977. }
  36978. /**
  36979. * Get rid of any excess {@link IterableChangeRecord_}s from the previous collection
  36980. *
  36981. * - `record` The first excess {@link IterableChangeRecord_}.
  36982. *
  36983. * @internal
  36984. */
  36985. _truncate(record) {
  36986. // Anything after that needs to be removed;
  36987. while (record !== null) {
  36988. const nextRecord = record._next;
  36989. this._addToRemovals(this._unlink(record));
  36990. record = nextRecord;
  36991. }
  36992. if (this._unlinkedRecords !== null) {
  36993. this._unlinkedRecords.clear();
  36994. }
  36995. if (this._additionsTail !== null) {
  36996. this._additionsTail._nextAdded = null;
  36997. }
  36998. if (this._movesTail !== null) {
  36999. this._movesTail._nextMoved = null;
  37000. }
  37001. if (this._itTail !== null) {
  37002. this._itTail._next = null;
  37003. }
  37004. if (this._removalsTail !== null) {
  37005. this._removalsTail._nextRemoved = null;
  37006. }
  37007. if (this._identityChangesTail !== null) {
  37008. this._identityChangesTail._nextIdentityChange = null;
  37009. }
  37010. }
  37011. /** @internal */
  37012. _reinsertAfter(record, prevRecord, index) {
  37013. if (this._unlinkedRecords !== null) {
  37014. this._unlinkedRecords.remove(record);
  37015. }
  37016. const prev = record._prevRemoved;
  37017. const next = record._nextRemoved;
  37018. if (prev === null) {
  37019. this._removalsHead = next;
  37020. }
  37021. else {
  37022. prev._nextRemoved = next;
  37023. }
  37024. if (next === null) {
  37025. this._removalsTail = prev;
  37026. }
  37027. else {
  37028. next._prevRemoved = prev;
  37029. }
  37030. this._insertAfter(record, prevRecord, index);
  37031. this._addToMoves(record, index);
  37032. return record;
  37033. }
  37034. /** @internal */
  37035. _moveAfter(record, prevRecord, index) {
  37036. this._unlink(record);
  37037. this._insertAfter(record, prevRecord, index);
  37038. this._addToMoves(record, index);
  37039. return record;
  37040. }
  37041. /** @internal */
  37042. _addAfter(record, prevRecord, index) {
  37043. this._insertAfter(record, prevRecord, index);
  37044. if (this._additionsTail === null) {
  37045. // TODO(vicb):
  37046. // assert(this._additionsHead === null);
  37047. this._additionsTail = this._additionsHead = record;
  37048. }
  37049. else {
  37050. // TODO(vicb):
  37051. // assert(_additionsTail._nextAdded === null);
  37052. // assert(record._nextAdded === null);
  37053. this._additionsTail = this._additionsTail._nextAdded = record;
  37054. }
  37055. return record;
  37056. }
  37057. /** @internal */
  37058. _insertAfter(record, prevRecord, index) {
  37059. // TODO(vicb):
  37060. // assert(record != prevRecord);
  37061. // assert(record._next === null);
  37062. // assert(record._prev === null);
  37063. const next = prevRecord === null ? this._itHead : prevRecord._next;
  37064. // TODO(vicb):
  37065. // assert(next != record);
  37066. // assert(prevRecord != record);
  37067. record._next = next;
  37068. record._prev = prevRecord;
  37069. if (next === null) {
  37070. this._itTail = record;
  37071. }
  37072. else {
  37073. next._prev = record;
  37074. }
  37075. if (prevRecord === null) {
  37076. this._itHead = record;
  37077. }
  37078. else {
  37079. prevRecord._next = record;
  37080. }
  37081. if (this._linkedRecords === null) {
  37082. this._linkedRecords = new _DuplicateMap();
  37083. }
  37084. this._linkedRecords.put(record);
  37085. record.currentIndex = index;
  37086. return record;
  37087. }
  37088. /** @internal */
  37089. _remove(record) {
  37090. return this._addToRemovals(this._unlink(record));
  37091. }
  37092. /** @internal */
  37093. _unlink(record) {
  37094. if (this._linkedRecords !== null) {
  37095. this._linkedRecords.remove(record);
  37096. }
  37097. const prev = record._prev;
  37098. const next = record._next;
  37099. // TODO(vicb):
  37100. // assert((record._prev = null) === null);
  37101. // assert((record._next = null) === null);
  37102. if (prev === null) {
  37103. this._itHead = next;
  37104. }
  37105. else {
  37106. prev._next = next;
  37107. }
  37108. if (next === null) {
  37109. this._itTail = prev;
  37110. }
  37111. else {
  37112. next._prev = prev;
  37113. }
  37114. return record;
  37115. }
  37116. /** @internal */
  37117. _addToMoves(record, toIndex) {
  37118. // TODO(vicb):
  37119. // assert(record._nextMoved === null);
  37120. if (record.previousIndex === toIndex) {
  37121. return record;
  37122. }
  37123. if (this._movesTail === null) {
  37124. // TODO(vicb):
  37125. // assert(_movesHead === null);
  37126. this._movesTail = this._movesHead = record;
  37127. }
  37128. else {
  37129. // TODO(vicb):
  37130. // assert(_movesTail._nextMoved === null);
  37131. this._movesTail = this._movesTail._nextMoved = record;
  37132. }
  37133. return record;
  37134. }
  37135. _addToRemovals(record) {
  37136. if (this._unlinkedRecords === null) {
  37137. this._unlinkedRecords = new _DuplicateMap();
  37138. }
  37139. this._unlinkedRecords.put(record);
  37140. record.currentIndex = null;
  37141. record._nextRemoved = null;
  37142. if (this._removalsTail === null) {
  37143. // TODO(vicb):
  37144. // assert(_removalsHead === null);
  37145. this._removalsTail = this._removalsHead = record;
  37146. record._prevRemoved = null;
  37147. }
  37148. else {
  37149. // TODO(vicb):
  37150. // assert(_removalsTail._nextRemoved === null);
  37151. // assert(record._nextRemoved === null);
  37152. record._prevRemoved = this._removalsTail;
  37153. this._removalsTail = this._removalsTail._nextRemoved = record;
  37154. }
  37155. return record;
  37156. }
  37157. /** @internal */
  37158. _addIdentityChange(record, item) {
  37159. record.item = item;
  37160. if (this._identityChangesTail === null) {
  37161. this._identityChangesTail = this._identityChangesHead = record;
  37162. }
  37163. else {
  37164. this._identityChangesTail = this._identityChangesTail._nextIdentityChange = record;
  37165. }
  37166. return record;
  37167. }
  37168. }
  37169. class IterableChangeRecord_ {
  37170. item;
  37171. trackById;
  37172. currentIndex = null;
  37173. previousIndex = null;
  37174. /** @internal */
  37175. _nextPrevious = null;
  37176. /** @internal */
  37177. _prev = null;
  37178. /** @internal */
  37179. _next = null;
  37180. /** @internal */
  37181. _prevDup = null;
  37182. /** @internal */
  37183. _nextDup = null;
  37184. /** @internal */
  37185. _prevRemoved = null;
  37186. /** @internal */
  37187. _nextRemoved = null;
  37188. /** @internal */
  37189. _nextAdded = null;
  37190. /** @internal */
  37191. _nextMoved = null;
  37192. /** @internal */
  37193. _nextIdentityChange = null;
  37194. constructor(item, trackById) {
  37195. this.item = item;
  37196. this.trackById = trackById;
  37197. }
  37198. }
  37199. // A linked list of IterableChangeRecords with the same IterableChangeRecord_.item
  37200. class _DuplicateItemRecordList {
  37201. /** @internal */
  37202. _head = null;
  37203. /** @internal */
  37204. _tail = null;
  37205. /**
  37206. * Append the record to the list of duplicates.
  37207. *
  37208. * Note: by design all records in the list of duplicates hold the same value in record.item.
  37209. */
  37210. add(record) {
  37211. if (this._head === null) {
  37212. this._head = this._tail = record;
  37213. record._nextDup = null;
  37214. record._prevDup = null;
  37215. }
  37216. else {
  37217. // TODO(vicb):
  37218. // assert(record.item == _head.item ||
  37219. // record.item is num && record.item.isNaN && _head.item is num && _head.item.isNaN);
  37220. this._tail._nextDup = record;
  37221. record._prevDup = this._tail;
  37222. record._nextDup = null;
  37223. this._tail = record;
  37224. }
  37225. }
  37226. // Returns a IterableChangeRecord_ having IterableChangeRecord_.trackById == trackById and
  37227. // IterableChangeRecord_.currentIndex >= atOrAfterIndex
  37228. get(trackById, atOrAfterIndex) {
  37229. let record;
  37230. for (record = this._head; record !== null; record = record._nextDup) {
  37231. if ((atOrAfterIndex === null || atOrAfterIndex <= record.currentIndex) &&
  37232. Object.is(record.trackById, trackById)) {
  37233. return record;
  37234. }
  37235. }
  37236. return null;
  37237. }
  37238. /**
  37239. * Remove one {@link IterableChangeRecord_} from the list of duplicates.
  37240. *
  37241. * Returns whether the list of duplicates is empty.
  37242. */
  37243. remove(record) {
  37244. // TODO(vicb):
  37245. // assert(() {
  37246. // // verify that the record being removed is in the list.
  37247. // for (IterableChangeRecord_ cursor = _head; cursor != null; cursor = cursor._nextDup) {
  37248. // if (identical(cursor, record)) return true;
  37249. // }
  37250. // return false;
  37251. //});
  37252. const prev = record._prevDup;
  37253. const next = record._nextDup;
  37254. if (prev === null) {
  37255. this._head = next;
  37256. }
  37257. else {
  37258. prev._nextDup = next;
  37259. }
  37260. if (next === null) {
  37261. this._tail = prev;
  37262. }
  37263. else {
  37264. next._prevDup = prev;
  37265. }
  37266. return this._head === null;
  37267. }
  37268. }
  37269. class _DuplicateMap {
  37270. map = new Map();
  37271. put(record) {
  37272. const key = record.trackById;
  37273. let duplicates = this.map.get(key);
  37274. if (!duplicates) {
  37275. duplicates = new _DuplicateItemRecordList();
  37276. this.map.set(key, duplicates);
  37277. }
  37278. duplicates.add(record);
  37279. }
  37280. /**
  37281. * Retrieve the `value` using key. Because the IterableChangeRecord_ value may be one which we
  37282. * have already iterated over, we use the `atOrAfterIndex` to pretend it is not there.
  37283. *
  37284. * Use case: `[a, b, c, a, a]` if we are at index `3` which is the second `a` then asking if we
  37285. * have any more `a`s needs to return the second `a`.
  37286. */
  37287. get(trackById, atOrAfterIndex) {
  37288. const key = trackById;
  37289. const recordList = this.map.get(key);
  37290. return recordList ? recordList.get(trackById, atOrAfterIndex) : null;
  37291. }
  37292. /**
  37293. * Removes a {@link IterableChangeRecord_} from the list of duplicates.
  37294. *
  37295. * The list of duplicates also is removed from the map if it gets empty.
  37296. */
  37297. remove(record) {
  37298. const key = record.trackById;
  37299. const recordList = this.map.get(key);
  37300. // Remove the list of duplicates when it gets empty
  37301. if (recordList.remove(record)) {
  37302. this.map.delete(key);
  37303. }
  37304. return record;
  37305. }
  37306. get isEmpty() {
  37307. return this.map.size === 0;
  37308. }
  37309. clear() {
  37310. this.map.clear();
  37311. }
  37312. }
  37313. function getPreviousIndex(item, addRemoveOffset, moveOffsets) {
  37314. const previousIndex = item.previousIndex;
  37315. if (previousIndex === null)
  37316. return previousIndex;
  37317. let moveOffset = 0;
  37318. if (moveOffsets && previousIndex < moveOffsets.length) {
  37319. moveOffset = moveOffsets[previousIndex];
  37320. }
  37321. return previousIndex + addRemoveOffset + moveOffset;
  37322. }
  37323. class DefaultKeyValueDifferFactory {
  37324. constructor() { }
  37325. supports(obj) {
  37326. return obj instanceof Map || isJsObject(obj);
  37327. }
  37328. create() {
  37329. return new DefaultKeyValueDiffer();
  37330. }
  37331. }
  37332. class DefaultKeyValueDiffer {
  37333. _records = new Map();
  37334. _mapHead = null;
  37335. // _appendAfter is used in the check loop
  37336. _appendAfter = null;
  37337. _previousMapHead = null;
  37338. _changesHead = null;
  37339. _changesTail = null;
  37340. _additionsHead = null;
  37341. _additionsTail = null;
  37342. _removalsHead = null;
  37343. _removalsTail = null;
  37344. get isDirty() {
  37345. return (this._additionsHead !== null || this._changesHead !== null || this._removalsHead !== null);
  37346. }
  37347. forEachItem(fn) {
  37348. let record;
  37349. for (record = this._mapHead; record !== null; record = record._next) {
  37350. fn(record);
  37351. }
  37352. }
  37353. forEachPreviousItem(fn) {
  37354. let record;
  37355. for (record = this._previousMapHead; record !== null; record = record._nextPrevious) {
  37356. fn(record);
  37357. }
  37358. }
  37359. forEachChangedItem(fn) {
  37360. let record;
  37361. for (record = this._changesHead; record !== null; record = record._nextChanged) {
  37362. fn(record);
  37363. }
  37364. }
  37365. forEachAddedItem(fn) {
  37366. let record;
  37367. for (record = this._additionsHead; record !== null; record = record._nextAdded) {
  37368. fn(record);
  37369. }
  37370. }
  37371. forEachRemovedItem(fn) {
  37372. let record;
  37373. for (record = this._removalsHead; record !== null; record = record._nextRemoved) {
  37374. fn(record);
  37375. }
  37376. }
  37377. diff(map) {
  37378. if (!map) {
  37379. map = new Map();
  37380. }
  37381. else if (!(map instanceof Map || isJsObject(map))) {
  37382. throw new RuntimeError(900 /* RuntimeErrorCode.INVALID_DIFFER_INPUT */, ngDevMode && `Error trying to diff '${stringify(map)}'. Only maps and objects are allowed`);
  37383. }
  37384. return this.check(map) ? this : null;
  37385. }
  37386. onDestroy() { }
  37387. /**
  37388. * Check the current state of the map vs the previous.
  37389. * The algorithm is optimised for when the keys do no change.
  37390. */
  37391. check(map) {
  37392. this._reset();
  37393. let insertBefore = this._mapHead;
  37394. this._appendAfter = null;
  37395. this._forEach(map, (value, key) => {
  37396. if (insertBefore && insertBefore.key === key) {
  37397. this._maybeAddToChanges(insertBefore, value);
  37398. this._appendAfter = insertBefore;
  37399. insertBefore = insertBefore._next;
  37400. }
  37401. else {
  37402. const record = this._getOrCreateRecordForKey(key, value);
  37403. insertBefore = this._insertBeforeOrAppend(insertBefore, record);
  37404. }
  37405. });
  37406. // Items remaining at the end of the list have been deleted
  37407. if (insertBefore) {
  37408. if (insertBefore._prev) {
  37409. insertBefore._prev._next = null;
  37410. }
  37411. this._removalsHead = insertBefore;
  37412. for (let record = insertBefore; record !== null; record = record._nextRemoved) {
  37413. if (record === this._mapHead) {
  37414. this._mapHead = null;
  37415. }
  37416. this._records.delete(record.key);
  37417. record._nextRemoved = record._next;
  37418. record.previousValue = record.currentValue;
  37419. record.currentValue = null;
  37420. record._prev = null;
  37421. record._next = null;
  37422. }
  37423. }
  37424. // Make sure tails have no next records from previous runs
  37425. if (this._changesTail)
  37426. this._changesTail._nextChanged = null;
  37427. if (this._additionsTail)
  37428. this._additionsTail._nextAdded = null;
  37429. return this.isDirty;
  37430. }
  37431. /**
  37432. * Inserts a record before `before` or append at the end of the list when `before` is null.
  37433. *
  37434. * Notes:
  37435. * - This method appends at `this._appendAfter`,
  37436. * - This method updates `this._appendAfter`,
  37437. * - The return value is the new value for the insertion pointer.
  37438. */
  37439. _insertBeforeOrAppend(before, record) {
  37440. if (before) {
  37441. const prev = before._prev;
  37442. record._next = before;
  37443. record._prev = prev;
  37444. before._prev = record;
  37445. if (prev) {
  37446. prev._next = record;
  37447. }
  37448. if (before === this._mapHead) {
  37449. this._mapHead = record;
  37450. }
  37451. this._appendAfter = before;
  37452. return before;
  37453. }
  37454. if (this._appendAfter) {
  37455. this._appendAfter._next = record;
  37456. record._prev = this._appendAfter;
  37457. }
  37458. else {
  37459. this._mapHead = record;
  37460. }
  37461. this._appendAfter = record;
  37462. return null;
  37463. }
  37464. _getOrCreateRecordForKey(key, value) {
  37465. if (this._records.has(key)) {
  37466. const record = this._records.get(key);
  37467. this._maybeAddToChanges(record, value);
  37468. const prev = record._prev;
  37469. const next = record._next;
  37470. if (prev) {
  37471. prev._next = next;
  37472. }
  37473. if (next) {
  37474. next._prev = prev;
  37475. }
  37476. record._next = null;
  37477. record._prev = null;
  37478. return record;
  37479. }
  37480. const record = new KeyValueChangeRecord_(key);
  37481. this._records.set(key, record);
  37482. record.currentValue = value;
  37483. this._addToAdditions(record);
  37484. return record;
  37485. }
  37486. /** @internal */
  37487. _reset() {
  37488. if (this.isDirty) {
  37489. let record;
  37490. // let `_previousMapHead` contain the state of the map before the changes
  37491. this._previousMapHead = this._mapHead;
  37492. for (record = this._previousMapHead; record !== null; record = record._next) {
  37493. record._nextPrevious = record._next;
  37494. }
  37495. // Update `record.previousValue` with the value of the item before the changes
  37496. // We need to update all changed items (that's those which have been added and changed)
  37497. for (record = this._changesHead; record !== null; record = record._nextChanged) {
  37498. record.previousValue = record.currentValue;
  37499. }
  37500. for (record = this._additionsHead; record != null; record = record._nextAdded) {
  37501. record.previousValue = record.currentValue;
  37502. }
  37503. this._changesHead = this._changesTail = null;
  37504. this._additionsHead = this._additionsTail = null;
  37505. this._removalsHead = null;
  37506. }
  37507. }
  37508. // Add the record or a given key to the list of changes only when the value has actually changed
  37509. _maybeAddToChanges(record, newValue) {
  37510. if (!Object.is(newValue, record.currentValue)) {
  37511. record.previousValue = record.currentValue;
  37512. record.currentValue = newValue;
  37513. this._addToChanges(record);
  37514. }
  37515. }
  37516. _addToAdditions(record) {
  37517. if (this._additionsHead === null) {
  37518. this._additionsHead = this._additionsTail = record;
  37519. }
  37520. else {
  37521. this._additionsTail._nextAdded = record;
  37522. this._additionsTail = record;
  37523. }
  37524. }
  37525. _addToChanges(record) {
  37526. if (this._changesHead === null) {
  37527. this._changesHead = this._changesTail = record;
  37528. }
  37529. else {
  37530. this._changesTail._nextChanged = record;
  37531. this._changesTail = record;
  37532. }
  37533. }
  37534. /** @internal */
  37535. _forEach(obj, fn) {
  37536. if (obj instanceof Map) {
  37537. obj.forEach(fn);
  37538. }
  37539. else {
  37540. Object.keys(obj).forEach((k) => fn(obj[k], k));
  37541. }
  37542. }
  37543. }
  37544. class KeyValueChangeRecord_ {
  37545. key;
  37546. previousValue = null;
  37547. currentValue = null;
  37548. /** @internal */
  37549. _nextPrevious = null;
  37550. /** @internal */
  37551. _next = null;
  37552. /** @internal */
  37553. _prev = null;
  37554. /** @internal */
  37555. _nextAdded = null;
  37556. /** @internal */
  37557. _nextRemoved = null;
  37558. /** @internal */
  37559. _nextChanged = null;
  37560. constructor(key) {
  37561. this.key = key;
  37562. }
  37563. }
  37564. function defaultIterableDiffersFactory() {
  37565. return new IterableDiffers([new DefaultIterableDifferFactory()]);
  37566. }
  37567. /**
  37568. * A repository of different iterable diffing strategies used by NgFor, NgClass, and others.
  37569. *
  37570. * @publicApi
  37571. */
  37572. class IterableDiffers {
  37573. factories;
  37574. /** @nocollapse */
  37575. static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
  37576. token: IterableDiffers,
  37577. providedIn: 'root',
  37578. factory: defaultIterableDiffersFactory,
  37579. });
  37580. constructor(factories) {
  37581. this.factories = factories;
  37582. }
  37583. static create(factories, parent) {
  37584. if (parent != null) {
  37585. const copied = parent.factories.slice();
  37586. factories = factories.concat(copied);
  37587. }
  37588. return new IterableDiffers(factories);
  37589. }
  37590. /**
  37591. * Takes an array of {@link IterableDifferFactory} and returns a provider used to extend the
  37592. * inherited {@link IterableDiffers} instance with the provided factories and return a new
  37593. * {@link IterableDiffers} instance.
  37594. *
  37595. * @usageNotes
  37596. * ### Example
  37597. *
  37598. * The following example shows how to extend an existing list of factories,
  37599. * which will only be applied to the injector for this component and its children.
  37600. * This step is all that's required to make a new {@link IterableDiffer} available.
  37601. *
  37602. * ```ts
  37603. * @Component({
  37604. * viewProviders: [
  37605. * IterableDiffers.extend([new ImmutableListDiffer()])
  37606. * ]
  37607. * })
  37608. * ```
  37609. */
  37610. static extend(factories) {
  37611. return {
  37612. provide: IterableDiffers,
  37613. useFactory: (parent) => {
  37614. // if parent is null, it means that we are in the root injector and we have just overridden
  37615. // the default injection mechanism for IterableDiffers, in such a case just assume
  37616. // `defaultIterableDiffersFactory`.
  37617. return IterableDiffers.create(factories, parent || defaultIterableDiffersFactory());
  37618. },
  37619. // Dependency technically isn't optional, but we can provide a better error message this way.
  37620. deps: [[IterableDiffers, new SkipSelf(), new Optional()]],
  37621. };
  37622. }
  37623. find(iterable) {
  37624. const factory = this.factories.find((f) => f.supports(iterable));
  37625. if (factory != null) {
  37626. return factory;
  37627. }
  37628. else {
  37629. throw new RuntimeError(901 /* RuntimeErrorCode.NO_SUPPORTING_DIFFER_FACTORY */, ngDevMode &&
  37630. `Cannot find a differ supporting object '${iterable}' of type '${getTypeNameForDebugging(iterable)}'`);
  37631. }
  37632. }
  37633. }
  37634. function getTypeNameForDebugging(type) {
  37635. return type['name'] || typeof type;
  37636. }
  37637. function defaultKeyValueDiffersFactory() {
  37638. return new KeyValueDiffers([new DefaultKeyValueDifferFactory()]);
  37639. }
  37640. /**
  37641. * A repository of different Map diffing strategies used by NgClass, NgStyle, and others.
  37642. *
  37643. * @publicApi
  37644. */
  37645. class KeyValueDiffers {
  37646. /** @nocollapse */
  37647. static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
  37648. token: KeyValueDiffers,
  37649. providedIn: 'root',
  37650. factory: defaultKeyValueDiffersFactory,
  37651. });
  37652. factories;
  37653. constructor(factories) {
  37654. this.factories = factories;
  37655. }
  37656. static create(factories, parent) {
  37657. if (parent) {
  37658. const copied = parent.factories.slice();
  37659. factories = factories.concat(copied);
  37660. }
  37661. return new KeyValueDiffers(factories);
  37662. }
  37663. /**
  37664. * Takes an array of {@link KeyValueDifferFactory} and returns a provider used to extend the
  37665. * inherited {@link KeyValueDiffers} instance with the provided factories and return a new
  37666. * {@link KeyValueDiffers} instance.
  37667. *
  37668. * @usageNotes
  37669. * ### Example
  37670. *
  37671. * The following example shows how to extend an existing list of factories,
  37672. * which will only be applied to the injector for this component and its children.
  37673. * This step is all that's required to make a new {@link KeyValueDiffer} available.
  37674. *
  37675. * ```ts
  37676. * @Component({
  37677. * viewProviders: [
  37678. * KeyValueDiffers.extend([new ImmutableMapDiffer()])
  37679. * ]
  37680. * })
  37681. * ```
  37682. */
  37683. static extend(factories) {
  37684. return {
  37685. provide: KeyValueDiffers,
  37686. useFactory: (parent) => {
  37687. // if parent is null, it means that we are in the root injector and we have just overridden
  37688. // the default injection mechanism for KeyValueDiffers, in such a case just assume
  37689. // `defaultKeyValueDiffersFactory`.
  37690. return KeyValueDiffers.create(factories, parent || defaultKeyValueDiffersFactory());
  37691. },
  37692. // Dependency technically isn't optional, but we can provide a better error message this way.
  37693. deps: [[KeyValueDiffers, new SkipSelf(), new Optional()]],
  37694. };
  37695. }
  37696. find(kv) {
  37697. const factory = this.factories.find((f) => f.supports(kv));
  37698. if (factory) {
  37699. return factory;
  37700. }
  37701. throw new RuntimeError(901 /* RuntimeErrorCode.NO_SUPPORTING_DIFFER_FACTORY */, ngDevMode && `Cannot find a differ supporting object '${kv}'`);
  37702. }
  37703. }
  37704. /**
  37705. * Structural diffing for `Object`s and `Map`s.
  37706. */
  37707. const keyValDiff = [new DefaultKeyValueDifferFactory()];
  37708. /**
  37709. * Structural diffing for `Iterable` types such as `Array`s.
  37710. */
  37711. const iterableDiff = [new DefaultIterableDifferFactory()];
  37712. const defaultIterableDiffers = new IterableDiffers(iterableDiff);
  37713. const defaultKeyValueDiffers = new KeyValueDiffers(keyValDiff);
  37714. /**
  37715. * This platform has to be included in any other platform
  37716. *
  37717. * @publicApi
  37718. */
  37719. const platformCore = createPlatformFactory(null, 'core', []);
  37720. /**
  37721. * Re-exported by `BrowserModule`, which is included automatically in the root
  37722. * `AppModule` when you create a new app with the CLI `new` command. Eagerly injects
  37723. * `ApplicationRef` to instantiate it.
  37724. *
  37725. * @publicApi
  37726. */
  37727. class ApplicationModule {
  37728. // Inject ApplicationRef to make it eager...
  37729. constructor(appRef) { }
  37730. static ɵfac = function ApplicationModule_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || ApplicationModule)(ɵɵinject(ApplicationRef)); };
  37731. static ɵmod = /*@__PURE__*/ ɵɵdefineNgModule({ type: ApplicationModule });
  37732. static ɵinj = /*@__PURE__*/ ɵɵdefineInjector({});
  37733. }
  37734. (() => { (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(ApplicationModule, [{
  37735. type: NgModule
  37736. }], () => [{ type: ApplicationRef }], null); })();
  37737. /**
  37738. * Internal create application API that implements the core application creation logic and optional
  37739. * bootstrap logic.
  37740. *
  37741. * Platforms (such as `platform-browser`) may require different set of application and platform
  37742. * providers for an application to function correctly. As a result, platforms may use this function
  37743. * internally and supply the necessary providers during the bootstrap, while exposing
  37744. * platform-specific APIs as a part of their public API.
  37745. *
  37746. * @returns A promise that returns an `ApplicationRef` instance once resolved.
  37747. */
  37748. function internalCreateApplication(config) {
  37749. profiler(8 /* ProfilerEvent.BootstrapApplicationStart */);
  37750. try {
  37751. const { rootComponent, appProviders, platformProviders } = config;
  37752. if ((typeof ngDevMode === 'undefined' || ngDevMode) && rootComponent !== undefined) {
  37753. assertStandaloneComponentType(rootComponent);
  37754. }
  37755. const platformInjector = createOrReusePlatformInjector(platformProviders);
  37756. // Create root application injector based on a set of providers configured at the platform
  37757. // bootstrap level as well as providers passed to the bootstrap call by a user.
  37758. const allAppProviders = [
  37759. internalProvideZoneChangeDetection({}),
  37760. { provide: ChangeDetectionScheduler, useExisting: ChangeDetectionSchedulerImpl },
  37761. ...(appProviders || []),
  37762. ];
  37763. const adapter = new EnvironmentNgModuleRefAdapter({
  37764. providers: allAppProviders,
  37765. parent: platformInjector,
  37766. debugName: typeof ngDevMode === 'undefined' || ngDevMode ? 'Environment Injector' : '',
  37767. // We skip environment initializers because we need to run them inside the NgZone, which
  37768. // happens after we get the NgZone instance from the Injector.
  37769. runEnvironmentInitializers: false,
  37770. });
  37771. return bootstrap({
  37772. r3Injector: adapter.injector,
  37773. platformInjector,
  37774. rootComponent,
  37775. });
  37776. }
  37777. catch (e) {
  37778. return Promise.reject(e);
  37779. }
  37780. finally {
  37781. profiler(9 /* ProfilerEvent.BootstrapApplicationEnd */);
  37782. }
  37783. }
  37784. /** Apps in which we've enabled event replay.
  37785. * This is to prevent initializing event replay more than once per app.
  37786. */
  37787. const appsWithEventReplay = new WeakSet();
  37788. /**
  37789. * The key that represents all replayable elements that are not in defer blocks.
  37790. */
  37791. const EAGER_CONTENT_LISTENERS_KEY = '';
  37792. /**
  37793. * A list of block events that need to be replayed
  37794. */
  37795. let blockEventQueue = [];
  37796. /**
  37797. * Determines whether Event Replay feature should be activated on the client.
  37798. */
  37799. function shouldEnableEventReplay(injector) {
  37800. return injector.get(IS_EVENT_REPLAY_ENABLED, EVENT_REPLAY_ENABLED_DEFAULT);
  37801. }
  37802. /**
  37803. * Returns a set of providers required to setup support for event replay.
  37804. * Requires hydration to be enabled separately.
  37805. */
  37806. function withEventReplay() {
  37807. const providers = [
  37808. {
  37809. provide: IS_EVENT_REPLAY_ENABLED,
  37810. useFactory: () => {
  37811. let isEnabled = true;
  37812. if (typeof ngServerMode === 'undefined' || !ngServerMode) {
  37813. // Note: globalThis[CONTRACT_PROPERTY] may be undefined in case Event Replay feature
  37814. // is enabled, but there are no events configured in this application, in which case
  37815. // we don't activate this feature, since there are no events to replay.
  37816. const appId = inject(APP_ID);
  37817. isEnabled = !!window._ejsas?.[appId];
  37818. }
  37819. if (isEnabled) {
  37820. performanceMarkFeature('NgEventReplay');
  37821. }
  37822. return isEnabled;
  37823. },
  37824. },
  37825. ];
  37826. if (typeof ngServerMode === 'undefined' || !ngServerMode) {
  37827. providers.push({
  37828. provide: ENVIRONMENT_INITIALIZER,
  37829. useValue: () => {
  37830. const appRef = inject(ApplicationRef);
  37831. const { injector } = appRef;
  37832. // We have to check for the appRef here due to the possibility of multiple apps
  37833. // being present on the same page. We only want to enable event replay for the
  37834. // apps that actually want it.
  37835. if (!appsWithEventReplay.has(appRef)) {
  37836. const jsActionMap = inject(JSACTION_BLOCK_ELEMENT_MAP);
  37837. if (shouldEnableEventReplay(injector)) {
  37838. setStashFn((rEl, eventName, listenerFn) => {
  37839. // If a user binds to a ng-container and uses a directive that binds using a host listener,
  37840. // this element could be a comment node. So we need to ensure we have an actual element
  37841. // node before stashing anything.
  37842. if (rEl.nodeType !== Node.ELEMENT_NODE)
  37843. return;
  37844. sharedStashFunction(rEl, eventName, listenerFn);
  37845. sharedMapFunction(rEl, jsActionMap);
  37846. });
  37847. }
  37848. }
  37849. },
  37850. multi: true,
  37851. }, {
  37852. provide: APP_BOOTSTRAP_LISTENER,
  37853. useFactory: () => {
  37854. const appId = inject(APP_ID);
  37855. const appRef = inject(ApplicationRef);
  37856. const { injector } = appRef;
  37857. return () => {
  37858. // We have to check for the appRef here due to the possibility of multiple apps
  37859. // being present on the same page. We only want to enable event replay for the
  37860. // apps that actually want it.
  37861. if (!shouldEnableEventReplay(injector) || appsWithEventReplay.has(appRef)) {
  37862. return;
  37863. }
  37864. appsWithEventReplay.add(appRef);
  37865. appRef.onDestroy(() => {
  37866. appsWithEventReplay.delete(appRef);
  37867. // Ensure that we're always safe calling this in the browser.
  37868. if (typeof ngServerMode !== 'undefined' && !ngServerMode) {
  37869. // `_ejsa` should be deleted when the app is destroyed, ensuring that
  37870. // no elements are still captured in the global list and are not prevented
  37871. // from being garbage collected.
  37872. clearAppScopedEarlyEventContract(appId);
  37873. // Clean up the reference to the function set by the environment initializer,
  37874. // as the function closure may capture injected elements and prevent them
  37875. // from being properly garbage collected.
  37876. setStashFn(() => { });
  37877. }
  37878. });
  37879. // Kick off event replay logic once hydration for the initial part
  37880. // of the application is completed. This timing is similar to the unclaimed
  37881. // dehydrated views cleanup timing.
  37882. appRef.whenStable().then(() => {
  37883. // Note: we have to check whether the application is destroyed before
  37884. // performing other operations with the `injector`.
  37885. // The application may be destroyed **before** it becomes stable, so when
  37886. // the `whenStable` resolves, the injector might already be in
  37887. // a destroyed state. Thus, calling `injector.get` would throw an error
  37888. // indicating that the injector has already been destroyed.
  37889. if (appRef.destroyed) {
  37890. return;
  37891. }
  37892. const eventContractDetails = injector.get(JSACTION_EVENT_CONTRACT);
  37893. initEventReplay(eventContractDetails, injector);
  37894. const jsActionMap = injector.get(JSACTION_BLOCK_ELEMENT_MAP);
  37895. jsActionMap.get(EAGER_CONTENT_LISTENERS_KEY)?.forEach(removeListeners);
  37896. jsActionMap.delete(EAGER_CONTENT_LISTENERS_KEY);
  37897. const eventContract = eventContractDetails.instance;
  37898. // This removes event listeners registered through the container manager,
  37899. // as listeners registered on `document.body` might never be removed if we
  37900. // don't clean up the contract.
  37901. if (isIncrementalHydrationEnabled(injector)) {
  37902. // When incremental hydration is enabled, we cannot clean up the event
  37903. // contract immediately because we're unaware if there are any deferred
  37904. // blocks to hydrate. We can only schedule a contract cleanup when the
  37905. // app is destroyed.
  37906. appRef.onDestroy(() => eventContract.cleanUp());
  37907. }
  37908. else {
  37909. eventContract.cleanUp();
  37910. }
  37911. });
  37912. };
  37913. },
  37914. multi: true,
  37915. });
  37916. }
  37917. return providers;
  37918. }
  37919. const initEventReplay = (eventDelegation, injector) => {
  37920. const appId = injector.get(APP_ID);
  37921. // This is set in packages/platform-server/src/utils.ts
  37922. const earlyJsactionData = window._ejsas[appId];
  37923. const eventContract = (eventDelegation.instance = new EventContract(new EventContractContainer(earlyJsactionData.c)));
  37924. for (const et of earlyJsactionData.et) {
  37925. eventContract.addEvent(et);
  37926. }
  37927. for (const et of earlyJsactionData.etc) {
  37928. eventContract.addEvent(et);
  37929. }
  37930. const eventInfos = getAppScopedQueuedEventInfos(appId);
  37931. eventContract.replayEarlyEventInfos(eventInfos);
  37932. clearAppScopedEarlyEventContract(appId);
  37933. const dispatcher = new EventDispatcher((event) => {
  37934. invokeRegisteredReplayListeners(injector, event, event.currentTarget);
  37935. });
  37936. registerDispatcher(eventContract, dispatcher);
  37937. };
  37938. /**
  37939. * Extracts information about all DOM events (added in a template) registered on elements in a give
  37940. * LView. Maps collected events to a corresponding DOM element (an element is used as a key).
  37941. */
  37942. function collectDomEventsInfo(tView, lView, eventTypesToReplay) {
  37943. const domEventsInfo = new Map();
  37944. const lCleanup = lView[CLEANUP];
  37945. const tCleanup = tView.cleanup;
  37946. if (!tCleanup || !lCleanup) {
  37947. return domEventsInfo;
  37948. }
  37949. for (let i = 0; i < tCleanup.length;) {
  37950. const firstParam = tCleanup[i++];
  37951. const secondParam = tCleanup[i++];
  37952. if (typeof firstParam !== 'string') {
  37953. continue;
  37954. }
  37955. const eventType = firstParam;
  37956. if (!isEarlyEventType(eventType)) {
  37957. continue;
  37958. }
  37959. if (isCaptureEventType(eventType)) {
  37960. eventTypesToReplay.capture.add(eventType);
  37961. }
  37962. else {
  37963. eventTypesToReplay.regular.add(eventType);
  37964. }
  37965. const listenerElement = unwrapRNode(lView[secondParam]);
  37966. i++; // move the cursor to the next position (location of the listener idx)
  37967. const useCaptureOrIndx = tCleanup[i++];
  37968. // if useCaptureOrIndx is boolean then report it as is.
  37969. // if useCaptureOrIndx is positive number then it in unsubscribe method
  37970. // if useCaptureOrIndx is negative number then it is a Subscription
  37971. const isDomEvent = typeof useCaptureOrIndx === 'boolean' || useCaptureOrIndx >= 0;
  37972. if (!isDomEvent) {
  37973. continue;
  37974. }
  37975. if (!domEventsInfo.has(listenerElement)) {
  37976. domEventsInfo.set(listenerElement, [eventType]);
  37977. }
  37978. else {
  37979. domEventsInfo.get(listenerElement).push(eventType);
  37980. }
  37981. }
  37982. return domEventsInfo;
  37983. }
  37984. function invokeRegisteredReplayListeners(injector, event, currentTarget) {
  37985. const blockName = (currentTarget && currentTarget.getAttribute(DEFER_BLOCK_SSR_ID_ATTRIBUTE)) ?? '';
  37986. if (/d\d+/.test(blockName)) {
  37987. hydrateAndInvokeBlockListeners(blockName, injector, event, currentTarget);
  37988. }
  37989. else if (event.eventPhase === EventPhase.REPLAY) {
  37990. invokeListeners(event, currentTarget);
  37991. }
  37992. }
  37993. function hydrateAndInvokeBlockListeners(blockName, injector, event, currentTarget) {
  37994. blockEventQueue.push({ event, currentTarget });
  37995. triggerHydrationFromBlockName(injector, blockName, replayQueuedBlockEvents);
  37996. }
  37997. function replayQueuedBlockEvents(hydratedBlocks) {
  37998. // clone the queue
  37999. const queue = [...blockEventQueue];
  38000. const hydrated = new Set(hydratedBlocks);
  38001. // empty it
  38002. blockEventQueue = [];
  38003. for (let { event, currentTarget } of queue) {
  38004. const blockName = currentTarget.getAttribute(DEFER_BLOCK_SSR_ID_ATTRIBUTE);
  38005. if (hydrated.has(blockName)) {
  38006. invokeListeners(event, currentTarget);
  38007. }
  38008. else {
  38009. // requeue events that weren't yet hydrated
  38010. blockEventQueue.push({ event, currentTarget });
  38011. }
  38012. }
  38013. }
  38014. /**
  38015. * A collection that tracks all serialized views (`ngh` DOM annotations)
  38016. * to avoid duplication. An attempt to add a duplicate view results in the
  38017. * collection returning the index of the previously collected serialized view.
  38018. * This reduces the number of annotations needed for a given page.
  38019. */
  38020. class SerializedViewCollection {
  38021. views = [];
  38022. indexByContent = new Map();
  38023. add(serializedView) {
  38024. const viewAsString = JSON.stringify(serializedView);
  38025. if (!this.indexByContent.has(viewAsString)) {
  38026. const index = this.views.length;
  38027. this.views.push(serializedView);
  38028. this.indexByContent.set(viewAsString, index);
  38029. return index;
  38030. }
  38031. return this.indexByContent.get(viewAsString);
  38032. }
  38033. getAll() {
  38034. return this.views;
  38035. }
  38036. }
  38037. /**
  38038. * Global counter that is used to generate a unique id for TViews
  38039. * during the serialization process.
  38040. */
  38041. let tViewSsrId = 0;
  38042. /**
  38043. * Generates a unique id for a given TView and returns this id.
  38044. * The id is also stored on this instance of a TView and reused in
  38045. * subsequent calls.
  38046. *
  38047. * This id is needed to uniquely identify and pick up dehydrated views
  38048. * at runtime.
  38049. */
  38050. function getSsrId(tView) {
  38051. if (!tView.ssrId) {
  38052. tView.ssrId = `t${tViewSsrId++}`;
  38053. }
  38054. return tView.ssrId;
  38055. }
  38056. /**
  38057. * Computes the number of root nodes in a given view
  38058. * (or child nodes in a given container if a tNode is provided).
  38059. */
  38060. function calcNumRootNodes(tView, lView, tNode) {
  38061. const rootNodes = [];
  38062. collectNativeNodes(tView, lView, tNode, rootNodes);
  38063. return rootNodes.length;
  38064. }
  38065. /**
  38066. * Computes the number of root nodes in all views in a given LContainer.
  38067. */
  38068. function calcNumRootNodesInLContainer(lContainer) {
  38069. const rootNodes = [];
  38070. collectNativeNodesInLContainer(lContainer, rootNodes);
  38071. return rootNodes.length;
  38072. }
  38073. /**
  38074. * Annotates root level component's LView for hydration,
  38075. * see `annotateHostElementForHydration` for additional information.
  38076. */
  38077. function annotateComponentLViewForHydration(lView, context, injector) {
  38078. const hostElement = lView[HOST];
  38079. // Root elements might also be annotated with the `ngSkipHydration` attribute,
  38080. // check if it's present before starting the serialization process.
  38081. if (hostElement && !hostElement.hasAttribute(SKIP_HYDRATION_ATTR_NAME)) {
  38082. return annotateHostElementForHydration(hostElement, lView, null, context);
  38083. }
  38084. return null;
  38085. }
  38086. /**
  38087. * Annotates root level LContainer for hydration. This happens when a root component
  38088. * injects ViewContainerRef, thus making the component an anchor for a view container.
  38089. * This function serializes the component itself as well as all views from the view
  38090. * container.
  38091. */
  38092. function annotateLContainerForHydration(lContainer, context, injector) {
  38093. const componentLView = unwrapLView(lContainer[HOST]);
  38094. // Serialize the root component itself.
  38095. const componentLViewNghIndex = annotateComponentLViewForHydration(componentLView, context);
  38096. if (componentLViewNghIndex === null) {
  38097. // Component was not serialized (for example, if hydration was skipped by adding
  38098. // the `ngSkipHydration` attribute or this component uses i18n blocks in the template,
  38099. // but `withI18nSupport()` was not added), avoid annotating host element with the `ngh`
  38100. // attribute.
  38101. return;
  38102. }
  38103. const hostElement = unwrapRNode(componentLView[HOST]);
  38104. // Serialize all views within this view container.
  38105. const rootLView = lContainer[PARENT];
  38106. const rootLViewNghIndex = annotateHostElementForHydration(hostElement, rootLView, null, context);
  38107. const renderer = componentLView[RENDERER];
  38108. // For cases when a root component also acts as an anchor node for a ViewContainerRef
  38109. // (for example, when ViewContainerRef is injected in a root component), there is a need
  38110. // to serialize information about the component itself, as well as an LContainer that
  38111. // represents this ViewContainerRef. Effectively, we need to serialize 2 pieces of info:
  38112. // (1) hydration info for the root component itself and (2) hydration info for the
  38113. // ViewContainerRef instance (an LContainer). Each piece of information is included into
  38114. // the hydration data (in the TransferState object) separately, thus we end up with 2 ids.
  38115. // Since we only have 1 root element, we encode both bits of info into a single string:
  38116. // ids are separated by the `|` char (e.g. `10|25`, where `10` is the ngh for a component view
  38117. // and 25 is the `ngh` for a root view which holds LContainer).
  38118. const finalIndex = `${componentLViewNghIndex}|${rootLViewNghIndex}`;
  38119. renderer.setAttribute(hostElement, NGH_ATTR_NAME, finalIndex);
  38120. }
  38121. /**
  38122. * Annotates all components bootstrapped in a given ApplicationRef
  38123. * with info needed for hydration.
  38124. *
  38125. * @param appRef An instance of an ApplicationRef.
  38126. * @param doc A reference to the current Document instance.
  38127. * @return event types that need to be replayed
  38128. */
  38129. function annotateForHydration(appRef, doc) {
  38130. const injector = appRef.injector;
  38131. const isI18nHydrationEnabledVal = isI18nHydrationEnabled(injector);
  38132. const isIncrementalHydrationEnabledVal = isIncrementalHydrationEnabled(injector);
  38133. const serializedViewCollection = new SerializedViewCollection();
  38134. const corruptedTextNodes = new Map();
  38135. const viewRefs = appRef._views;
  38136. const shouldReplayEvents = injector.get(IS_EVENT_REPLAY_ENABLED, EVENT_REPLAY_ENABLED_DEFAULT);
  38137. const eventTypesToReplay = {
  38138. regular: new Set(),
  38139. capture: new Set(),
  38140. };
  38141. const deferBlocks = new Map();
  38142. appRef.injector.get(APP_ID);
  38143. for (const viewRef of viewRefs) {
  38144. const lNode = getLNodeForHydration(viewRef);
  38145. // An `lView` might be `null` if a `ViewRef` represents
  38146. // an embedded view (not a component view).
  38147. if (lNode !== null) {
  38148. const context = {
  38149. serializedViewCollection,
  38150. corruptedTextNodes,
  38151. isI18nHydrationEnabled: isI18nHydrationEnabledVal,
  38152. isIncrementalHydrationEnabled: isIncrementalHydrationEnabledVal,
  38153. i18nChildren: new Map(),
  38154. eventTypesToReplay,
  38155. shouldReplayEvents,
  38156. deferBlocks,
  38157. };
  38158. if (isLContainer(lNode)) {
  38159. annotateLContainerForHydration(lNode, context);
  38160. }
  38161. else {
  38162. annotateComponentLViewForHydration(lNode, context);
  38163. }
  38164. insertCorruptedTextNodeMarkers(corruptedTextNodes, doc);
  38165. }
  38166. }
  38167. // Note: we *always* include hydration info key and a corresponding value
  38168. // into the TransferState, even if the list of serialized views is empty.
  38169. // This is needed as a signal to the client that the server part of the
  38170. // hydration logic was setup and enabled correctly. Otherwise, if a client
  38171. // hydration doesn't find a key in the transfer state - an error is produced.
  38172. const serializedViews = serializedViewCollection.getAll();
  38173. const transferState = injector.get(TransferState);
  38174. transferState.set(NGH_DATA_KEY, serializedViews);
  38175. if (deferBlocks.size > 0) {
  38176. const blocks = {};
  38177. for (const [id, info] of deferBlocks.entries()) {
  38178. blocks[id] = info;
  38179. }
  38180. transferState.set(NGH_DEFER_BLOCKS_KEY, blocks);
  38181. }
  38182. return eventTypesToReplay;
  38183. }
  38184. /**
  38185. * Serializes the lContainer data into a list of SerializedView objects,
  38186. * that represent views within this lContainer.
  38187. *
  38188. * @param lContainer the lContainer we are serializing
  38189. * @param tNode the TNode that contains info about this LContainer
  38190. * @param lView that hosts this LContainer
  38191. * @param parentDeferBlockId the defer block id of the parent if it exists
  38192. * @param context the hydration context
  38193. * @returns an array of the `SerializedView` objects
  38194. */
  38195. function serializeLContainer(lContainer, tNode, lView, parentDeferBlockId, context) {
  38196. const views = [];
  38197. let lastViewAsString = '';
  38198. for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
  38199. let childLView = lContainer[i];
  38200. let template;
  38201. let numRootNodes;
  38202. let serializedView;
  38203. if (isRootView(childLView)) {
  38204. // If this is a root view, get an LView for the underlying component,
  38205. // because it contains information about the view to serialize.
  38206. childLView = childLView[HEADER_OFFSET];
  38207. // If we have an LContainer at this position, this indicates that the
  38208. // host element was used as a ViewContainerRef anchor (e.g. a `ViewContainerRef`
  38209. // was injected within the component class). This case requires special handling.
  38210. if (isLContainer(childLView)) {
  38211. // Calculate the number of root nodes in all views in a given container
  38212. // and increment by one to account for an anchor node itself, i.e. in this
  38213. // scenario we'll have a layout that would look like this:
  38214. // `<app-root /><#VIEW1><#VIEW2>...<!--container-->`
  38215. // The `+1` is to capture the `<app-root />` element.
  38216. numRootNodes = calcNumRootNodesInLContainer(childLView) + 1;
  38217. annotateLContainerForHydration(childLView, context);
  38218. const componentLView = unwrapLView(childLView[HOST]);
  38219. serializedView = {
  38220. [TEMPLATE_ID]: componentLView[TVIEW].ssrId,
  38221. [NUM_ROOT_NODES]: numRootNodes,
  38222. };
  38223. }
  38224. }
  38225. if (!serializedView) {
  38226. const childTView = childLView[TVIEW];
  38227. if (childTView.type === 1 /* TViewType.Component */) {
  38228. template = childTView.ssrId;
  38229. // This is a component view, thus it has only 1 root node: the component
  38230. // host node itself (other nodes would be inside that host node).
  38231. numRootNodes = 1;
  38232. }
  38233. else {
  38234. template = getSsrId(childTView);
  38235. numRootNodes = calcNumRootNodes(childTView, childLView, childTView.firstChild);
  38236. }
  38237. serializedView = {
  38238. [TEMPLATE_ID]: template,
  38239. [NUM_ROOT_NODES]: numRootNodes,
  38240. };
  38241. let isHydrateNeverBlock = false;
  38242. // If this is a defer block, serialize extra info.
  38243. if (isDeferBlock(lView[TVIEW], tNode)) {
  38244. const lDetails = getLDeferBlockDetails(lView, tNode);
  38245. const tDetails = getTDeferBlockDetails(lView[TVIEW], tNode);
  38246. if (context.isIncrementalHydrationEnabled && tDetails.hydrateTriggers !== null) {
  38247. const deferBlockId = `d${context.deferBlocks.size}`;
  38248. if (tDetails.hydrateTriggers.has(7 /* DeferBlockTrigger.Never */)) {
  38249. isHydrateNeverBlock = true;
  38250. }
  38251. let rootNodes = [];
  38252. collectNativeNodesInLContainer(lContainer, rootNodes);
  38253. // Add defer block into info context.deferBlocks
  38254. const deferBlockInfo = {
  38255. [NUM_ROOT_NODES]: rootNodes.length,
  38256. [DEFER_BLOCK_STATE$1]: lDetails[DEFER_BLOCK_STATE],
  38257. };
  38258. const serializedTriggers = serializeHydrateTriggers(tDetails.hydrateTriggers);
  38259. if (serializedTriggers.length > 0) {
  38260. deferBlockInfo[DEFER_HYDRATE_TRIGGERS] = serializedTriggers;
  38261. }
  38262. if (parentDeferBlockId !== null) {
  38263. // Serialize parent id only when it's present.
  38264. deferBlockInfo[DEFER_PARENT_BLOCK_ID] = parentDeferBlockId;
  38265. }
  38266. context.deferBlocks.set(deferBlockId, deferBlockInfo);
  38267. const node = unwrapRNode(lContainer);
  38268. if (node !== undefined) {
  38269. if (node.nodeType === Node.COMMENT_NODE) {
  38270. annotateDeferBlockAnchorForHydration(node, deferBlockId);
  38271. }
  38272. }
  38273. else {
  38274. ngDevMode && validateNodeExists(node, childLView, tNode);
  38275. ngDevMode &&
  38276. validateMatchingNode(node, Node.COMMENT_NODE, null, childLView, tNode, true);
  38277. annotateDeferBlockAnchorForHydration(node, deferBlockId);
  38278. }
  38279. if (!isHydrateNeverBlock) {
  38280. // Add JSAction attributes for root nodes that use some hydration triggers
  38281. annotateDeferBlockRootNodesWithJsAction(tDetails, rootNodes, deferBlockId, context);
  38282. }
  38283. // Use current block id as parent for nested routes.
  38284. parentDeferBlockId = deferBlockId;
  38285. // Serialize extra info into the view object.
  38286. // TODO(incremental-hydration): this should be serialized and included at a different level
  38287. // (not at the view level).
  38288. serializedView[DEFER_BLOCK_ID] = deferBlockId;
  38289. }
  38290. // DEFER_BLOCK_STATE is used for reconciliation in hydration, both regular and incremental.
  38291. // We need to know which template is rendered when hydrating. So we serialize this state
  38292. // regardless of hydration type.
  38293. serializedView[DEFER_BLOCK_STATE$1] = lDetails[DEFER_BLOCK_STATE];
  38294. }
  38295. if (!isHydrateNeverBlock) {
  38296. Object.assign(serializedView, serializeLView(lContainer[i], parentDeferBlockId, context));
  38297. }
  38298. }
  38299. // Check if the previous view has the same shape (for example, it was
  38300. // produced by the *ngFor), in which case bump the counter on the previous
  38301. // view instead of including the same information again.
  38302. const currentViewAsString = JSON.stringify(serializedView);
  38303. if (views.length > 0 && currentViewAsString === lastViewAsString) {
  38304. const previousView = views[views.length - 1];
  38305. previousView[MULTIPLIER] ??= 1;
  38306. previousView[MULTIPLIER]++;
  38307. }
  38308. else {
  38309. // Record this view as most recently added.
  38310. lastViewAsString = currentViewAsString;
  38311. views.push(serializedView);
  38312. }
  38313. }
  38314. return views;
  38315. }
  38316. function serializeHydrateTriggers(triggerMap) {
  38317. const serializableDeferBlockTrigger = new Set([
  38318. 0 /* DeferBlockTrigger.Idle */,
  38319. 1 /* DeferBlockTrigger.Immediate */,
  38320. 2 /* DeferBlockTrigger.Viewport */,
  38321. 5 /* DeferBlockTrigger.Timer */,
  38322. ]);
  38323. let triggers = [];
  38324. for (let [trigger, details] of triggerMap) {
  38325. if (serializableDeferBlockTrigger.has(trigger)) {
  38326. if (details === null) {
  38327. triggers.push(trigger);
  38328. }
  38329. else {
  38330. triggers.push({ trigger, delay: details.delay });
  38331. }
  38332. }
  38333. }
  38334. return triggers;
  38335. }
  38336. /**
  38337. * Helper function to produce a node path (which navigation steps runtime logic
  38338. * needs to take to locate a node) and stores it in the `NODES` section of the
  38339. * current serialized view.
  38340. */
  38341. function appendSerializedNodePath(ngh, tNode, lView, excludedParentNodes) {
  38342. const noOffsetIndex = tNode.index - HEADER_OFFSET;
  38343. ngh[NODES] ??= {};
  38344. // Ensure we don't calculate the path multiple times.
  38345. ngh[NODES][noOffsetIndex] ??= calcPathForNode(tNode, lView, excludedParentNodes);
  38346. }
  38347. /**
  38348. * Helper function to append information about a disconnected node.
  38349. * This info is needed at runtime to avoid DOM lookups for this element
  38350. * and instead, the element would be created from scratch.
  38351. */
  38352. function appendDisconnectedNodeIndex(ngh, tNodeOrNoOffsetIndex) {
  38353. const noOffsetIndex = typeof tNodeOrNoOffsetIndex === 'number'
  38354. ? tNodeOrNoOffsetIndex
  38355. : tNodeOrNoOffsetIndex.index - HEADER_OFFSET;
  38356. ngh[DISCONNECTED_NODES] ??= [];
  38357. if (!ngh[DISCONNECTED_NODES].includes(noOffsetIndex)) {
  38358. ngh[DISCONNECTED_NODES].push(noOffsetIndex);
  38359. }
  38360. }
  38361. /**
  38362. * Serializes the lView data into a SerializedView object that will later be added
  38363. * to the TransferState storage and referenced using the `ngh` attribute on a host
  38364. * element.
  38365. *
  38366. * @param lView the lView we are serializing
  38367. * @param context the hydration context
  38368. * @returns the `SerializedView` object containing the data to be added to the host node
  38369. */
  38370. function serializeLView(lView, parentDeferBlockId = null, context) {
  38371. const ngh = {};
  38372. const tView = lView[TVIEW];
  38373. const i18nChildren = getOrComputeI18nChildren(tView, context);
  38374. const nativeElementsToEventTypes = context.shouldReplayEvents
  38375. ? collectDomEventsInfo(tView, lView, context.eventTypesToReplay)
  38376. : null;
  38377. // Iterate over DOM element references in an LView.
  38378. for (let i = HEADER_OFFSET; i < tView.bindingStartIndex; i++) {
  38379. const tNode = tView.data[i];
  38380. const noOffsetIndex = i - HEADER_OFFSET;
  38381. // Attempt to serialize any i18n data for the given slot. We do this first, as i18n
  38382. // has its own process for serialization.
  38383. const i18nData = trySerializeI18nBlock(lView, i, context);
  38384. if (i18nData) {
  38385. ngh[I18N_DATA] ??= {};
  38386. ngh[I18N_DATA][noOffsetIndex] = i18nData.caseQueue;
  38387. for (const nodeNoOffsetIndex of i18nData.disconnectedNodes) {
  38388. appendDisconnectedNodeIndex(ngh, nodeNoOffsetIndex);
  38389. }
  38390. for (const nodeNoOffsetIndex of i18nData.disjointNodes) {
  38391. const tNode = tView.data[nodeNoOffsetIndex + HEADER_OFFSET];
  38392. ngDevMode && assertTNode(tNode);
  38393. appendSerializedNodePath(ngh, tNode, lView, i18nChildren);
  38394. }
  38395. continue;
  38396. }
  38397. // Skip processing of a given slot in the following cases:
  38398. // - Local refs (e.g. <div #localRef>) take up an extra slot in LViews
  38399. // to store the same element. In this case, there is no information in
  38400. // a corresponding slot in TNode data structure.
  38401. // - When a slot contains something other than a TNode. For example, there
  38402. // might be some metadata information about a defer block or a control flow block.
  38403. if (!isTNodeShape(tNode)) {
  38404. continue;
  38405. }
  38406. // Skip any nodes that are in an i18n block but are considered detached (i.e. not
  38407. // present in the template). These nodes are disconnected from the DOM tree, and
  38408. // so we don't want to serialize any information about them.
  38409. if (isDetachedByI18n(tNode)) {
  38410. continue;
  38411. }
  38412. // Check if a native node that represents a given TNode is disconnected from the DOM tree.
  38413. // Such nodes must be excluded from the hydration (since the hydration won't be able to
  38414. // find them), so the TNode ids are collected and used at runtime to skip the hydration.
  38415. //
  38416. // This situation may happen during the content projection, when some nodes don't make it
  38417. // into one of the content projection slots (for example, when there is no default
  38418. // <ng-content /> slot in projector component's template).
  38419. if (isDisconnectedNode(tNode, lView) && isContentProjectedNode(tNode)) {
  38420. appendDisconnectedNodeIndex(ngh, tNode);
  38421. continue;
  38422. }
  38423. if (Array.isArray(tNode.projection)) {
  38424. for (const projectionHeadTNode of tNode.projection) {
  38425. // We may have `null`s in slots with no projected content.
  38426. if (!projectionHeadTNode)
  38427. continue;
  38428. if (!Array.isArray(projectionHeadTNode)) {
  38429. // If we process re-projected content (i.e. `<ng-content>`
  38430. // appears at projection location), skip annotations for this content
  38431. // since all DOM nodes in this projection were handled while processing
  38432. // a parent lView, which contains those nodes.
  38433. if (!isProjectionTNode(projectionHeadTNode) &&
  38434. !isInSkipHydrationBlock(projectionHeadTNode)) {
  38435. if (isDisconnectedNode(projectionHeadTNode, lView)) {
  38436. // Check whether this node is connected, since we may have a TNode
  38437. // in the data structure as a projection segment head, but the
  38438. // content projection slot might be disabled (e.g.
  38439. // <ng-content *ngIf="false" />).
  38440. appendDisconnectedNodeIndex(ngh, projectionHeadTNode);
  38441. }
  38442. else {
  38443. appendSerializedNodePath(ngh, projectionHeadTNode, lView, i18nChildren);
  38444. }
  38445. }
  38446. }
  38447. else {
  38448. // If a value is an array, it means that we are processing a projection
  38449. // where projectable nodes were passed in as DOM nodes (for example, when
  38450. // calling `ViewContainerRef.createComponent(CmpA, {projectableNodes: [...]})`).
  38451. //
  38452. // In this scenario, nodes can come from anywhere (either created manually,
  38453. // accessed via `document.querySelector`, etc) and may be in any state
  38454. // (attached or detached from the DOM tree). As a result, we can not reliably
  38455. // restore the state for such cases during hydration.
  38456. throw unsupportedProjectionOfDomNodes(unwrapRNode(lView[i]));
  38457. }
  38458. }
  38459. }
  38460. conditionallyAnnotateNodePath(ngh, tNode, lView, i18nChildren);
  38461. if (isLContainer(lView[i])) {
  38462. // Serialize information about a template.
  38463. const embeddedTView = tNode.tView;
  38464. if (embeddedTView !== null) {
  38465. ngh[TEMPLATES] ??= {};
  38466. ngh[TEMPLATES][noOffsetIndex] = getSsrId(embeddedTView);
  38467. }
  38468. // Serialize views within this LContainer.
  38469. const hostNode = lView[i][HOST]; // host node of this container
  38470. // LView[i][HOST] can be of 2 different types:
  38471. // - either a DOM node
  38472. // - or an array that represents an LView of a component
  38473. if (Array.isArray(hostNode)) {
  38474. // This is a component, serialize info about it.
  38475. const targetNode = unwrapRNode(hostNode);
  38476. if (!targetNode.hasAttribute(SKIP_HYDRATION_ATTR_NAME)) {
  38477. annotateHostElementForHydration(targetNode, hostNode, parentDeferBlockId, context);
  38478. }
  38479. }
  38480. ngh[CONTAINERS] ??= {};
  38481. ngh[CONTAINERS][noOffsetIndex] = serializeLContainer(lView[i], tNode, lView, parentDeferBlockId, context);
  38482. }
  38483. else if (Array.isArray(lView[i]) && !isLetDeclaration(tNode)) {
  38484. // This is a component, annotate the host node with an `ngh` attribute.
  38485. // Note: Let declarations that return an array are also storing an array in the LView,
  38486. // we need to exclude them.
  38487. const targetNode = unwrapRNode(lView[i][HOST]);
  38488. if (!targetNode.hasAttribute(SKIP_HYDRATION_ATTR_NAME)) {
  38489. annotateHostElementForHydration(targetNode, lView[i], parentDeferBlockId, context);
  38490. }
  38491. }
  38492. else {
  38493. // <ng-container> case
  38494. if (tNode.type & 8 /* TNodeType.ElementContainer */) {
  38495. // An <ng-container> is represented by the number of
  38496. // top-level nodes. This information is needed to skip over
  38497. // those nodes to reach a corresponding anchor node (comment node).
  38498. ngh[ELEMENT_CONTAINERS] ??= {};
  38499. ngh[ELEMENT_CONTAINERS][noOffsetIndex] = calcNumRootNodes(tView, lView, tNode.child);
  38500. }
  38501. else if (tNode.type & (16 /* TNodeType.Projection */ | 128 /* TNodeType.LetDeclaration */)) {
  38502. // Current TNode represents an `<ng-content>` slot or `@let` declaration,
  38503. // thus it has no DOM elements associated with it, so the **next sibling**
  38504. // node would not be able to find an anchor. In this case, use full path instead.
  38505. let nextTNode = tNode.next;
  38506. // Skip over all `<ng-content>` slots and `@let` declarations in a row.
  38507. while (nextTNode !== null &&
  38508. nextTNode.type & (16 /* TNodeType.Projection */ | 128 /* TNodeType.LetDeclaration */)) {
  38509. nextTNode = nextTNode.next;
  38510. }
  38511. if (nextTNode && !isInSkipHydrationBlock(nextTNode)) {
  38512. // Handle a tNode after the `<ng-content>` slot.
  38513. appendSerializedNodePath(ngh, nextTNode, lView, i18nChildren);
  38514. }
  38515. }
  38516. else if (tNode.type & 1 /* TNodeType.Text */) {
  38517. const rNode = unwrapRNode(lView[i]);
  38518. processTextNodeBeforeSerialization(context, rNode);
  38519. }
  38520. }
  38521. // Attach `jsaction` attribute to elements that have registered listeners,
  38522. // thus potentially having a need to do an event replay.
  38523. if (nativeElementsToEventTypes && tNode.type & 2 /* TNodeType.Element */) {
  38524. const nativeElement = unwrapRNode(lView[i]);
  38525. if (nativeElementsToEventTypes.has(nativeElement)) {
  38526. setJSActionAttributes(nativeElement, nativeElementsToEventTypes.get(nativeElement), parentDeferBlockId);
  38527. }
  38528. }
  38529. }
  38530. return ngh;
  38531. }
  38532. /**
  38533. * Serializes node location in cases when it's needed, specifically:
  38534. *
  38535. * 1. If `tNode.projectionNext` is different from `tNode.next` - it means that
  38536. * the next `tNode` after projection is different from the one in the original
  38537. * template. Since hydration relies on `tNode.next`, this serialized info
  38538. * is required to help runtime code find the node at the correct location.
  38539. * 2. In certain content projection-based use-cases, it's possible that only
  38540. * a content of a projected element is rendered. In this case, content nodes
  38541. * require an extra annotation, since runtime logic can't rely on parent-child
  38542. * connection to identify the location of a node.
  38543. */
  38544. function conditionallyAnnotateNodePath(ngh, tNode, lView, excludedParentNodes) {
  38545. if (isProjectionTNode(tNode)) {
  38546. // Do not annotate projection nodes (<ng-content />), since
  38547. // they don't have a corresponding DOM node representing them.
  38548. return;
  38549. }
  38550. // Handle case #1 described above.
  38551. if (tNode.projectionNext &&
  38552. tNode.projectionNext !== tNode.next &&
  38553. !isInSkipHydrationBlock(tNode.projectionNext)) {
  38554. appendSerializedNodePath(ngh, tNode.projectionNext, lView, excludedParentNodes);
  38555. }
  38556. // Handle case #2 described above.
  38557. // Note: we only do that for the first node (i.e. when `tNode.prev === null`),
  38558. // the rest of the nodes would rely on the current node location, so no extra
  38559. // annotation is needed.
  38560. if (tNode.prev === null &&
  38561. tNode.parent !== null &&
  38562. isDisconnectedNode(tNode.parent, lView) &&
  38563. !isDisconnectedNode(tNode, lView)) {
  38564. appendSerializedNodePath(ngh, tNode, lView, excludedParentNodes);
  38565. }
  38566. }
  38567. /**
  38568. * Determines whether a component instance that is represented
  38569. * by a given LView uses `ViewEncapsulation.ShadowDom`.
  38570. */
  38571. function componentUsesShadowDomEncapsulation(lView) {
  38572. const instance = lView[CONTEXT];
  38573. return instance?.constructor
  38574. ? getComponentDef(instance.constructor)?.encapsulation === ViewEncapsulation.ShadowDom
  38575. : false;
  38576. }
  38577. /**
  38578. * Annotates component host element for hydration:
  38579. * - by either adding the `ngh` attribute and collecting hydration-related info
  38580. * for the serialization and transferring to the client
  38581. * - or by adding the `ngSkipHydration` attribute in case Angular detects that
  38582. * component contents is not compatible with hydration.
  38583. *
  38584. * @param element The Host element to be annotated
  38585. * @param lView The associated LView
  38586. * @param context The hydration context
  38587. * @returns An index of serialized view from the transfer state object
  38588. * or `null` when a given component can not be serialized.
  38589. */
  38590. function annotateHostElementForHydration(element, lView, parentDeferBlockId, context) {
  38591. const renderer = lView[RENDERER];
  38592. if ((hasI18n(lView) && !isI18nHydrationSupportEnabled()) ||
  38593. componentUsesShadowDomEncapsulation(lView)) {
  38594. // Attach the skip hydration attribute if this component:
  38595. // - either has i18n blocks, since hydrating such blocks is not yet supported
  38596. // - or uses ShadowDom view encapsulation, since Domino doesn't support
  38597. // shadow DOM, so we can not guarantee that client and server representations
  38598. // would exactly match
  38599. renderer.setAttribute(element, SKIP_HYDRATION_ATTR_NAME, '');
  38600. return null;
  38601. }
  38602. else {
  38603. const ngh = serializeLView(lView, parentDeferBlockId, context);
  38604. const index = context.serializedViewCollection.add(ngh);
  38605. renderer.setAttribute(element, NGH_ATTR_NAME, index.toString());
  38606. return index;
  38607. }
  38608. }
  38609. /**
  38610. * Annotates defer block comment node for hydration:
  38611. *
  38612. * @param comment The Host element to be annotated
  38613. * @param deferBlockId the id of the target defer block
  38614. */
  38615. function annotateDeferBlockAnchorForHydration(comment, deferBlockId) {
  38616. comment.textContent = `ngh=${deferBlockId}`;
  38617. }
  38618. /**
  38619. * Physically inserts the comment nodes to ensure empty text nodes and adjacent
  38620. * text node separators are preserved after server serialization of the DOM.
  38621. * These get swapped back for empty text nodes or separators once hydration happens
  38622. * on the client.
  38623. *
  38624. * @param corruptedTextNodes The Map of text nodes to be replaced with comments
  38625. * @param doc The document
  38626. */
  38627. function insertCorruptedTextNodeMarkers(corruptedTextNodes, doc) {
  38628. for (const [textNode, marker] of corruptedTextNodes) {
  38629. textNode.after(doc.createComment(marker));
  38630. }
  38631. }
  38632. /**
  38633. * Detects whether a given TNode represents a node that
  38634. * is being content projected.
  38635. */
  38636. function isContentProjectedNode(tNode) {
  38637. let currentTNode = tNode;
  38638. while (currentTNode != null) {
  38639. // If we come across a component host node in parent nodes -
  38640. // this TNode is in the content projection section.
  38641. if (isComponentHost(currentTNode)) {
  38642. return true;
  38643. }
  38644. currentTNode = currentTNode.parent;
  38645. }
  38646. return false;
  38647. }
  38648. /**
  38649. * Incremental hydration requires that any defer block root node
  38650. * with interaction or hover triggers have all of their root nodes
  38651. * trigger hydration with those events. So we need to make sure all
  38652. * the root nodes of that block have the proper jsaction attribute
  38653. * to ensure hydration is triggered, since the content is dehydrated
  38654. */
  38655. function annotateDeferBlockRootNodesWithJsAction(tDetails, rootNodes, parentDeferBlockId, context) {
  38656. const actionList = convertHydrateTriggersToJsAction(tDetails.hydrateTriggers);
  38657. for (let et of actionList) {
  38658. context.eventTypesToReplay.regular.add(et);
  38659. }
  38660. if (actionList.length > 0) {
  38661. const elementNodes = rootNodes.filter((rn) => rn.nodeType === Node.ELEMENT_NODE);
  38662. for (let rNode of elementNodes) {
  38663. setJSActionAttributes(rNode, actionList, parentDeferBlockId);
  38664. }
  38665. }
  38666. }
  38667. /**
  38668. * Indicates whether the hydration-related code was added,
  38669. * prevents adding it multiple times.
  38670. */
  38671. let isHydrationSupportEnabled = false;
  38672. /**
  38673. * Indicates whether the i18n-related code was added,
  38674. * prevents adding it multiple times.
  38675. *
  38676. * Note: This merely controls whether the code is loaded,
  38677. * while `setIsI18nHydrationSupportEnabled` determines
  38678. * whether i18n blocks are serialized or hydrated.
  38679. */
  38680. let isI18nHydrationRuntimeSupportEnabled = false;
  38681. /**
  38682. * Indicates whether the incremental hydration code was added,
  38683. * prevents adding it multiple times.
  38684. */
  38685. let isIncrementalHydrationRuntimeSupportEnabled = false;
  38686. /**
  38687. * Defines a period of time that Angular waits for the `ApplicationRef.isStable` to emit `true`.
  38688. * If there was no event with the `true` value during this time, Angular reports a warning.
  38689. */
  38690. const APPLICATION_IS_STABLE_TIMEOUT = 10_000;
  38691. /**
  38692. * Brings the necessary hydration code in tree-shakable manner.
  38693. * The code is only present when the `provideClientHydration` is
  38694. * invoked. Otherwise, this code is tree-shaken away during the
  38695. * build optimization step.
  38696. *
  38697. * This technique allows us to swap implementations of methods so
  38698. * tree shaking works appropriately when hydration is disabled or
  38699. * enabled. It brings in the appropriate version of the method that
  38700. * supports hydration only when enabled.
  38701. */
  38702. function enableHydrationRuntimeSupport() {
  38703. if (!isHydrationSupportEnabled) {
  38704. isHydrationSupportEnabled = true;
  38705. enableRetrieveHydrationInfoImpl();
  38706. enableLocateOrCreateElementNodeImpl();
  38707. enableLocateOrCreateTextNodeImpl();
  38708. enableLocateOrCreateElementContainerNodeImpl();
  38709. enableLocateOrCreateContainerAnchorImpl();
  38710. enableLocateOrCreateContainerRefImpl();
  38711. enableFindMatchingDehydratedViewImpl();
  38712. enableApplyRootElementTransformImpl();
  38713. }
  38714. }
  38715. /**
  38716. * Brings the necessary i18n hydration code in tree-shakable manner.
  38717. * Similar to `enableHydrationRuntimeSupport`, the code is only
  38718. * present when `withI18nSupport` is invoked.
  38719. */
  38720. function enableI18nHydrationRuntimeSupport() {
  38721. if (!isI18nHydrationRuntimeSupportEnabled) {
  38722. isI18nHydrationRuntimeSupportEnabled = true;
  38723. enableLocateOrCreateI18nNodeImpl();
  38724. enablePrepareI18nBlockForHydrationImpl();
  38725. enableClaimDehydratedIcuCaseImpl();
  38726. }
  38727. }
  38728. /**
  38729. * Brings the necessary incremental hydration code in tree-shakable manner.
  38730. * Similar to `enableHydrationRuntimeSupport`, the code is only
  38731. * present when `enableIncrementalHydrationRuntimeSupport` is invoked.
  38732. */
  38733. function enableIncrementalHydrationRuntimeSupport() {
  38734. if (!isIncrementalHydrationRuntimeSupportEnabled) {
  38735. isIncrementalHydrationRuntimeSupportEnabled = true;
  38736. enableRetrieveDeferBlockDataImpl();
  38737. }
  38738. }
  38739. /**
  38740. * Outputs a message with hydration stats into a console.
  38741. */
  38742. function printHydrationStats(injector) {
  38743. const console = injector.get(Console);
  38744. const message = `Angular hydrated ${ngDevMode.hydratedComponents} component(s) ` +
  38745. `and ${ngDevMode.hydratedNodes} node(s), ` +
  38746. `${ngDevMode.componentsSkippedHydration} component(s) were skipped. ` +
  38747. (isIncrementalHydrationEnabled(injector)
  38748. ? `${ngDevMode.deferBlocksWithIncrementalHydration} defer block(s) were configured to use incremental hydration. `
  38749. : '') +
  38750. `Learn more at https://angular.dev/guide/hydration.`;
  38751. // tslint:disable-next-line:no-console
  38752. console.log(message);
  38753. }
  38754. /**
  38755. * Returns a Promise that is resolved when an application becomes stable.
  38756. */
  38757. function whenStableWithTimeout(appRef) {
  38758. const whenStablePromise = appRef.whenStable();
  38759. if (typeof ngDevMode !== 'undefined' && ngDevMode) {
  38760. const timeoutTime = APPLICATION_IS_STABLE_TIMEOUT;
  38761. const console = appRef.injector.get(Console);
  38762. const ngZone = appRef.injector.get(NgZone);
  38763. // The following call should not and does not prevent the app to become stable
  38764. // We cannot use RxJS timer here because the app would remain unstable.
  38765. // This also avoids an extra change detection cycle.
  38766. const timeoutId = ngZone.runOutsideAngular(() => {
  38767. return setTimeout(() => logWarningOnStableTimedout(timeoutTime, console), timeoutTime);
  38768. });
  38769. whenStablePromise.finally(() => clearTimeout(timeoutId));
  38770. }
  38771. return whenStablePromise;
  38772. }
  38773. /**
  38774. * Defines a name of an attribute that is added to the <body> tag
  38775. * in the `index.html` file in case a given route was configured
  38776. * with `RenderMode.Client`. 'cm' is an abbreviation for "Client Mode".
  38777. */
  38778. const CLIENT_RENDER_MODE_FLAG = 'ngcm';
  38779. /**
  38780. * Checks whether the `RenderMode.Client` was defined for the current route.
  38781. */
  38782. function isClientRenderModeEnabled() {
  38783. const doc = getDocument();
  38784. return ((typeof ngServerMode === 'undefined' || !ngServerMode) &&
  38785. doc.body.hasAttribute(CLIENT_RENDER_MODE_FLAG));
  38786. }
  38787. /**
  38788. * Returns a set of providers required to setup hydration support
  38789. * for an application that is server side rendered. This function is
  38790. * included into the `provideClientHydration` public API function from
  38791. * the `platform-browser` package.
  38792. *
  38793. * The function sets up an internal flag that would be recognized during
  38794. * the server side rendering time as well, so there is no need to
  38795. * configure or change anything in NgUniversal to enable the feature.
  38796. */
  38797. function withDomHydration() {
  38798. const providers = [
  38799. {
  38800. provide: IS_HYDRATION_DOM_REUSE_ENABLED,
  38801. useFactory: () => {
  38802. let isEnabled = true;
  38803. if (typeof ngServerMode === 'undefined' || !ngServerMode) {
  38804. // On the client, verify that the server response contains
  38805. // hydration annotations. Otherwise, keep hydration disabled.
  38806. const transferState = inject(TransferState, { optional: true });
  38807. isEnabled = !!transferState?.get(NGH_DATA_KEY, null);
  38808. }
  38809. if (isEnabled) {
  38810. performanceMarkFeature('NgHydration');
  38811. }
  38812. return isEnabled;
  38813. },
  38814. },
  38815. {
  38816. provide: ENVIRONMENT_INITIALIZER,
  38817. useValue: () => {
  38818. // i18n support is enabled by calling withI18nSupport(), but there's
  38819. // no way to turn it off (e.g. for tests), so we turn it off by default.
  38820. setIsI18nHydrationSupportEnabled(false);
  38821. if (typeof ngServerMode !== 'undefined' && ngServerMode) {
  38822. // Since this function is used across both server and client,
  38823. // make sure that the runtime code is only added when invoked
  38824. // on the client (see the `enableHydrationRuntimeSupport` function
  38825. // call below).
  38826. return;
  38827. }
  38828. if (inject(IS_HYDRATION_DOM_REUSE_ENABLED)) {
  38829. verifySsrContentsIntegrity(getDocument());
  38830. enableHydrationRuntimeSupport();
  38831. }
  38832. else if (typeof ngDevMode !== 'undefined' && ngDevMode && !isClientRenderModeEnabled()) {
  38833. const console = inject(Console);
  38834. const message = formatRuntimeError(-505 /* RuntimeErrorCode.MISSING_HYDRATION_ANNOTATIONS */, 'Angular hydration was requested on the client, but there was no ' +
  38835. 'serialized information present in the server response, ' +
  38836. 'thus hydration was not enabled. ' +
  38837. 'Make sure the `provideClientHydration()` is included into the list ' +
  38838. 'of providers in the server part of the application configuration.');
  38839. console.warn(message);
  38840. }
  38841. },
  38842. multi: true,
  38843. },
  38844. ];
  38845. if (typeof ngServerMode === 'undefined' || !ngServerMode) {
  38846. providers.push({
  38847. provide: PRESERVE_HOST_CONTENT,
  38848. useFactory: () => {
  38849. // Preserve host element content only in a browser
  38850. // environment and when hydration is configured properly.
  38851. // On a server, an application is rendered from scratch,
  38852. // so the host content needs to be empty.
  38853. return inject(IS_HYDRATION_DOM_REUSE_ENABLED);
  38854. },
  38855. }, {
  38856. provide: APP_BOOTSTRAP_LISTENER,
  38857. useFactory: () => {
  38858. if (inject(IS_HYDRATION_DOM_REUSE_ENABLED)) {
  38859. const appRef = inject(ApplicationRef);
  38860. return () => {
  38861. // Wait until an app becomes stable and cleanup all views that
  38862. // were not claimed during the application bootstrap process.
  38863. // The timing is similar to when we start the serialization process
  38864. // on the server.
  38865. //
  38866. // Note: the cleanup task *MUST* be scheduled within the Angular zone in Zone apps
  38867. // to ensure that change detection is properly run afterward.
  38868. whenStableWithTimeout(appRef).then(() => {
  38869. // Note: we have to check whether the application is destroyed before
  38870. // performing other operations with the `injector`.
  38871. // The application may be destroyed **before** it becomes stable, so when
  38872. // the `whenStableWithTimeout` resolves, the injector might already be in
  38873. // a destroyed state. Thus, calling `injector.get` would throw an error
  38874. // indicating that the injector has already been destroyed.
  38875. if (appRef.destroyed) {
  38876. return;
  38877. }
  38878. cleanupDehydratedViews(appRef);
  38879. if (typeof ngDevMode !== 'undefined' && ngDevMode) {
  38880. countBlocksSkippedByHydration(appRef.injector);
  38881. printHydrationStats(appRef.injector);
  38882. }
  38883. });
  38884. };
  38885. }
  38886. return () => { }; // noop
  38887. },
  38888. multi: true,
  38889. });
  38890. }
  38891. return makeEnvironmentProviders(providers);
  38892. }
  38893. /**
  38894. * Returns a set of providers required to setup support for i18n hydration.
  38895. * Requires hydration to be enabled separately.
  38896. */
  38897. function withI18nSupport() {
  38898. return [
  38899. {
  38900. provide: IS_I18N_HYDRATION_ENABLED,
  38901. useFactory: () => inject(IS_HYDRATION_DOM_REUSE_ENABLED),
  38902. },
  38903. {
  38904. provide: ENVIRONMENT_INITIALIZER,
  38905. useValue: () => {
  38906. if (inject(IS_HYDRATION_DOM_REUSE_ENABLED)) {
  38907. enableI18nHydrationRuntimeSupport();
  38908. setIsI18nHydrationSupportEnabled(true);
  38909. performanceMarkFeature('NgI18nHydration');
  38910. }
  38911. },
  38912. multi: true,
  38913. },
  38914. ];
  38915. }
  38916. /**
  38917. * Returns a set of providers required to setup support for incremental hydration.
  38918. * Requires hydration to be enabled separately.
  38919. * Enabling incremental hydration also enables event replay for the entire app.
  38920. *
  38921. * @developerPreview
  38922. */
  38923. function withIncrementalHydration() {
  38924. const providers = [
  38925. withEventReplay(),
  38926. {
  38927. provide: IS_INCREMENTAL_HYDRATION_ENABLED,
  38928. useValue: true,
  38929. },
  38930. {
  38931. provide: DEHYDRATED_BLOCK_REGISTRY,
  38932. useClass: DehydratedBlockRegistry,
  38933. },
  38934. {
  38935. provide: ENVIRONMENT_INITIALIZER,
  38936. useValue: () => {
  38937. enableIncrementalHydrationRuntimeSupport();
  38938. performanceMarkFeature('NgIncrementalHydration');
  38939. },
  38940. multi: true,
  38941. },
  38942. ];
  38943. if (typeof ngServerMode === 'undefined' || !ngServerMode) {
  38944. providers.push({
  38945. provide: APP_BOOTSTRAP_LISTENER,
  38946. useFactory: () => {
  38947. const injector = inject(Injector);
  38948. const doc = getDocument();
  38949. return () => {
  38950. const deferBlockData = processBlockData(injector);
  38951. const commentsByBlockId = gatherDeferBlocksCommentNodes(doc, doc.body);
  38952. processAndInitTriggers(injector, deferBlockData, commentsByBlockId);
  38953. appendDeferBlocksToJSActionMap(doc, injector);
  38954. };
  38955. },
  38956. multi: true,
  38957. });
  38958. }
  38959. return providers;
  38960. }
  38961. /**
  38962. *
  38963. * @param time The time in ms until the stable timedout warning message is logged
  38964. */
  38965. function logWarningOnStableTimedout(time, console) {
  38966. const message = `Angular hydration expected the ApplicationRef.isStable() to emit \`true\`, but it ` +
  38967. `didn't happen within ${time}ms. Angular hydration logic depends on the application becoming stable ` +
  38968. `as a signal to complete hydration process.`;
  38969. console.warn(formatRuntimeError(-506 /* RuntimeErrorCode.HYDRATION_STABLE_TIMEDOUT */, message));
  38970. }
  38971. /**
  38972. * Transforms a value (typically a string) to a boolean.
  38973. * Intended to be used as a transform function of an input.
  38974. *
  38975. * @usageNotes
  38976. * ```ts
  38977. * @Input({ transform: booleanAttribute }) status!: boolean;
  38978. * ```
  38979. * @param value Value to be transformed.
  38980. *
  38981. * @publicApi
  38982. */
  38983. function booleanAttribute(value) {
  38984. return typeof value === 'boolean' ? value : value != null && value !== 'false';
  38985. }
  38986. /**
  38987. * Transforms a value (typically a string) to a number.
  38988. * Intended to be used as a transform function of an input.
  38989. * @param value Value to be transformed.
  38990. * @param fallbackValue Value to use if the provided value can't be parsed as a number.
  38991. *
  38992. * @usageNotes
  38993. * ```ts
  38994. * @Input({ transform: numberAttribute }) id!: number;
  38995. * ```
  38996. *
  38997. * @publicApi
  38998. */
  38999. function numberAttribute(value, fallbackValue = NaN) {
  39000. // parseFloat(value) handles most of the cases we're interested in (it treats null, empty string,
  39001. // and other non-number values as NaN, where Number just uses 0) but it considers the string
  39002. // '123hello' to be a valid number. Therefore we also check if Number(value) is NaN.
  39003. const isNumberValue = !isNaN(parseFloat(value)) && !isNaN(Number(value));
  39004. return isNumberValue ? Number(value) : fallbackValue;
  39005. }
  39006. const PERFORMANCE_MARK_PREFIX = '🅰️';
  39007. let enablePerfLogging = false;
  39008. /**
  39009. * Function that will start measuring against the performance API
  39010. * Should be used in pair with stopMeasuring
  39011. */
  39012. function startMeasuring(label) {
  39013. if (!enablePerfLogging) {
  39014. return;
  39015. }
  39016. const { startLabel } = labels(label);
  39017. /* tslint:disable:ban */
  39018. performance.mark(startLabel);
  39019. /* tslint:enable:ban */
  39020. }
  39021. /**
  39022. * Function that will stop measuring against the performance API
  39023. * Should be used in pair with stopMeasuring
  39024. */
  39025. function stopMeasuring(label) {
  39026. if (!enablePerfLogging) {
  39027. return;
  39028. }
  39029. const { startLabel, labelName, endLabel } = labels(label);
  39030. /* tslint:disable:ban */
  39031. performance.mark(endLabel);
  39032. performance.measure(labelName, startLabel, endLabel);
  39033. performance.clearMarks(startLabel);
  39034. performance.clearMarks(endLabel);
  39035. /* tslint:enable:ban */
  39036. }
  39037. function labels(label) {
  39038. const labelName = `${PERFORMANCE_MARK_PREFIX}:${label}`;
  39039. return {
  39040. labelName,
  39041. startLabel: `start:${labelName}`,
  39042. endLabel: `end:${labelName}`,
  39043. };
  39044. }
  39045. let warningLogged = false;
  39046. /**
  39047. * This enables an internal performance profiler
  39048. *
  39049. * It should not be imported in application code
  39050. */
  39051. function enableProfiling() {
  39052. if (!warningLogged &&
  39053. (typeof performance === 'undefined' || !performance.mark || !performance.measure)) {
  39054. warningLogged = true;
  39055. console.warn('Performance API is not supported on this platform');
  39056. return;
  39057. }
  39058. enablePerfLogging = true;
  39059. }
  39060. function disableProfiling() {
  39061. enablePerfLogging = false;
  39062. }
  39063. /**
  39064. * Execute an arbitrary function in a non-reactive (non-tracking) context. The executed function
  39065. * can, optionally, return a value.
  39066. */
  39067. function untracked(nonReactiveReadsFn) {
  39068. return untracked$1(nonReactiveReadsFn);
  39069. }
  39070. /**
  39071. * Create a computed `Signal` which derives a reactive value from an expression.
  39072. */
  39073. function computed(computation, options) {
  39074. const getter = createComputed(computation, options?.equal);
  39075. if (ngDevMode) {
  39076. getter.toString = () => `[Computed: ${getter()}]`;
  39077. getter[SIGNAL].debugName = options?.debugName;
  39078. }
  39079. return getter;
  39080. }
  39081. class MicrotaskEffectScheduler extends ZoneAwareEffectScheduler {
  39082. pendingTasks = inject(PendingTasksInternal);
  39083. taskId = null;
  39084. schedule(effect) {
  39085. // Check whether there are any pending effects _before_ queueing in the base class.
  39086. super.schedule(effect);
  39087. if (this.taskId === null) {
  39088. this.taskId = this.pendingTasks.add();
  39089. queueMicrotask(() => this.flush());
  39090. }
  39091. }
  39092. flush() {
  39093. try {
  39094. super.flush();
  39095. }
  39096. finally {
  39097. if (this.taskId !== null) {
  39098. this.pendingTasks.remove(this.taskId);
  39099. this.taskId = null;
  39100. }
  39101. }
  39102. }
  39103. /** @nocollapse */
  39104. static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
  39105. token: MicrotaskEffectScheduler,
  39106. providedIn: 'root',
  39107. factory: () => new MicrotaskEffectScheduler(),
  39108. });
  39109. }
  39110. /**
  39111. * Core reactive node for an Angular effect.
  39112. *
  39113. * `EffectHandle` combines the reactive graph's `Watch` base node for effects with the framework's
  39114. * scheduling abstraction (`MicrotaskEffectScheduler`) as well as automatic cleanup via `DestroyRef`
  39115. * if available/requested.
  39116. */
  39117. class EffectHandle {
  39118. scheduler;
  39119. effectFn;
  39120. zone;
  39121. injector;
  39122. unregisterOnDestroy;
  39123. watcher;
  39124. constructor(scheduler, effectFn, zone, destroyRef, injector, allowSignalWrites) {
  39125. this.scheduler = scheduler;
  39126. this.effectFn = effectFn;
  39127. this.zone = zone;
  39128. this.injector = injector;
  39129. this.watcher = createWatch((onCleanup) => this.runEffect(onCleanup), () => this.schedule(), allowSignalWrites);
  39130. this.unregisterOnDestroy = destroyRef?.onDestroy(() => this.destroy());
  39131. }
  39132. runEffect(onCleanup) {
  39133. try {
  39134. this.effectFn(onCleanup);
  39135. }
  39136. catch (err) {
  39137. // Inject the `ErrorHandler` here in order to avoid circular DI error
  39138. // if the effect is used inside of a custom `ErrorHandler`.
  39139. const errorHandler = this.injector.get(ErrorHandler, null, { optional: true });
  39140. errorHandler?.handleError(err);
  39141. }
  39142. }
  39143. run() {
  39144. this.watcher.run();
  39145. }
  39146. schedule() {
  39147. this.scheduler.schedule(this);
  39148. }
  39149. destroy() {
  39150. this.watcher.destroy();
  39151. this.unregisterOnDestroy?.();
  39152. // Note: if the effect is currently scheduled, it's not un-scheduled, and so the scheduler will
  39153. // retain a reference to it. Attempting to execute it will be a no-op.
  39154. }
  39155. }
  39156. // Just used for the name for the debug error below.
  39157. function effect$1() { }
  39158. /**
  39159. * Create a global `Effect` for the given reactive function.
  39160. */
  39161. function microtaskEffect(effectFn, options) {
  39162. ngDevMode &&
  39163. assertNotInReactiveContext(effect$1, 'Call `effect` outside of a reactive context. For example, schedule the ' +
  39164. 'effect inside the component constructor.');
  39165. !options?.injector && assertInInjectionContext(effect$1);
  39166. const injector = options?.injector ?? inject(Injector);
  39167. const destroyRef = options?.manualCleanup !== true ? injector.get(DestroyRef) : null;
  39168. const handle = new EffectHandle(injector.get(MicrotaskEffectScheduler), effectFn, typeof Zone === 'undefined' ? null : Zone.current, destroyRef, injector, options?.allowSignalWrites ?? false);
  39169. // Effects need to be marked dirty manually to trigger their initial run. The timing of this
  39170. // marking matters, because the effects may read signals that track component inputs, which are
  39171. // only available after those components have had their first update pass.
  39172. //
  39173. // We inject `ChangeDetectorRef` optionally, to determine whether this effect is being created in
  39174. // the context of a component or not. If it is, then we check whether the component has already
  39175. // run its update pass, and defer the effect's initial scheduling until the update pass if it
  39176. // hasn't already run.
  39177. const cdr = injector.get(ChangeDetectorRef, null, { optional: true });
  39178. if (!cdr || !(cdr._lView[FLAGS] & 8 /* LViewFlags.FirstLViewPass */)) {
  39179. // This effect is either not running in a view injector, or the view has already
  39180. // undergone its first change detection pass, which is necessary for any required inputs to be
  39181. // set.
  39182. handle.watcher.notify();
  39183. }
  39184. else {
  39185. // Delay the initialization of the effect until the view is fully initialized.
  39186. (cdr._lView[EFFECTS_TO_SCHEDULE] ??= []).push(handle.watcher.notify);
  39187. }
  39188. return handle;
  39189. }
  39190. class EffectRefImpl {
  39191. [SIGNAL];
  39192. constructor(node) {
  39193. this[SIGNAL] = node;
  39194. }
  39195. destroy() {
  39196. this[SIGNAL].destroy();
  39197. }
  39198. }
  39199. /**
  39200. * Registers an "effect" that will be scheduled & executed whenever the signals that it reads
  39201. * changes.
  39202. *
  39203. * Angular has two different kinds of effect: component effects and root effects. Component effects
  39204. * are created when `effect()` is called from a component, directive, or within a service of a
  39205. * component/directive. Root effects are created when `effect()` is called from outside the
  39206. * component tree, such as in a root service, or when the `forceRoot` option is provided.
  39207. *
  39208. * The two effect types differ in their timing. Component effects run as a component lifecycle
  39209. * event during Angular's synchronization (change detection) process, and can safely read input
  39210. * signals or create/destroy views that depend on component state. Root effects run as microtasks
  39211. * and have no connection to the component tree or change detection.
  39212. *
  39213. * `effect()` must be run in injection context, unless the `injector` option is manually specified.
  39214. *
  39215. * @developerPreview
  39216. */
  39217. function effect(effectFn, options) {
  39218. ngDevMode &&
  39219. assertNotInReactiveContext(effect, 'Call `effect` outside of a reactive context. For example, schedule the ' +
  39220. 'effect inside the component constructor.');
  39221. !options?.injector && assertInInjectionContext(effect);
  39222. if (ngDevMode && options?.allowSignalWrites !== undefined) {
  39223. console.warn(`The 'allowSignalWrites' flag is deprecated and no longer impacts effect() (writes are always allowed)`);
  39224. }
  39225. const injector = options?.injector ?? inject(Injector);
  39226. let destroyRef = options?.manualCleanup !== true ? injector.get(DestroyRef) : null;
  39227. let node;
  39228. const viewContext = injector.get(ViewContext, null, { optional: true });
  39229. const notifier = injector.get(ChangeDetectionScheduler);
  39230. if (viewContext !== null && !options?.forceRoot) {
  39231. // This effect was created in the context of a view, and will be associated with the view.
  39232. node = createViewEffect(viewContext.view, notifier, effectFn);
  39233. if (destroyRef instanceof NodeInjectorDestroyRef && destroyRef._lView === viewContext.view) {
  39234. // The effect is being created in the same view as the `DestroyRef` references, so it will be
  39235. // automatically destroyed without the need for an explicit `DestroyRef` registration.
  39236. destroyRef = null;
  39237. }
  39238. }
  39239. else {
  39240. // This effect was created outside the context of a view, and will be scheduled independently.
  39241. node = createRootEffect(effectFn, injector.get(EffectScheduler), notifier);
  39242. }
  39243. node.injector = injector;
  39244. if (destroyRef !== null) {
  39245. // If we need to register for cleanup, do that here.
  39246. node.onDestroyFn = destroyRef.onDestroy(() => node.destroy());
  39247. }
  39248. const effectRef = new EffectRefImpl(node);
  39249. if (ngDevMode) {
  39250. node.debugName = options?.debugName ?? '';
  39251. const prevInjectorProfilerContext = setInjectorProfilerContext({ injector, token: null });
  39252. try {
  39253. emitEffectCreatedEvent(effectRef);
  39254. }
  39255. finally {
  39256. setInjectorProfilerContext(prevInjectorProfilerContext);
  39257. }
  39258. }
  39259. return effectRef;
  39260. }
  39261. /**
  39262. * Not public API, which guarantees `EffectScheduler` only ever comes from the application root
  39263. * injector.
  39264. */
  39265. /* @__PURE__ */ new InjectionToken('', {
  39266. providedIn: 'root',
  39267. factory: () => inject(EffectScheduler),
  39268. });
  39269. const BASE_EFFECT_NODE =
  39270. /* @__PURE__ */ (() => ({
  39271. ...REACTIVE_NODE,
  39272. consumerIsAlwaysLive: true,
  39273. consumerAllowSignalWrites: true,
  39274. dirty: true,
  39275. hasRun: false,
  39276. cleanupFns: undefined,
  39277. zone: null,
  39278. kind: 'effect',
  39279. onDestroyFn: noop,
  39280. run() {
  39281. this.dirty = false;
  39282. if (ngDevMode && isInNotificationPhase()) {
  39283. throw new Error(`Schedulers cannot synchronously execute watches while scheduling.`);
  39284. }
  39285. if (this.hasRun && !consumerPollProducersForChange(this)) {
  39286. return;
  39287. }
  39288. this.hasRun = true;
  39289. const registerCleanupFn = (cleanupFn) => (this.cleanupFns ??= []).push(cleanupFn);
  39290. const prevNode = consumerBeforeComputation(this);
  39291. // We clear `setIsRefreshingViews` so that `markForCheck()` within the body of an effect will
  39292. // cause CD to reach the component in question.
  39293. const prevRefreshingViews = setIsRefreshingViews(false);
  39294. try {
  39295. this.maybeCleanup();
  39296. this.fn(registerCleanupFn);
  39297. }
  39298. finally {
  39299. setIsRefreshingViews(prevRefreshingViews);
  39300. consumerAfterComputation(this, prevNode);
  39301. }
  39302. },
  39303. maybeCleanup() {
  39304. if (!this.cleanupFns?.length) {
  39305. return;
  39306. }
  39307. try {
  39308. // Attempt to run the cleanup functions. Regardless of failure or success, we consider
  39309. // cleanup "completed" and clear the list for the next run of the effect. Note that an error
  39310. // from the cleanup function will still crash the current run of the effect.
  39311. while (this.cleanupFns.length) {
  39312. this.cleanupFns.pop()();
  39313. }
  39314. }
  39315. finally {
  39316. this.cleanupFns = [];
  39317. }
  39318. },
  39319. }))();
  39320. const ROOT_EFFECT_NODE =
  39321. /* @__PURE__ */ (() => ({
  39322. ...BASE_EFFECT_NODE,
  39323. consumerMarkedDirty() {
  39324. this.scheduler.schedule(this);
  39325. this.notifier.notify(12 /* NotificationSource.RootEffect */);
  39326. },
  39327. destroy() {
  39328. consumerDestroy(this);
  39329. this.onDestroyFn();
  39330. this.maybeCleanup();
  39331. this.scheduler.remove(this);
  39332. },
  39333. }))();
  39334. const VIEW_EFFECT_NODE =
  39335. /* @__PURE__ */ (() => ({
  39336. ...BASE_EFFECT_NODE,
  39337. consumerMarkedDirty() {
  39338. this.view[FLAGS] |= 8192 /* LViewFlags.HasChildViewsToRefresh */;
  39339. markAncestorsForTraversal(this.view);
  39340. this.notifier.notify(13 /* NotificationSource.ViewEffect */);
  39341. },
  39342. destroy() {
  39343. consumerDestroy(this);
  39344. this.onDestroyFn();
  39345. this.maybeCleanup();
  39346. this.view[EFFECTS]?.delete(this);
  39347. },
  39348. }))();
  39349. function createViewEffect(view, notifier, fn) {
  39350. const node = Object.create(VIEW_EFFECT_NODE);
  39351. node.view = view;
  39352. node.zone = typeof Zone !== 'undefined' ? Zone.current : null;
  39353. node.notifier = notifier;
  39354. node.fn = fn;
  39355. view[EFFECTS] ??= new Set();
  39356. view[EFFECTS].add(node);
  39357. node.consumerMarkedDirty(node);
  39358. return node;
  39359. }
  39360. function createRootEffect(fn, scheduler, notifier) {
  39361. const node = Object.create(ROOT_EFFECT_NODE);
  39362. node.fn = fn;
  39363. node.scheduler = scheduler;
  39364. node.notifier = notifier;
  39365. node.zone = typeof Zone !== 'undefined' ? Zone.current : null;
  39366. node.scheduler.schedule(node);
  39367. node.notifier.notify(12 /* NotificationSource.RootEffect */);
  39368. return node;
  39369. }
  39370. /**
  39371. * Status of a `Resource`.
  39372. *
  39373. * @experimental
  39374. */
  39375. var ResourceStatus;
  39376. (function (ResourceStatus) {
  39377. /**
  39378. * The resource has no valid request and will not perform any loading.
  39379. *
  39380. * `value()` will be `undefined`.
  39381. */
  39382. ResourceStatus[ResourceStatus["Idle"] = 0] = "Idle";
  39383. /**
  39384. * Loading failed with an error.
  39385. *
  39386. * `value()` will be `undefined`.
  39387. */
  39388. ResourceStatus[ResourceStatus["Error"] = 1] = "Error";
  39389. /**
  39390. * The resource is currently loading a new value as a result of a change in its `request`.
  39391. *
  39392. * `value()` will be `undefined`.
  39393. */
  39394. ResourceStatus[ResourceStatus["Loading"] = 2] = "Loading";
  39395. /**
  39396. * The resource is currently reloading a fresh value for the same request.
  39397. *
  39398. * `value()` will continue to return the previously fetched value during the reloading operation.
  39399. */
  39400. ResourceStatus[ResourceStatus["Reloading"] = 3] = "Reloading";
  39401. /**
  39402. * Loading has completed and the resource has the value returned from the loader.
  39403. */
  39404. ResourceStatus[ResourceStatus["Resolved"] = 4] = "Resolved";
  39405. /**
  39406. * The resource's value was set locally via `.set()` or `.update()`.
  39407. */
  39408. ResourceStatus[ResourceStatus["Local"] = 5] = "Local";
  39409. })(ResourceStatus || (ResourceStatus = {}));
  39410. const identityFn = (v) => v;
  39411. function linkedSignal(optionsOrComputation, options) {
  39412. if (typeof optionsOrComputation === 'function') {
  39413. const getter = createLinkedSignal(optionsOrComputation, (identityFn), options?.equal);
  39414. return upgradeLinkedSignalGetter(getter);
  39415. }
  39416. else {
  39417. const getter = createLinkedSignal(optionsOrComputation.source, optionsOrComputation.computation, optionsOrComputation.equal);
  39418. return upgradeLinkedSignalGetter(getter);
  39419. }
  39420. }
  39421. function upgradeLinkedSignalGetter(getter) {
  39422. if (ngDevMode) {
  39423. getter.toString = () => `[LinkedSignal: ${getter()}]`;
  39424. }
  39425. const node = getter[SIGNAL];
  39426. const upgradedGetter = getter;
  39427. upgradedGetter.set = (newValue) => linkedSignalSetFn(node, newValue);
  39428. upgradedGetter.update = (updateFn) => linkedSignalUpdateFn(node, updateFn);
  39429. upgradedGetter.asReadonly = signalAsReadonlyFn.bind(getter);
  39430. return upgradedGetter;
  39431. }
  39432. function resource(options) {
  39433. options?.injector || assertInInjectionContext(resource);
  39434. const request = (options.request ?? (() => null));
  39435. return new ResourceImpl(request, getLoader(options), options.defaultValue, options.equal ? wrapEqualityFn(options.equal) : undefined, options.injector ?? inject(Injector));
  39436. }
  39437. /**
  39438. * Base class which implements `.value` as a `WritableSignal` by delegating `.set` and `.update`.
  39439. */
  39440. class BaseWritableResource {
  39441. value;
  39442. constructor(value) {
  39443. this.value = value;
  39444. this.value.set = this.set.bind(this);
  39445. this.value.update = this.update.bind(this);
  39446. this.value.asReadonly = signalAsReadonlyFn;
  39447. }
  39448. update(updateFn) {
  39449. this.set(updateFn(untracked(this.value)));
  39450. }
  39451. isLoading = computed(() => this.status() === ResourceStatus.Loading || this.status() === ResourceStatus.Reloading);
  39452. hasValue() {
  39453. return this.value() !== undefined;
  39454. }
  39455. asReadonly() {
  39456. return this;
  39457. }
  39458. }
  39459. /**
  39460. * Implementation for `resource()` which uses a `linkedSignal` to manage the resource's state.
  39461. */
  39462. class ResourceImpl extends BaseWritableResource {
  39463. loaderFn;
  39464. defaultValue;
  39465. equal;
  39466. pendingTasks;
  39467. /**
  39468. * The current state of the resource. Status, value, and error are derived from this.
  39469. */
  39470. state;
  39471. /**
  39472. * Combines the current request with a reload counter which allows the resource to be reloaded on
  39473. * imperative command.
  39474. */
  39475. extRequest;
  39476. effectRef;
  39477. pendingController;
  39478. resolvePendingTask = undefined;
  39479. destroyed = false;
  39480. constructor(request, loaderFn, defaultValue, equal, injector) {
  39481. super(
  39482. // Feed a computed signal for the value to `BaseWritableResource`, which will upgrade it to a
  39483. // `WritableSignal` that delegates to `ResourceImpl.set`.
  39484. computed(() => {
  39485. const streamValue = this.state().stream?.();
  39486. return streamValue && isResolved(streamValue) ? streamValue.value : this.defaultValue;
  39487. }, { equal }));
  39488. this.loaderFn = loaderFn;
  39489. this.defaultValue = defaultValue;
  39490. this.equal = equal;
  39491. // Extend `request()` to include a writable reload signal.
  39492. this.extRequest = linkedSignal({
  39493. source: request,
  39494. computation: (request) => ({ request, reload: 0 }),
  39495. });
  39496. // The main resource state is managed in a `linkedSignal`, which allows the resource to change
  39497. // state instantaneously when the request signal changes.
  39498. this.state = linkedSignal({
  39499. // Whenever the request changes,
  39500. source: this.extRequest,
  39501. // Compute the state of the resource given a change in status.
  39502. computation: (extRequest, previous) => {
  39503. const status = extRequest.request === undefined ? ResourceStatus.Idle : ResourceStatus.Loading;
  39504. if (!previous) {
  39505. return {
  39506. extRequest,
  39507. status,
  39508. previousStatus: ResourceStatus.Idle,
  39509. stream: undefined,
  39510. };
  39511. }
  39512. else {
  39513. return {
  39514. extRequest,
  39515. status,
  39516. previousStatus: projectStatusOfState(previous.value),
  39517. // If the request hasn't changed, keep the previous stream.
  39518. stream: previous.value.extRequest.request === extRequest.request
  39519. ? previous.value.stream
  39520. : undefined,
  39521. };
  39522. }
  39523. },
  39524. });
  39525. this.effectRef = effect(this.loadEffect.bind(this), {
  39526. injector,
  39527. manualCleanup: true,
  39528. });
  39529. this.pendingTasks = injector.get(PendingTasks);
  39530. // Cancel any pending request when the resource itself is destroyed.
  39531. injector.get(DestroyRef).onDestroy(() => this.destroy());
  39532. }
  39533. status = computed(() => projectStatusOfState(this.state()));
  39534. error = computed(() => {
  39535. const stream = this.state().stream?.();
  39536. return stream && !isResolved(stream) ? stream.error : undefined;
  39537. });
  39538. /**
  39539. * Called either directly via `WritableResource.set` or via `.value.set()`.
  39540. */
  39541. set(value) {
  39542. if (this.destroyed) {
  39543. return;
  39544. }
  39545. const current = untracked(this.value);
  39546. const state = untracked(this.state);
  39547. if (state.status === ResourceStatus.Local &&
  39548. (this.equal ? this.equal(current, value) : current === value)) {
  39549. return;
  39550. }
  39551. // Enter Local state with the user-defined value.
  39552. this.state.set({
  39553. extRequest: state.extRequest,
  39554. status: ResourceStatus.Local,
  39555. previousStatus: ResourceStatus.Local,
  39556. stream: signal({ value }),
  39557. });
  39558. // We're departing from whatever state the resource was in previously, so cancel any in-progress
  39559. // loading operations.
  39560. this.abortInProgressLoad();
  39561. }
  39562. reload() {
  39563. // We don't want to restart in-progress loads.
  39564. const { status } = untracked(this.state);
  39565. if (status === ResourceStatus.Idle || status === ResourceStatus.Loading) {
  39566. return false;
  39567. }
  39568. // Increment the request reload to trigger the `state` linked signal to switch us to `Reload`
  39569. this.extRequest.update(({ request, reload }) => ({ request, reload: reload + 1 }));
  39570. return true;
  39571. }
  39572. destroy() {
  39573. this.destroyed = true;
  39574. this.effectRef.destroy();
  39575. this.abortInProgressLoad();
  39576. // Destroyed resources enter Idle state.
  39577. this.state.set({
  39578. extRequest: { request: undefined, reload: 0 },
  39579. status: ResourceStatus.Idle,
  39580. previousStatus: ResourceStatus.Idle,
  39581. stream: undefined,
  39582. });
  39583. }
  39584. async loadEffect() {
  39585. const extRequest = this.extRequest();
  39586. // Capture the previous status before any state transitions. Note that this is `untracked` since
  39587. // we do not want the effect to depend on the state of the resource, only on the request.
  39588. const { status: currentStatus, previousStatus } = untracked(this.state);
  39589. if (extRequest.request === undefined) {
  39590. // Nothing to load (and we should already be in a non-loading state).
  39591. return;
  39592. }
  39593. else if (currentStatus !== ResourceStatus.Loading) {
  39594. // We're not in a loading or reloading state, so this loading request is stale.
  39595. return;
  39596. }
  39597. // Cancel any previous loading attempts.
  39598. this.abortInProgressLoad();
  39599. // Capturing _this_ load's pending task in a local variable is important here. We may attempt to
  39600. // resolve it twice:
  39601. //
  39602. // 1. when the loading function promise resolves/rejects
  39603. // 2. when cancelling the loading operation
  39604. //
  39605. // After the loading operation is cancelled, `this.resolvePendingTask` no longer represents this
  39606. // particular task, but this `await` may eventually resolve/reject. Thus, when we cancel in
  39607. // response to (1) below, we need to cancel the locally saved task.
  39608. let resolvePendingTask = (this.resolvePendingTask =
  39609. this.pendingTasks.add());
  39610. const { signal: abortSignal } = (this.pendingController = new AbortController());
  39611. try {
  39612. // The actual loading is run through `untracked` - only the request side of `resource` is
  39613. // reactive. This avoids any confusion with signals tracking or not tracking depending on
  39614. // which side of the `await` they are.
  39615. const stream = await untracked(() => {
  39616. return this.loaderFn({
  39617. request: extRequest.request,
  39618. abortSignal,
  39619. previous: {
  39620. status: previousStatus,
  39621. },
  39622. });
  39623. });
  39624. // If this request has been aborted, or the current request no longer
  39625. // matches this load, then we should ignore this resolution.
  39626. if (abortSignal.aborted || untracked(this.extRequest) !== extRequest) {
  39627. return;
  39628. }
  39629. this.state.set({
  39630. extRequest,
  39631. status: ResourceStatus.Resolved,
  39632. previousStatus: ResourceStatus.Resolved,
  39633. stream,
  39634. });
  39635. }
  39636. catch (err) {
  39637. if (abortSignal.aborted || untracked(this.extRequest) !== extRequest) {
  39638. return;
  39639. }
  39640. this.state.set({
  39641. extRequest,
  39642. status: ResourceStatus.Resolved,
  39643. previousStatus: ResourceStatus.Error,
  39644. stream: signal({ error: err }),
  39645. });
  39646. }
  39647. finally {
  39648. // Resolve the pending task now that the resource has a value.
  39649. resolvePendingTask?.();
  39650. resolvePendingTask = undefined;
  39651. }
  39652. }
  39653. abortInProgressLoad() {
  39654. untracked(() => this.pendingController?.abort());
  39655. this.pendingController = undefined;
  39656. // Once the load is aborted, we no longer want to block stability on its resolution.
  39657. this.resolvePendingTask?.();
  39658. this.resolvePendingTask = undefined;
  39659. }
  39660. }
  39661. /**
  39662. * Wraps an equality function to handle either value being `undefined`.
  39663. */
  39664. function wrapEqualityFn(equal) {
  39665. return (a, b) => (a === undefined || b === undefined ? a === b : equal(a, b));
  39666. }
  39667. function getLoader(options) {
  39668. if (isStreamingResourceOptions(options)) {
  39669. return options.stream;
  39670. }
  39671. return async (params) => {
  39672. try {
  39673. return signal({ value: await options.loader(params) });
  39674. }
  39675. catch (err) {
  39676. return signal({ error: err });
  39677. }
  39678. };
  39679. }
  39680. function isStreamingResourceOptions(options) {
  39681. return !!options.stream;
  39682. }
  39683. /**
  39684. * Project from a state with `ResourceInternalStatus` to the user-facing `ResourceStatus`
  39685. */
  39686. function projectStatusOfState(state) {
  39687. switch (state.status) {
  39688. case ResourceStatus.Loading:
  39689. return state.extRequest.reload === 0 ? ResourceStatus.Loading : ResourceStatus.Reloading;
  39690. case ResourceStatus.Resolved:
  39691. return isResolved(untracked(state.stream)) ? ResourceStatus.Resolved : ResourceStatus.Error;
  39692. default:
  39693. return state.status;
  39694. }
  39695. }
  39696. function isResolved(state) {
  39697. return state.error === undefined;
  39698. }
  39699. /*!
  39700. * @license
  39701. * Copyright Google LLC All Rights Reserved.
  39702. *
  39703. * Use of this source code is governed by an MIT-style license that can be
  39704. * found in the LICENSE file at https://angular.dev/license
  39705. */
  39706. /**
  39707. * Gets the class name of the closest component to a node.
  39708. * Warning! this function will return minified names if the name of the component is minified. The
  39709. * consumer of the function is responsible for resolving the minified name to its original name.
  39710. * @param node Node from which to start the search.
  39711. */
  39712. function getClosestComponentName(node) {
  39713. let currentNode = node;
  39714. while (currentNode) {
  39715. const lView = readPatchedLView(currentNode);
  39716. if (lView !== null) {
  39717. for (let i = HEADER_OFFSET; i < lView.length; i++) {
  39718. const current = lView[i];
  39719. if ((!isLView(current) && !isLContainer(current)) || current[HOST] !== currentNode) {
  39720. continue;
  39721. }
  39722. const tView = lView[TVIEW];
  39723. const tNode = getTNode(tView, i);
  39724. if (isComponentHost(tNode)) {
  39725. const def = tView.data[tNode.directiveStart + tNode.componentOffset];
  39726. const name = def.debugInfo?.className || def.type.name;
  39727. // Note: the name may be an empty string if the class name is
  39728. // dropped due to minification. In such cases keep going up the tree.
  39729. if (name) {
  39730. return name;
  39731. }
  39732. else {
  39733. break;
  39734. }
  39735. }
  39736. }
  39737. }
  39738. currentNode = currentNode.parentNode;
  39739. }
  39740. return null;
  39741. }
  39742. /**
  39743. * Compiles a partial directive declaration object into a full directive definition object.
  39744. *
  39745. * @codeGenApi
  39746. */
  39747. function ɵɵngDeclareDirective(decl) {
  39748. const compiler = getCompilerFacade({
  39749. usage: 1 /* JitCompilerUsage.PartialDeclaration */,
  39750. kind: 'directive',
  39751. type: decl.type,
  39752. });
  39753. return compiler.compileDirectiveDeclaration(angularCoreEnv, `ng:///${decl.type.name}/ɵfac.js`, decl);
  39754. }
  39755. /**
  39756. * Evaluates the class metadata declaration.
  39757. *
  39758. * @codeGenApi
  39759. */
  39760. function ɵɵngDeclareClassMetadata(decl) {
  39761. setClassMetadata(decl.type, decl.decorators, decl.ctorParameters ?? null, decl.propDecorators ?? null);
  39762. }
  39763. /**
  39764. * Evaluates the class metadata of a component that contains deferred blocks.
  39765. *
  39766. * @codeGenApi
  39767. */
  39768. function ɵɵngDeclareClassMetadataAsync(decl) {
  39769. setClassMetadataAsync(decl.type, decl.resolveDeferredDeps, (...types) => {
  39770. const meta = decl.resolveMetadata(...types);
  39771. setClassMetadata(decl.type, meta.decorators, meta.ctorParameters, meta.propDecorators);
  39772. });
  39773. }
  39774. /**
  39775. * Compiles a partial component declaration object into a full component definition object.
  39776. *
  39777. * @codeGenApi
  39778. */
  39779. function ɵɵngDeclareComponent(decl) {
  39780. const compiler = getCompilerFacade({
  39781. usage: 1 /* JitCompilerUsage.PartialDeclaration */,
  39782. kind: 'component',
  39783. type: decl.type,
  39784. });
  39785. return compiler.compileComponentDeclaration(angularCoreEnv, `ng:///${decl.type.name}/ɵcmp.js`, decl);
  39786. }
  39787. /**
  39788. * Compiles a partial pipe declaration object into a full pipe definition object.
  39789. *
  39790. * @codeGenApi
  39791. */
  39792. function ɵɵngDeclareFactory(decl) {
  39793. const compiler = getCompilerFacade({
  39794. usage: 1 /* JitCompilerUsage.PartialDeclaration */,
  39795. kind: getFactoryKind(decl.target),
  39796. type: decl.type,
  39797. });
  39798. return compiler.compileFactoryDeclaration(angularCoreEnv, `ng:///${decl.type.name}/ɵfac.js`, decl);
  39799. }
  39800. function getFactoryKind(target) {
  39801. switch (target) {
  39802. case FactoryTarget.Directive:
  39803. return 'directive';
  39804. case FactoryTarget.Component:
  39805. return 'component';
  39806. case FactoryTarget.Injectable:
  39807. return 'injectable';
  39808. case FactoryTarget.Pipe:
  39809. return 'pipe';
  39810. case FactoryTarget.NgModule:
  39811. return 'NgModule';
  39812. }
  39813. }
  39814. /**
  39815. * Compiles a partial injectable declaration object into a full injectable definition object.
  39816. *
  39817. * @codeGenApi
  39818. */
  39819. function ɵɵngDeclareInjectable(decl) {
  39820. const compiler = getCompilerFacade({
  39821. usage: 1 /* JitCompilerUsage.PartialDeclaration */,
  39822. kind: 'injectable',
  39823. type: decl.type,
  39824. });
  39825. return compiler.compileInjectableDeclaration(angularCoreEnv, `ng:///${decl.type.name}/ɵprov.js`, decl);
  39826. }
  39827. /**
  39828. * Compiles a partial injector declaration object into a full injector definition object.
  39829. *
  39830. * @codeGenApi
  39831. */
  39832. function ɵɵngDeclareInjector(decl) {
  39833. const compiler = getCompilerFacade({
  39834. usage: 1 /* JitCompilerUsage.PartialDeclaration */,
  39835. kind: 'NgModule',
  39836. type: decl.type,
  39837. });
  39838. return compiler.compileInjectorDeclaration(angularCoreEnv, `ng:///${decl.type.name}/ɵinj.js`, decl);
  39839. }
  39840. /**
  39841. * Compiles a partial NgModule declaration object into a full NgModule definition object.
  39842. *
  39843. * @codeGenApi
  39844. */
  39845. function ɵɵngDeclareNgModule(decl) {
  39846. const compiler = getCompilerFacade({
  39847. usage: 1 /* JitCompilerUsage.PartialDeclaration */,
  39848. kind: 'NgModule',
  39849. type: decl.type,
  39850. });
  39851. return compiler.compileNgModuleDeclaration(angularCoreEnv, `ng:///${decl.type.name}/ɵmod.js`, decl);
  39852. }
  39853. /**
  39854. * Compiles a partial pipe declaration object into a full pipe definition object.
  39855. *
  39856. * @codeGenApi
  39857. */
  39858. function ɵɵngDeclarePipe(decl) {
  39859. const compiler = getCompilerFacade({
  39860. usage: 1 /* JitCompilerUsage.PartialDeclaration */,
  39861. kind: 'pipe',
  39862. type: decl.type,
  39863. });
  39864. return compiler.compilePipeDeclaration(angularCoreEnv, `ng:///${decl.type.name}/ɵpipe.js`, decl);
  39865. }
  39866. const NOT_SET = Symbol('NOT_SET');
  39867. const EMPTY_CLEANUP_SET = new Set();
  39868. const AFTER_RENDER_PHASE_EFFECT_NODE = /* @__PURE__ */ (() => ({
  39869. ...SIGNAL_NODE,
  39870. consumerIsAlwaysLive: true,
  39871. consumerAllowSignalWrites: true,
  39872. value: NOT_SET,
  39873. cleanup: null,
  39874. /** Called when the effect becomes dirty */
  39875. consumerMarkedDirty() {
  39876. if (this.sequence.impl.executing) {
  39877. // If hooks are in the middle of executing, then it matters whether this node has yet been
  39878. // executed within its sequence. If not, then we don't want to notify the scheduler since
  39879. // this node will be reached naturally.
  39880. if (this.sequence.lastPhase === null || this.sequence.lastPhase < this.phase) {
  39881. return;
  39882. }
  39883. // If during the execution of a later phase an earlier phase became dirty, then we should not
  39884. // run any further phases until the earlier one reruns.
  39885. this.sequence.erroredOrDestroyed = true;
  39886. }
  39887. // Either hooks are not running, or we're marking a node dirty that has already run within its
  39888. // sequence.
  39889. this.sequence.scheduler.notify(7 /* NotificationSource.RenderHook */);
  39890. },
  39891. phaseFn(previousValue) {
  39892. this.sequence.lastPhase = this.phase;
  39893. if (!this.dirty) {
  39894. return this.signal;
  39895. }
  39896. this.dirty = false;
  39897. if (this.value !== NOT_SET && !consumerPollProducersForChange(this)) {
  39898. // None of our producers report a change since the last time they were read, so no
  39899. // recomputation of our value is necessary.
  39900. return this.signal;
  39901. }
  39902. // Run any needed cleanup functions.
  39903. try {
  39904. for (const cleanupFn of this.cleanup ?? EMPTY_CLEANUP_SET) {
  39905. cleanupFn();
  39906. }
  39907. }
  39908. finally {
  39909. // Even if a cleanup function errors, ensure it's cleared.
  39910. this.cleanup?.clear();
  39911. }
  39912. // Prepare to call the user's effect callback. If there was a previous phase, then it gave us
  39913. // its value as a `Signal`, otherwise `previousValue` will be `undefined`.
  39914. const args = [];
  39915. if (previousValue !== undefined) {
  39916. args.push(previousValue);
  39917. }
  39918. args.push(this.registerCleanupFn);
  39919. // Call the user's callback in our reactive context.
  39920. const prevConsumer = consumerBeforeComputation(this);
  39921. let newValue;
  39922. try {
  39923. newValue = this.userFn.apply(null, args);
  39924. }
  39925. finally {
  39926. consumerAfterComputation(this, prevConsumer);
  39927. }
  39928. if (this.value === NOT_SET || !this.equal(this.value, newValue)) {
  39929. this.value = newValue;
  39930. this.version++;
  39931. }
  39932. return this.signal;
  39933. },
  39934. }))();
  39935. /**
  39936. * An `AfterRenderSequence` that manages an `afterRenderEffect`'s phase effects.
  39937. */
  39938. class AfterRenderEffectSequence extends AfterRenderSequence {
  39939. scheduler;
  39940. /**
  39941. * While this sequence is executing, this tracks the last phase which was called by the
  39942. * `afterRender` machinery.
  39943. *
  39944. * When a phase effect is marked dirty, this is used to determine whether it's already run or not.
  39945. */
  39946. lastPhase = null;
  39947. /**
  39948. * The reactive nodes for each phase, if a phase effect is defined for that phase.
  39949. *
  39950. * These are initialized to `undefined` but set in the constructor.
  39951. */
  39952. nodes = [undefined, undefined, undefined, undefined];
  39953. constructor(impl, effectHooks, view, scheduler, destroyRef, snapshot = null) {
  39954. // Note that we also initialize the underlying `AfterRenderSequence` hooks to `undefined` and
  39955. // populate them as we create reactive nodes below.
  39956. super(impl, [undefined, undefined, undefined, undefined], view, false, destroyRef, snapshot);
  39957. this.scheduler = scheduler;
  39958. // Setup a reactive node for each phase.
  39959. for (const phase of AFTER_RENDER_PHASES) {
  39960. const effectHook = effectHooks[phase];
  39961. if (effectHook === undefined) {
  39962. continue;
  39963. }
  39964. const node = Object.create(AFTER_RENDER_PHASE_EFFECT_NODE);
  39965. node.sequence = this;
  39966. node.phase = phase;
  39967. node.userFn = effectHook;
  39968. node.dirty = true;
  39969. node.signal = (() => {
  39970. producerAccessed(node);
  39971. return node.value;
  39972. });
  39973. node.signal[SIGNAL] = node;
  39974. node.registerCleanupFn = (fn) => (node.cleanup ??= new Set()).add(fn);
  39975. this.nodes[phase] = node;
  39976. // Install the upstream hook which runs the `phaseFn` for this phase.
  39977. this.hooks[phase] = (value) => node.phaseFn(value);
  39978. }
  39979. }
  39980. afterRun() {
  39981. super.afterRun();
  39982. // We're done running this sequence, so reset `lastPhase`.
  39983. this.lastPhase = null;
  39984. }
  39985. destroy() {
  39986. super.destroy();
  39987. // Run the cleanup functions for each node.
  39988. for (const node of this.nodes) {
  39989. for (const fn of node?.cleanup ?? EMPTY_CLEANUP_SET) {
  39990. fn();
  39991. }
  39992. }
  39993. }
  39994. }
  39995. /**
  39996. * @experimental
  39997. */
  39998. function afterRenderEffect(callbackOrSpec, options) {
  39999. ngDevMode &&
  40000. assertNotInReactiveContext(afterRenderEffect, 'Call `afterRenderEffect` outside of a reactive context. For example, create the render ' +
  40001. 'effect inside the component constructor`.');
  40002. !options?.injector && assertInInjectionContext(afterRenderEffect);
  40003. if (typeof ngServerMode !== 'undefined' && ngServerMode) {
  40004. return NOOP_AFTER_RENDER_REF;
  40005. }
  40006. const injector = options?.injector ?? inject(Injector);
  40007. const scheduler = injector.get(ChangeDetectionScheduler);
  40008. const manager = injector.get(AfterRenderManager);
  40009. const tracing = injector.get(TracingService, null, { optional: true });
  40010. manager.impl ??= injector.get(AfterRenderImpl);
  40011. let spec = callbackOrSpec;
  40012. if (typeof spec === 'function') {
  40013. spec = { mixedReadWrite: callbackOrSpec };
  40014. }
  40015. const viewContext = injector.get(ViewContext, null, { optional: true });
  40016. const sequence = new AfterRenderEffectSequence(manager.impl, [spec.earlyRead, spec.write, spec.mixedReadWrite, spec.read], viewContext?.view, scheduler, injector.get(DestroyRef), tracing?.snapshot(null));
  40017. manager.impl.register(sequence);
  40018. return sequence;
  40019. }
  40020. /**
  40021. * Creates a `ComponentRef` instance based on provided component type and a set of options.
  40022. *
  40023. * @usageNotes
  40024. *
  40025. * The example below demonstrates how the `createComponent` function can be used
  40026. * to create an instance of a ComponentRef dynamically and attach it to an ApplicationRef,
  40027. * so that it gets included into change detection cycles.
  40028. *
  40029. * Note: the example uses standalone components, but the function can also be used for
  40030. * non-standalone components (declared in an NgModule) as well.
  40031. *
  40032. * ```angular-ts
  40033. * @Component({
  40034. * standalone: true,
  40035. * template: `Hello {{ name }}!`
  40036. * })
  40037. * class HelloComponent {
  40038. * name = 'Angular';
  40039. * }
  40040. *
  40041. * @Component({
  40042. * standalone: true,
  40043. * template: `<div id="hello-component-host"></div>`
  40044. * })
  40045. * class RootComponent {}
  40046. *
  40047. * // Bootstrap an application.
  40048. * const applicationRef = await bootstrapApplication(RootComponent);
  40049. *
  40050. * // Locate a DOM node that would be used as a host.
  40051. * const hostElement = document.getElementById('hello-component-host');
  40052. *
  40053. * // Get an `EnvironmentInjector` instance from the `ApplicationRef`.
  40054. * const environmentInjector = applicationRef.injector;
  40055. *
  40056. * // We can now create a `ComponentRef` instance.
  40057. * const componentRef = createComponent(HelloComponent, {hostElement, environmentInjector});
  40058. *
  40059. * // Last step is to register the newly created ref using the `ApplicationRef` instance
  40060. * // to include the component view into change detection cycles.
  40061. * applicationRef.attachView(componentRef.hostView);
  40062. * componentRef.changeDetectorRef.detectChanges();
  40063. * ```
  40064. *
  40065. * @param component Component class reference.
  40066. * @param options Set of options to use:
  40067. * * `environmentInjector`: An `EnvironmentInjector` instance to be used for the component.
  40068. * * `hostElement` (optional): A DOM node that should act as a host node for the component. If not
  40069. * provided, Angular creates one based on the tag name used in the component selector (and falls
  40070. * back to using `div` if selector doesn't have tag name info).
  40071. * * `elementInjector` (optional): An `ElementInjector` instance, see additional info about it
  40072. * [here](guide/di/hierarchical-dependency-injection#elementinjector).
  40073. * * `projectableNodes` (optional): A list of DOM nodes that should be projected through
  40074. * [`<ng-content>`](api/core/ng-content) of the new component instance, e.g.,
  40075. * `[[element1, element2]]`: projects `element1` and `element2` into the same `<ng-content>`.
  40076. * `[[element1, element2], [element3]]`: projects `element1` and `element2` into one `<ng-content>`,
  40077. * and `element3` into a separate `<ng-content>`.
  40078. * @returns ComponentRef instance that represents a given Component.
  40079. *
  40080. * @publicApi
  40081. */
  40082. function createComponent(component, options) {
  40083. ngDevMode && assertComponentDef(component);
  40084. const componentDef = getComponentDef(component);
  40085. const elementInjector = options.elementInjector || getNullInjector();
  40086. const factory = new ComponentFactory(componentDef);
  40087. return factory.create(elementInjector, options.projectableNodes, options.hostElement, options.environmentInjector);
  40088. }
  40089. /**
  40090. * Creates an object that allows to retrieve component metadata.
  40091. *
  40092. * @usageNotes
  40093. *
  40094. * The example below demonstrates how to use the function and how the fields
  40095. * of the returned object map to the component metadata.
  40096. *
  40097. * ```angular-ts
  40098. * @Component({
  40099. * standalone: true,
  40100. * selector: 'foo-component',
  40101. * template: `
  40102. * <ng-content></ng-content>
  40103. * <ng-content select="content-selector-a"></ng-content>
  40104. * `,
  40105. * })
  40106. * class FooComponent {
  40107. * @Input('inputName') inputPropName: string;
  40108. * @Output('outputName') outputPropName = new EventEmitter<void>();
  40109. * }
  40110. *
  40111. * const mirror = reflectComponentType(FooComponent);
  40112. * expect(mirror.type).toBe(FooComponent);
  40113. * expect(mirror.selector).toBe('foo-component');
  40114. * expect(mirror.isStandalone).toBe(true);
  40115. * expect(mirror.inputs).toEqual([{propName: 'inputName', templateName: 'inputPropName'}]);
  40116. * expect(mirror.outputs).toEqual([{propName: 'outputName', templateName: 'outputPropName'}]);
  40117. * expect(mirror.ngContentSelectors).toEqual([
  40118. * '*', // first `<ng-content>` in a template, the selector defaults to `*`
  40119. * 'content-selector-a' // second `<ng-content>` in a template
  40120. * ]);
  40121. * ```
  40122. *
  40123. * @param component Component class reference.
  40124. * @returns An object that allows to retrieve component metadata.
  40125. *
  40126. * @publicApi
  40127. */
  40128. function reflectComponentType(component) {
  40129. const componentDef = getComponentDef(component);
  40130. if (!componentDef)
  40131. return null;
  40132. const factory = new ComponentFactory(componentDef);
  40133. return {
  40134. get selector() {
  40135. return factory.selector;
  40136. },
  40137. get type() {
  40138. return factory.componentType;
  40139. },
  40140. get inputs() {
  40141. return factory.inputs;
  40142. },
  40143. get outputs() {
  40144. return factory.outputs;
  40145. },
  40146. get ngContentSelectors() {
  40147. return factory.ngContentSelectors;
  40148. },
  40149. get isStandalone() {
  40150. return componentDef.standalone;
  40151. },
  40152. get isSignal() {
  40153. return componentDef.signals;
  40154. },
  40155. };
  40156. }
  40157. /**
  40158. * Merge multiple application configurations from left to right.
  40159. *
  40160. * @param configs Two or more configurations to be merged.
  40161. * @returns A merged [ApplicationConfig](api/core/ApplicationConfig).
  40162. *
  40163. * @publicApi
  40164. */
  40165. function mergeApplicationConfig(...configs) {
  40166. return configs.reduce((prev, curr) => {
  40167. return Object.assign(prev, curr, { providers: [...prev.providers, ...curr.providers] });
  40168. }, { providers: [] });
  40169. }
  40170. /**
  40171. * Injection token representing the current HTTP request object.
  40172. *
  40173. * Use this token to access the current request when handling server-side
  40174. * rendering (SSR).
  40175. *
  40176. * @remarks
  40177. * This token may be `null` in the following scenarios:
  40178. *
  40179. * * During the build processes.
  40180. * * When the application is rendered in the browser (client-side rendering).
  40181. * * When performing static site generation (SSG).
  40182. * * During route extraction in development (at the time of the request).
  40183. *
  40184. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Request | `Request` on MDN}
  40185. *
  40186. * @developerPreview
  40187. */
  40188. const REQUEST = new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'REQUEST' : '', {
  40189. providedIn: 'platform',
  40190. factory: () => null,
  40191. });
  40192. /**
  40193. * Injection token for response initialization options.
  40194. *
  40195. * Use this token to provide response options for configuring or initializing
  40196. * HTTP responses in server-side rendering or API endpoints.
  40197. *
  40198. * @remarks
  40199. * This token may be `null` in the following scenarios:
  40200. *
  40201. * * During the build processes.
  40202. * * When the application is rendered in the browser (client-side rendering).
  40203. * * When performing static site generation (SSG).
  40204. * * During route extraction in development (at the time of the request).
  40205. *
  40206. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Response/Response | `ResponseInit` on MDN}
  40207. *
  40208. * @developerPreview
  40209. */
  40210. const RESPONSE_INIT = new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'RESPONSE_INIT' : '', {
  40211. providedIn: 'platform',
  40212. factory: () => null,
  40213. });
  40214. /**
  40215. * Injection token for additional request context.
  40216. *
  40217. * Use this token to pass custom metadata or context related to the current request in server-side rendering.
  40218. *
  40219. * @remarks
  40220. * This token is only available during server-side rendering and will be `null` in other contexts.
  40221. *
  40222. * @developerPreview
  40223. */
  40224. const REQUEST_CONTEXT = new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'REQUEST_CONTEXT' : '', {
  40225. providedIn: 'platform',
  40226. factory: () => null,
  40227. });
  40228. export { ANIMATION_MODULE_TYPE, APP_BOOTSTRAP_LISTENER, APP_ID, APP_INITIALIZER, AfterRenderPhase, ApplicationInitStatus, ApplicationModule, ApplicationRef, Attribute, COMPILER_OPTIONS, CSP_NONCE, CUSTOM_ELEMENTS_SCHEMA, ChangeDetectionStrategy, ChangeDetectorRef, Compiler, CompilerFactory, Component, ComponentFactory$1 as ComponentFactory, ComponentFactoryResolver$1 as ComponentFactoryResolver, ComponentRef$1 as ComponentRef, ContentChild, ContentChildren, DEFAULT_CURRENCY_CODE, DebugElement, DebugEventListener, DebugNode, DefaultIterableDiffer, DestroyRef, Directive, ENVIRONMENT_INITIALIZER, ElementRef, EmbeddedViewRef, EnvironmentInjector, ErrorHandler, EventEmitter, HOST_TAG_NAME, Host, HostAttributeToken, HostBinding, HostListener, INJECTOR$1 as INJECTOR, Inject, InjectFlags, Injectable, InjectionToken, Injector, Input, IterableDiffers, KeyValueDiffers, LOCALE_ID, MissingTranslationStrategy, ModuleWithComponentFactories, NO_ERRORS_SCHEMA, NgModule, NgModuleFactory$1 as NgModuleFactory, NgModuleRef$1 as NgModuleRef, NgProbeToken, NgZone, Optional, Output, OutputEmitterRef, PACKAGE_ROOT_URL, PLATFORM_ID, PLATFORM_INITIALIZER, PendingTasks, Pipe, PlatformRef, Query, QueryList, REQUEST, REQUEST_CONTEXT, RESPONSE_INIT, Renderer2, RendererFactory2, RendererStyleFlags2, ResourceStatus, Sanitizer, SecurityContext, Self, SimpleChange, SkipSelf, TRANSLATIONS, TRANSLATIONS_FORMAT, TemplateRef, Testability, TestabilityRegistry, TransferState, Type, VERSION, Version, ViewChild, ViewChildren, ViewContainerRef, ViewEncapsulation, ViewRef, afterNextRender, afterRender, afterRenderEffect, asNativeElements, assertInInjectionContext, assertNotInReactiveContext, assertPlatform, booleanAttribute, computed, contentChild, contentChildren, createComponent, createEnvironmentInjector, createNgModule, createNgModuleRef, createPlatform, createPlatformFactory, defineInjectable, destroyPlatform, effect, enableProdMode, forwardRef, getDebugNode, getModuleFactory, getNgModuleById, getPlatform, importProvidersFrom, inject, input, isDevMode, isSignal, isStandalone, linkedSignal, makeEnvironmentProviders, makeStateKey, mergeApplicationConfig, model, numberAttribute, output, platformCore, provideAppInitializer, provideEnvironmentInitializer, provideExperimentalCheckNoChangesForDebug, provideExperimentalZonelessChangeDetection, providePlatformInitializer, provideZoneChangeDetection, reflectComponentType, resolveForwardRef, resource, runInInjectionContext, setTestabilityGetter, signal, untracked, viewChild, viewChildren, ALLOW_MULTIPLE_PLATFORMS as ɵALLOW_MULTIPLE_PLATFORMS, AfterRenderManager as ɵAfterRenderManager, CONTAINER_HEADER_OFFSET as ɵCONTAINER_HEADER_OFFSET, ChangeDetectionScheduler as ɵChangeDetectionScheduler, ChangeDetectionSchedulerImpl as ɵChangeDetectionSchedulerImpl, ComponentFactory$1 as ɵComponentFactory, Console as ɵConsole, DEFAULT_LOCALE_ID as ɵDEFAULT_LOCALE_ID, DEFER_BLOCK_CONFIG as ɵDEFER_BLOCK_CONFIG, DEFER_BLOCK_DEPENDENCY_INTERCEPTOR as ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR, DeferBlockBehavior as ɵDeferBlockBehavior, DeferBlockState as ɵDeferBlockState, ENABLE_ROOT_COMPONENT_BOOTSTRAP as ɵENABLE_ROOT_COMPONENT_BOOTSTRAP, EffectScheduler as ɵEffectScheduler, IMAGE_CONFIG as ɵIMAGE_CONFIG, IMAGE_CONFIG_DEFAULTS as ɵIMAGE_CONFIG_DEFAULTS, INJECTOR_SCOPE as ɵINJECTOR_SCOPE, ɵINPUT_SIGNAL_BRAND_WRITE_TYPE, INTERNAL_APPLICATION_ERROR_HANDLER as ɵINTERNAL_APPLICATION_ERROR_HANDLER, IS_HYDRATION_DOM_REUSE_ENABLED as ɵIS_HYDRATION_DOM_REUSE_ENABLED, IS_INCREMENTAL_HYDRATION_ENABLED as ɵIS_INCREMENTAL_HYDRATION_ENABLED, JSACTION_EVENT_CONTRACT as ɵJSACTION_EVENT_CONTRACT, LContext as ɵLContext, LocaleDataIndex as ɵLocaleDataIndex, MicrotaskEffectScheduler as ɵMicrotaskEffectScheduler, NG_COMP_DEF as ɵNG_COMP_DEF, NG_DIR_DEF as ɵNG_DIR_DEF, NG_ELEMENT_ID as ɵNG_ELEMENT_ID, NG_INJ_DEF as ɵNG_INJ_DEF, NG_MOD_DEF as ɵNG_MOD_DEF, NG_PIPE_DEF as ɵNG_PIPE_DEF, NG_PROV_DEF as ɵNG_PROV_DEF, NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR as ɵNOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR, NO_CHANGE as ɵNO_CHANGE, NgModuleFactory as ɵNgModuleFactory, NoopNgZone as ɵNoopNgZone, PERFORMANCE_MARK_PREFIX as ɵPERFORMANCE_MARK_PREFIX, PROVIDED_NG_ZONE as ɵPROVIDED_NG_ZONE, PendingTasksInternal as ɵPendingTasksInternal, ReflectionCapabilities as ɵReflectionCapabilities, ComponentFactory as ɵRender3ComponentFactory, ComponentRef as ɵRender3ComponentRef, NgModuleRef as ɵRender3NgModuleRef, ResourceImpl as ɵResourceImpl, RuntimeError as ɵRuntimeError, SIGNAL as ɵSIGNAL, SSR_CONTENT_INTEGRITY_MARKER as ɵSSR_CONTENT_INTEGRITY_MARKER, TESTABILITY as ɵTESTABILITY, TESTABILITY_GETTER as ɵTESTABILITY_GETTER, TracingAction as ɵTracingAction, TracingService as ɵTracingService, USE_RUNTIME_DEPS_TRACKER_FOR_JIT as ɵUSE_RUNTIME_DEPS_TRACKER_FOR_JIT, ViewRef$1 as ɵViewRef, XSS_SECURITY_URL as ɵXSS_SECURITY_URL, ZONELESS_ENABLED as ɵZONELESS_ENABLED, _sanitizeHtml as ɵ_sanitizeHtml, _sanitizeUrl as ɵ_sanitizeUrl, allowSanitizationBypassAndThrow as ɵallowSanitizationBypassAndThrow, annotateForHydration as ɵannotateForHydration, bypassSanitizationTrustHtml as ɵbypassSanitizationTrustHtml, bypassSanitizationTrustResourceUrl as ɵbypassSanitizationTrustResourceUrl, bypassSanitizationTrustScript as ɵbypassSanitizationTrustScript, bypassSanitizationTrustStyle as ɵbypassSanitizationTrustStyle, bypassSanitizationTrustUrl as ɵbypassSanitizationTrustUrl, clearResolutionOfComponentResourcesQueue as ɵclearResolutionOfComponentResourcesQueue, compileComponent as ɵcompileComponent, compileDirective as ɵcompileDirective, compileNgModule as ɵcompileNgModule, compileNgModuleDefs as ɵcompileNgModuleDefs, compileNgModuleFactory as ɵcompileNgModuleFactory, compilePipe as ɵcompilePipe, convertToBitFlags as ɵconvertToBitFlags, createInjector as ɵcreateInjector, defaultIterableDiffers as ɵdefaultIterableDiffers, defaultKeyValueDiffers as ɵdefaultKeyValueDiffers, depsTracker as ɵdepsTracker, detectChangesInViewIfRequired as ɵdetectChangesInViewIfRequired, devModeEqual as ɵdevModeEqual, disableProfiling as ɵdisableProfiling, enableProfiling as ɵenableProfiling, findLocaleData as ɵfindLocaleData, flushModuleScopingQueueAsMuchAsPossible as ɵflushModuleScopingQueueAsMuchAsPossible, formatRuntimeError as ɵformatRuntimeError, generateStandaloneInDeclarationsError as ɵgenerateStandaloneInDeclarationsError, getAsyncClassMetadataFn as ɵgetAsyncClassMetadataFn, getClosestComponentName as ɵgetClosestComponentName, getDebugNode as ɵgetDebugNode, getDeferBlocks$1 as ɵgetDeferBlocks, getDirectives as ɵgetDirectives, getHostElement as ɵgetHostElement, getInjectableDef as ɵgetInjectableDef, getLContext as ɵgetLContext, getLocaleCurrencyCode as ɵgetLocaleCurrencyCode, getLocalePluralCase as ɵgetLocalePluralCase, getOutputDestroyRef as ɵgetOutputDestroyRef, getSanitizationBypassType as ɵgetSanitizationBypassType, ɵgetUnknownElementStrictMode, ɵgetUnknownPropertyStrictMode, _global as ɵglobal, injectChangeDetectorRef as ɵinjectChangeDetectorRef, internalCreateApplication as ɵinternalCreateApplication, internalProvideZoneChangeDetection as ɵinternalProvideZoneChangeDetection, isBoundToModule as ɵisBoundToModule, isComponentDefPendingResolution as ɵisComponentDefPendingResolution, isEnvironmentProviders as ɵisEnvironmentProviders, isInjectable as ɵisInjectable, isNgModule as ɵisNgModule, isPromise as ɵisPromise, isSubscribable as ɵisSubscribable, isViewDirty as ɵisViewDirty, markForRefresh as ɵmarkForRefresh, microtaskEffect as ɵmicrotaskEffect, noSideEffects as ɵnoSideEffects, patchComponentDefWithScope as ɵpatchComponentDefWithScope, performanceMarkFeature as ɵperformanceMarkFeature, publishExternalGlobalUtil as ɵpublishExternalGlobalUtil, readHydrationInfo as ɵreadHydrationInfo, registerLocaleData as ɵregisterLocaleData, renderDeferBlockState as ɵrenderDeferBlockState, resetCompiledComponents as ɵresetCompiledComponents, resetJitOptions as ɵresetJitOptions, resolveComponentResources as ɵresolveComponentResources, restoreComponentResolutionQueue as ɵrestoreComponentResolutionQueue, setAllowDuplicateNgModuleIdsForTest as ɵsetAllowDuplicateNgModuleIdsForTest, ɵsetClassDebugInfo, setClassMetadata as ɵsetClassMetadata, setClassMetadataAsync as ɵsetClassMetadataAsync, setCurrentInjector as ɵsetCurrentInjector, setDocument as ɵsetDocument, setInjectorProfilerContext as ɵsetInjectorProfilerContext, setLocaleId as ɵsetLocaleId, ɵsetUnknownElementStrictMode, ɵsetUnknownPropertyStrictMode, startMeasuring as ɵstartMeasuring, stopMeasuring as ɵstopMeasuring, store as ɵstore, stringify as ɵstringify, transitiveScopesFor as ɵtransitiveScopesFor, triggerResourceLoading as ɵtriggerResourceLoading, truncateMiddle as ɵtruncateMiddle, unregisterAllLocaleData as ɵunregisterLocaleData, unwrapSafeValue as ɵunwrapSafeValue, ɵunwrapWritableSignal, withDomHydration as ɵwithDomHydration, withEventReplay as ɵwithEventReplay, withI18nSupport as ɵwithI18nSupport, withIncrementalHydration as ɵwithIncrementalHydration, ɵɵCopyDefinitionFeature, ɵɵExternalStylesFeature, FactoryTarget as ɵɵFactoryTarget, ɵɵHostDirectivesFeature, ɵɵInheritDefinitionFeature, ɵɵNgOnChangesFeature, ɵɵProvidersFeature, ɵɵadvance, ɵɵattachSourceLocations, ɵɵattribute, ɵɵattributeInterpolate1, ɵɵattributeInterpolate2, ɵɵattributeInterpolate3, ɵɵattributeInterpolate4, ɵɵattributeInterpolate5, ɵɵattributeInterpolate6, ɵɵattributeInterpolate7, ɵɵattributeInterpolate8, ɵɵattributeInterpolateV, ɵɵclassMap, ɵɵclassMapInterpolate1, ɵɵclassMapInterpolate2, ɵɵclassMapInterpolate3, ɵɵclassMapInterpolate4, ɵɵclassMapInterpolate5, ɵɵclassMapInterpolate6, ɵɵclassMapInterpolate7, ɵɵclassMapInterpolate8, ɵɵclassMapInterpolateV, ɵɵclassProp, ɵɵcomponentInstance, ɵɵconditional, ɵɵcontentQuery, ɵɵcontentQuerySignal, ɵɵdeclareLet, ɵɵdefer, ɵɵdeferEnableTimerScheduling, ɵɵdeferHydrateNever, ɵɵdeferHydrateOnHover, ɵɵdeferHydrateOnIdle, ɵɵdeferHydrateOnImmediate, ɵɵdeferHydrateOnInteraction, ɵɵdeferHydrateOnTimer, ɵɵdeferHydrateOnViewport, ɵɵdeferHydrateWhen, ɵɵdeferOnHover, ɵɵdeferOnIdle, ɵɵdeferOnImmediate, ɵɵdeferOnInteraction, ɵɵdeferOnTimer, ɵɵdeferOnViewport, ɵɵdeferPrefetchOnHover, ɵɵdeferPrefetchOnIdle, ɵɵdeferPrefetchOnImmediate, ɵɵdeferPrefetchOnInteraction, ɵɵdeferPrefetchOnTimer, ɵɵdeferPrefetchOnViewport, ɵɵdeferPrefetchWhen, ɵɵdeferWhen, ɵɵdefineComponent, ɵɵdefineDirective, ɵɵdefineInjectable, ɵɵdefineInjector, ɵɵdefineNgModule, ɵɵdefinePipe, ɵɵdirectiveInject, ɵɵdisableBindings, ɵɵelement, ɵɵelementContainer, ɵɵelementContainerEnd, ɵɵelementContainerStart, ɵɵelementEnd, ɵɵelementStart, ɵɵenableBindings, ɵɵgetComponentDepsFactory, ɵɵgetCurrentView, ɵɵgetInheritedFactory, ɵɵhostProperty, ɵɵi18n, ɵɵi18nApply, ɵɵi18nAttributes, ɵɵi18nEnd, ɵɵi18nExp, ɵɵi18nPostprocess, ɵɵi18nStart, ɵɵinject, ɵɵinjectAttribute, ɵɵinvalidFactory, ɵɵinvalidFactoryDep, ɵɵlistener, ɵɵloadQuery, ɵɵnamespaceHTML, ɵɵnamespaceMathML, ɵɵnamespaceSVG, ɵɵnextContext, ɵɵngDeclareClassMetadata, ɵɵngDeclareClassMetadataAsync, ɵɵngDeclareComponent, ɵɵngDeclareDirective, ɵɵngDeclareFactory, ɵɵngDeclareInjectable, ɵɵngDeclareInjector, ɵɵngDeclareNgModule, ɵɵngDeclarePipe, ɵɵpipe, ɵɵpipeBind1, ɵɵpipeBind2, ɵɵpipeBind3, ɵɵpipeBind4, ɵɵpipeBindV, ɵɵprojection, ɵɵprojectionDef, ɵɵproperty, ɵɵpropertyInterpolate, ɵɵpropertyInterpolate1, ɵɵpropertyInterpolate2, ɵɵpropertyInterpolate3, ɵɵpropertyInterpolate4, ɵɵpropertyInterpolate5, ɵɵpropertyInterpolate6, ɵɵpropertyInterpolate7, ɵɵpropertyInterpolate8, ɵɵpropertyInterpolateV, ɵɵpureFunction0, ɵɵpureFunction1, ɵɵpureFunction2, ɵɵpureFunction3, ɵɵpureFunction4, ɵɵpureFunction5, ɵɵpureFunction6, ɵɵpureFunction7, ɵɵpureFunction8, ɵɵpureFunctionV, ɵɵqueryAdvance, ɵɵqueryRefresh, ɵɵreadContextLet, ɵɵreference, registerNgModuleType as ɵɵregisterNgModuleType, ɵɵrepeater, ɵɵrepeaterCreate, ɵɵrepeaterTrackByIdentity, ɵɵrepeaterTrackByIndex, ɵɵreplaceMetadata, ɵɵresetView, ɵɵresolveBody, ɵɵresolveDocument, ɵɵresolveWindow, ɵɵrestoreView, ɵɵsanitizeHtml, ɵɵsanitizeResourceUrl, ɵɵsanitizeScript, ɵɵsanitizeStyle, ɵɵsanitizeUrl, ɵɵsanitizeUrlOrResourceUrl, ɵɵsetComponentScope, ɵɵsetNgModuleScope, ɵɵstoreLet, ɵɵstyleMap, ɵɵstyleMapInterpolate1, ɵɵstyleMapInterpolate2, ɵɵstyleMapInterpolate3, ɵɵstyleMapInterpolate4, ɵɵstyleMapInterpolate5, ɵɵstyleMapInterpolate6, ɵɵstyleMapInterpolate7, ɵɵstyleMapInterpolate8, ɵɵstyleMapInterpolateV, ɵɵstyleProp, ɵɵstylePropInterpolate1, ɵɵstylePropInterpolate2, ɵɵstylePropInterpolate3, ɵɵstylePropInterpolate4, ɵɵstylePropInterpolate5, ɵɵstylePropInterpolate6, ɵɵstylePropInterpolate7, ɵɵstylePropInterpolate8, ɵɵstylePropInterpolateV, ɵɵsyntheticHostListener, ɵɵsyntheticHostProperty, ɵɵtemplate, ɵɵtemplateRefExtractor, ɵɵtext, ɵɵtextInterpolate, ɵɵtextInterpolate1, ɵɵtextInterpolate2, ɵɵtextInterpolate3, ɵɵtextInterpolate4, ɵɵtextInterpolate5, ɵɵtextInterpolate6, ɵɵtextInterpolate7, ɵɵtextInterpolate8, ɵɵtextInterpolateV, ɵɵtrustConstantHtml, ɵɵtrustConstantResourceUrl, ɵɵtwoWayBindingSet, ɵɵtwoWayListener, ɵɵtwoWayProperty, ɵɵvalidateIframeAttribute, ɵɵviewQuery, ɵɵviewQuerySignal };
  40229. //# sourceMappingURL=core.mjs.map