core.mjs 1.6 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662
  1. /**
  2. * @license Angular v19.2.13
  3. * (c) 2010-2025 Google LLC. https://angular.io/
  4. * License: MIT
  5. */
  6. import { SIGNAL_NODE, signalSetFn, SIGNAL, producerAccessed, getActiveConsumer, setActiveConsumer as setActiveConsumer$1, createSignal, signalUpdateFn, consumerDestroy, REACTIVE_NODE, consumerPollProducersForChange, consumerBeforeComputation, consumerAfterComputation, createComputed, setThrowInvalidWriteToSignalError, untracked as untracked$1, isInNotificationPhase, createLinkedSignal, linkedSignalSetFn, linkedSignalUpdateFn } from './untracked-BKcld_ew.mjs';
  7. export { setAlternateWeakRefImpl as ɵsetAlternateWeakRefImpl } from './untracked-BKcld_ew.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. function formatRuntimeErrorCode(code) {
  50. // Error code might be a negative number, which is a special marker that instructs the logic to
  51. // generate a link to the error details page on angular.io.
  52. // We also prepend `0` to non-compile-time errors.
  53. return `NG0${Math.abs(code)}`;
  54. }
  55. /**
  56. * Called to format a runtime error.
  57. * See additional info on the `message` argument type in the `RuntimeError` class description.
  58. */
  59. function formatRuntimeError(code, message) {
  60. const fullCode = formatRuntimeErrorCode(code);
  61. let errorMessage = `${fullCode}${message ? ': ' + message : ''}`;
  62. if (ngDevMode && code < 0) {
  63. const addPeriodSeparator = !errorMessage.match(/[.,;!?\n]$/);
  64. const separator = addPeriodSeparator ? '.' : '';
  65. errorMessage = `${errorMessage}${separator} Find more at ${ERROR_DETAILS_PAGE_BASE_URL}/${fullCode}`;
  66. }
  67. return errorMessage;
  68. }
  69. const REQUIRED_UNSET_VALUE = /* @__PURE__ */ Symbol('InputSignalNode#UNSET');
  70. // Note: Using an IIFE here to ensure that the spread assignment is not considered
  71. // a side-effect, ending up preserving `COMPUTED_NODE` and `REACTIVE_NODE`.
  72. // TODO: remove when https://github.com/evanw/esbuild/issues/3392 is resolved.
  73. const INPUT_SIGNAL_NODE = /* @__PURE__ */ (() => {
  74. return {
  75. ...SIGNAL_NODE,
  76. transformFn: undefined,
  77. applyValueToInputSignal(node, value) {
  78. signalSetFn(node, value);
  79. },
  80. };
  81. })();
  82. const ɵINPUT_SIGNAL_BRAND_WRITE_TYPE = /* @__PURE__ */ Symbol();
  83. /**
  84. * Creates an input signal.
  85. *
  86. * @param initialValue The initial value.
  87. * Can be set to {@link REQUIRED_UNSET_VALUE} for required inputs.
  88. * @param options Additional options for the input. e.g. a transform, or an alias.
  89. */
  90. function createInputSignal(initialValue, options) {
  91. const node = Object.create(INPUT_SIGNAL_NODE);
  92. node.value = initialValue;
  93. // Perf note: Always set `transformFn` here to ensure that `node` always
  94. // has the same v8 class shape, allowing monomorphic reads on input signals.
  95. node.transformFn = options?.transform;
  96. function inputValueFn() {
  97. // Record that someone looked at this signal.
  98. producerAccessed(node);
  99. if (node.value === REQUIRED_UNSET_VALUE) {
  100. let message = null;
  101. if (ngDevMode) {
  102. const name = options?.debugName ?? options?.alias;
  103. message = `Input${name ? ` "${name}"` : ''} is required but no value is available yet.`;
  104. }
  105. throw new RuntimeError(-950 /* RuntimeErrorCode.REQUIRED_INPUT_NO_VALUE */, message);
  106. }
  107. return node.value;
  108. }
  109. inputValueFn[SIGNAL] = node;
  110. if (ngDevMode) {
  111. inputValueFn.toString = () => `[Input Signal: ${inputValueFn()}]`;
  112. node.debugName = options?.debugName;
  113. }
  114. return inputValueFn;
  115. }
  116. /**
  117. * Convince closure compiler that the wrapped function has no side-effects.
  118. *
  119. * Closure compiler always assumes that `toString` has no side-effects. We use this quirk to
  120. * allow us to execute a function but have closure compiler mark the call as no-side-effects.
  121. * It is important that the return value for the `noSideEffects` function be assigned
  122. * to something which is retained otherwise the call to `noSideEffects` will be removed by closure
  123. * compiler.
  124. */
  125. function noSideEffects(fn) {
  126. return { toString: fn }.toString();
  127. }
  128. const ANNOTATIONS = '__annotations__';
  129. const PARAMETERS = '__parameters__';
  130. const PROP_METADATA = '__prop__metadata__';
  131. /**
  132. * @suppress {globalThis}
  133. */
  134. function makeDecorator(name, props, parentClass, additionalProcessing, typeFn) {
  135. return noSideEffects(() => {
  136. const metaCtor = makeMetadataCtor(props);
  137. function DecoratorFactory(...args) {
  138. if (this instanceof DecoratorFactory) {
  139. metaCtor.call(this, ...args);
  140. return this;
  141. }
  142. const annotationInstance = new DecoratorFactory(...args);
  143. return function TypeDecorator(cls) {
  144. if (typeFn)
  145. typeFn(cls, ...args);
  146. // Use of Object.defineProperty is important since it creates non-enumerable property which
  147. // prevents the property is copied during subclassing.
  148. const annotations = cls.hasOwnProperty(ANNOTATIONS)
  149. ? cls[ANNOTATIONS]
  150. : Object.defineProperty(cls, ANNOTATIONS, { value: [] })[ANNOTATIONS];
  151. annotations.push(annotationInstance);
  152. return cls;
  153. };
  154. }
  155. if (parentClass) {
  156. DecoratorFactory.prototype = Object.create(parentClass.prototype);
  157. }
  158. DecoratorFactory.prototype.ngMetadataName = name;
  159. DecoratorFactory.annotationCls = DecoratorFactory;
  160. return DecoratorFactory;
  161. });
  162. }
  163. function makeMetadataCtor(props) {
  164. return function ctor(...args) {
  165. if (props) {
  166. const values = props(...args);
  167. for (const propName in values) {
  168. this[propName] = values[propName];
  169. }
  170. }
  171. };
  172. }
  173. function makeParamDecorator(name, props, parentClass) {
  174. return noSideEffects(() => {
  175. const metaCtor = makeMetadataCtor(props);
  176. function ParamDecoratorFactory(...args) {
  177. if (this instanceof ParamDecoratorFactory) {
  178. metaCtor.apply(this, args);
  179. return this;
  180. }
  181. const annotationInstance = new ParamDecoratorFactory(...args);
  182. ParamDecorator.annotation = annotationInstance;
  183. return ParamDecorator;
  184. function ParamDecorator(cls, unusedKey, index) {
  185. // Use of Object.defineProperty is important since it creates non-enumerable property which
  186. // prevents the property is copied during subclassing.
  187. const parameters = cls.hasOwnProperty(PARAMETERS)
  188. ? cls[PARAMETERS]
  189. : Object.defineProperty(cls, PARAMETERS, { value: [] })[PARAMETERS];
  190. // there might be gaps if some in between parameters do not have annotations.
  191. // we pad with nulls.
  192. while (parameters.length <= index) {
  193. parameters.push(null);
  194. }
  195. (parameters[index] = parameters[index] || []).push(annotationInstance);
  196. return cls;
  197. }
  198. }
  199. ParamDecoratorFactory.prototype.ngMetadataName = name;
  200. ParamDecoratorFactory.annotationCls = ParamDecoratorFactory;
  201. return ParamDecoratorFactory;
  202. });
  203. }
  204. function makePropDecorator(name, props, parentClass, additionalProcessing) {
  205. return noSideEffects(() => {
  206. const metaCtor = makeMetadataCtor(props);
  207. function PropDecoratorFactory(...args) {
  208. if (this instanceof PropDecoratorFactory) {
  209. metaCtor.apply(this, args);
  210. return this;
  211. }
  212. const decoratorInstance = new PropDecoratorFactory(...args);
  213. function PropDecorator(target, name) {
  214. // target is undefined with standard decorators. This case is not supported and will throw
  215. // if this decorator is used in JIT mode with standard decorators.
  216. if (target === undefined) {
  217. throw new Error('Standard Angular field decorators are not supported in JIT mode.');
  218. }
  219. const constructor = target.constructor;
  220. // Use of Object.defineProperty is important because it creates a non-enumerable property
  221. // which prevents the property from being copied during subclassing.
  222. const meta = constructor.hasOwnProperty(PROP_METADATA)
  223. ? constructor[PROP_METADATA]
  224. : Object.defineProperty(constructor, PROP_METADATA, { value: {} })[PROP_METADATA];
  225. meta[name] = (meta.hasOwnProperty(name) && meta[name]) || [];
  226. meta[name].unshift(decoratorInstance);
  227. }
  228. return PropDecorator;
  229. }
  230. if (parentClass) {
  231. PropDecoratorFactory.prototype = Object.create(parentClass.prototype);
  232. }
  233. PropDecoratorFactory.prototype.ngMetadataName = name;
  234. PropDecoratorFactory.annotationCls = PropDecoratorFactory;
  235. return PropDecoratorFactory;
  236. });
  237. }
  238. const _global = globalThis;
  239. function ngDevModeResetPerfCounters() {
  240. const locationString = typeof location !== 'undefined' ? location.toString() : '';
  241. const newCounters = {
  242. namedConstructors: locationString.indexOf('ngDevMode=namedConstructors') != -1,
  243. firstCreatePass: 0,
  244. tNode: 0,
  245. tView: 0,
  246. rendererCreateTextNode: 0,
  247. rendererSetText: 0,
  248. rendererCreateElement: 0,
  249. rendererAddEventListener: 0,
  250. rendererSetAttribute: 0,
  251. rendererRemoveAttribute: 0,
  252. rendererSetProperty: 0,
  253. rendererSetClassName: 0,
  254. rendererAddClass: 0,
  255. rendererRemoveClass: 0,
  256. rendererSetStyle: 0,
  257. rendererRemoveStyle: 0,
  258. rendererDestroy: 0,
  259. rendererDestroyNode: 0,
  260. rendererMoveNode: 0,
  261. rendererRemoveNode: 0,
  262. rendererAppendChild: 0,
  263. rendererInsertBefore: 0,
  264. rendererCreateComment: 0,
  265. hydratedNodes: 0,
  266. hydratedComponents: 0,
  267. dehydratedViewsRemoved: 0,
  268. dehydratedViewsCleanupRuns: 0,
  269. componentsSkippedHydration: 0,
  270. deferBlocksWithIncrementalHydration: 0,
  271. };
  272. // Make sure to refer to ngDevMode as ['ngDevMode'] for closure.
  273. const allowNgDevModeTrue = locationString.indexOf('ngDevMode=false') === -1;
  274. if (!allowNgDevModeTrue) {
  275. _global['ngDevMode'] = false;
  276. }
  277. else {
  278. if (typeof _global['ngDevMode'] !== 'object') {
  279. _global['ngDevMode'] = {};
  280. }
  281. Object.assign(_global['ngDevMode'], newCounters);
  282. }
  283. return newCounters;
  284. }
  285. /**
  286. * This function checks to see if the `ngDevMode` has been set. If yes,
  287. * then we honor it, otherwise we default to dev mode with additional checks.
  288. *
  289. * The idea is that unless we are doing production build where we explicitly
  290. * set `ngDevMode == false` we should be helping the developer by providing
  291. * as much early warning and errors as possible.
  292. *
  293. * `ɵɵdefineComponent` is guaranteed to have been called before any component template functions
  294. * (and thus Ivy instructions), so a single initialization there is sufficient to ensure ngDevMode
  295. * is defined for the entire instruction set.
  296. *
  297. * When checking `ngDevMode` on toplevel, always init it before referencing it
  298. * (e.g. `((typeof ngDevMode === 'undefined' || ngDevMode) && initNgDevMode())`), otherwise you can
  299. * get a `ReferenceError` like in https://github.com/angular/angular/issues/31595.
  300. *
  301. * Details on possible values for `ngDevMode` can be found on its docstring.
  302. *
  303. * NOTE:
  304. * - changes to the `ngDevMode` name must be synced with `compiler-cli/src/tooling.ts`.
  305. */
  306. function initNgDevMode() {
  307. // The below checks are to ensure that calling `initNgDevMode` multiple times does not
  308. // reset the counters.
  309. // If the `ngDevMode` is not an object, then it means we have not created the perf counters
  310. // yet.
  311. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  312. if (typeof ngDevMode !== 'object' || Object.keys(ngDevMode).length === 0) {
  313. ngDevModeResetPerfCounters();
  314. }
  315. return typeof ngDevMode !== 'undefined' && !!ngDevMode;
  316. }
  317. return false;
  318. }
  319. function getClosureSafeProperty(objWithPropertyToExtract) {
  320. for (let key in objWithPropertyToExtract) {
  321. if (objWithPropertyToExtract[key] === getClosureSafeProperty) {
  322. return key;
  323. }
  324. }
  325. throw Error('Could not find renamed property on target object.');
  326. }
  327. /**
  328. * Sets properties on a target object from a source object, but only if
  329. * the property doesn't already exist on the target object.
  330. * @param target The target to set properties on
  331. * @param source The source of the property keys and values to set
  332. */
  333. function fillProperties(target, source) {
  334. for (const key in source) {
  335. if (source.hasOwnProperty(key) && !target.hasOwnProperty(key)) {
  336. target[key] = source[key];
  337. }
  338. }
  339. }
  340. function stringify(token) {
  341. if (typeof token === 'string') {
  342. return token;
  343. }
  344. if (Array.isArray(token)) {
  345. return `[${token.map(stringify).join(', ')}]`;
  346. }
  347. if (token == null) {
  348. return '' + token;
  349. }
  350. const name = token.overriddenName || token.name;
  351. if (name) {
  352. return `${name}`;
  353. }
  354. const result = token.toString();
  355. if (result == null) {
  356. return '' + result;
  357. }
  358. const newLineIndex = result.indexOf('\n');
  359. return newLineIndex >= 0 ? result.slice(0, newLineIndex) : result;
  360. }
  361. /**
  362. * Concatenates two strings with separator, allocating new strings only when necessary.
  363. *
  364. * @param before before string.
  365. * @param separator separator string.
  366. * @param after after string.
  367. * @returns concatenated string.
  368. */
  369. function concatStringsWithSpace(before, after) {
  370. if (!before)
  371. return after || '';
  372. if (!after)
  373. return before;
  374. return `${before} ${after}`;
  375. }
  376. /**
  377. * Ellipses the string in the middle when longer than the max length
  378. *
  379. * @param string
  380. * @param maxLength of the output string
  381. * @returns ellipsed string with ... in the middle
  382. */
  383. function truncateMiddle(str, maxLength = 100) {
  384. if (!str || maxLength < 1 || str.length <= maxLength)
  385. return str;
  386. if (maxLength == 1)
  387. return str.substring(0, 1) + '...';
  388. const halfLimit = Math.round(maxLength / 2);
  389. return str.substring(0, halfLimit) + '...' + str.substring(str.length - halfLimit);
  390. }
  391. const __forward_ref__ = getClosureSafeProperty({ __forward_ref__: getClosureSafeProperty });
  392. /**
  393. * Allows to refer to references which are not yet defined.
  394. *
  395. * For instance, `forwardRef` is used when the `token` which we need to refer to for the purposes of
  396. * DI is declared, but not yet defined. It is also used when the `token` which we use when creating
  397. * a query is not yet defined.
  398. *
  399. * `forwardRef` is also used to break circularities in standalone components imports.
  400. *
  401. * @usageNotes
  402. * ### Circular dependency example
  403. * {@example core/di/ts/forward_ref/forward_ref_spec.ts region='forward_ref'}
  404. *
  405. * ### Circular standalone reference import example
  406. * ```angular-ts
  407. * @Component({
  408. * standalone: true,
  409. * imports: [ChildComponent],
  410. * selector: 'app-parent',
  411. * template: `<app-child [hideParent]="hideParent"></app-child>`,
  412. * })
  413. * export class ParentComponent {
  414. * @Input() hideParent: boolean;
  415. * }
  416. *
  417. *
  418. * @Component({
  419. * standalone: true,
  420. * imports: [CommonModule, forwardRef(() => ParentComponent)],
  421. * selector: 'app-child',
  422. * template: `<app-parent *ngIf="!hideParent"></app-parent>`,
  423. * })
  424. * export class ChildComponent {
  425. * @Input() hideParent: boolean;
  426. * }
  427. * ```
  428. *
  429. * @publicApi
  430. */
  431. function forwardRef(forwardRefFn) {
  432. forwardRefFn.__forward_ref__ = forwardRef;
  433. forwardRefFn.toString = function () {
  434. return stringify(this());
  435. };
  436. return forwardRefFn;
  437. }
  438. /**
  439. * Lazily retrieves the reference value from a forwardRef.
  440. *
  441. * Acts as the identity function when given a non-forward-ref value.
  442. *
  443. * @usageNotes
  444. * ### Example
  445. *
  446. * {@example core/di/ts/forward_ref/forward_ref_spec.ts region='resolve_forward_ref'}
  447. *
  448. * @see {@link forwardRef}
  449. * @publicApi
  450. */
  451. function resolveForwardRef(type) {
  452. return isForwardRef(type) ? type() : type;
  453. }
  454. /** Checks whether a function is wrapped by a `forwardRef`. */
  455. function isForwardRef(fn) {
  456. return (typeof fn === 'function' &&
  457. fn.hasOwnProperty(__forward_ref__) &&
  458. fn.__forward_ref__ === forwardRef);
  459. }
  460. // The functions in this file verify that the assumptions we are making
  461. // about state in an instruction are correct before implementing any logic.
  462. // They are meant only to be called in dev mode as sanity checks.
  463. function assertNumber(actual, msg) {
  464. if (!(typeof actual === 'number')) {
  465. throwError(msg, typeof actual, 'number', '===');
  466. }
  467. }
  468. function assertNumberInRange(actual, minInclusive, maxInclusive) {
  469. assertNumber(actual, 'Expected a number');
  470. assertLessThanOrEqual(actual, maxInclusive, 'Expected number to be less than or equal to');
  471. assertGreaterThanOrEqual(actual, minInclusive, 'Expected number to be greater than or equal to');
  472. }
  473. function assertString(actual, msg) {
  474. if (!(typeof actual === 'string')) {
  475. throwError(msg, actual === null ? 'null' : typeof actual, 'string', '===');
  476. }
  477. }
  478. function assertFunction(actual, msg) {
  479. if (!(typeof actual === 'function')) {
  480. throwError(msg, actual === null ? 'null' : typeof actual, 'function', '===');
  481. }
  482. }
  483. function assertEqual(actual, expected, msg) {
  484. if (!(actual == expected)) {
  485. throwError(msg, actual, expected, '==');
  486. }
  487. }
  488. function assertNotEqual(actual, expected, msg) {
  489. if (!(actual != expected)) {
  490. throwError(msg, actual, expected, '!=');
  491. }
  492. }
  493. function assertSame(actual, expected, msg) {
  494. if (!(actual === expected)) {
  495. throwError(msg, actual, expected, '===');
  496. }
  497. }
  498. function assertNotSame(actual, expected, msg) {
  499. if (!(actual !== expected)) {
  500. throwError(msg, actual, expected, '!==');
  501. }
  502. }
  503. function assertLessThan(actual, expected, msg) {
  504. if (!(actual < expected)) {
  505. throwError(msg, actual, expected, '<');
  506. }
  507. }
  508. function assertLessThanOrEqual(actual, expected, msg) {
  509. if (!(actual <= expected)) {
  510. throwError(msg, actual, expected, '<=');
  511. }
  512. }
  513. function assertGreaterThan(actual, expected, msg) {
  514. if (!(actual > expected)) {
  515. throwError(msg, actual, expected, '>');
  516. }
  517. }
  518. function assertGreaterThanOrEqual(actual, expected, msg) {
  519. if (!(actual >= expected)) {
  520. throwError(msg, actual, expected, '>=');
  521. }
  522. }
  523. function assertDefined(actual, msg) {
  524. if (actual == null) {
  525. throwError(msg, actual, null, '!=');
  526. }
  527. }
  528. function throwError(msg, actual, expected, comparison) {
  529. throw new Error(`ASSERTION ERROR: ${msg}` +
  530. (comparison == null ? '' : ` [Expected=> ${expected} ${comparison} ${actual} <=Actual]`));
  531. }
  532. function assertDomNode(node) {
  533. if (!(node instanceof Node)) {
  534. throwError(`The provided value must be an instance of a DOM Node but got ${stringify(node)}`);
  535. }
  536. }
  537. function assertElement(node) {
  538. if (!(node instanceof Element)) {
  539. throwError(`The provided value must be an element but got ${stringify(node)}`);
  540. }
  541. }
  542. function assertIndexInRange(arr, index) {
  543. assertDefined(arr, 'Array must be defined.');
  544. const maxLen = arr.length;
  545. if (index < 0 || index >= maxLen) {
  546. throwError(`Index expected to be less than ${maxLen} but got ${index}`);
  547. }
  548. }
  549. function assertOneOf(value, ...validValues) {
  550. if (validValues.indexOf(value) !== -1)
  551. return true;
  552. throwError(`Expected value to be one of ${JSON.stringify(validValues)} but was ${JSON.stringify(value)}.`);
  553. }
  554. function assertNotReactive(fn) {
  555. if (getActiveConsumer() !== null) {
  556. throwError(`${fn}() should never be called in a reactive context.`);
  557. }
  558. }
  559. /**
  560. * Construct an injectable definition which defines how a token will be constructed by the DI
  561. * system, and in which injectors (if any) it will be available.
  562. *
  563. * This should be assigned to a static `ɵprov` field on a type, which will then be an
  564. * `InjectableType`.
  565. *
  566. * Options:
  567. * * `providedIn` determines which injectors will include the injectable, by either associating it
  568. * with an `@NgModule` or other `InjectorType`, or by specifying that this injectable should be
  569. * provided in the `'root'` injector, which will be the application-level injector in most apps.
  570. * * `factory` gives the zero argument function which will create an instance of the injectable.
  571. * The factory can call [`inject`](api/core/inject) to access the `Injector` and request injection
  572. * of dependencies.
  573. *
  574. * @codeGenApi
  575. * @publicApi This instruction has been emitted by ViewEngine for some time and is deployed to npm.
  576. */
  577. function ɵɵdefineInjectable(opts) {
  578. return {
  579. token: opts.token,
  580. providedIn: opts.providedIn || null,
  581. factory: opts.factory,
  582. value: undefined,
  583. };
  584. }
  585. /**
  586. * @deprecated in v8, delete after v10. This API should be used only by generated code, and that
  587. * code should now use ɵɵdefineInjectable instead.
  588. * @publicApi
  589. */
  590. const defineInjectable = ɵɵdefineInjectable;
  591. /**
  592. * Construct an `InjectorDef` which configures an injector.
  593. *
  594. * This should be assigned to a static injector def (`ɵinj`) field on a type, which will then be an
  595. * `InjectorType`.
  596. *
  597. * Options:
  598. *
  599. * * `providers`: an optional array of providers to add to the injector. Each provider must
  600. * either have a factory or point to a type which has a `ɵprov` static property (the
  601. * type must be an `InjectableType`).
  602. * * `imports`: an optional array of imports of other `InjectorType`s or `InjectorTypeWithModule`s
  603. * whose providers will also be added to the injector. Locally provided types will override
  604. * providers from imports.
  605. *
  606. * @codeGenApi
  607. */
  608. function ɵɵdefineInjector(options) {
  609. return { providers: options.providers || [], imports: options.imports || [] };
  610. }
  611. /**
  612. * Read the injectable def (`ɵprov`) for `type` in a way which is immune to accidentally reading
  613. * inherited value.
  614. *
  615. * @param type A type which may have its own (non-inherited) `ɵprov`.
  616. */
  617. function getInjectableDef(type) {
  618. return getOwnDefinition(type, NG_PROV_DEF) || getOwnDefinition(type, NG_INJECTABLE_DEF);
  619. }
  620. function isInjectable(type) {
  621. return getInjectableDef(type) !== null;
  622. }
  623. /**
  624. * Return definition only if it is defined directly on `type` and is not inherited from a base
  625. * class of `type`.
  626. */
  627. function getOwnDefinition(type, field) {
  628. return type.hasOwnProperty(field) ? type[field] : null;
  629. }
  630. /**
  631. * Read the injectable def (`ɵprov`) for `type` or read the `ɵprov` from one of its ancestors.
  632. *
  633. * @param type A type which may have `ɵprov`, via inheritance.
  634. *
  635. * @deprecated Will be removed in a future version of Angular, where an error will occur in the
  636. * scenario if we find the `ɵprov` on an ancestor only.
  637. */
  638. function getInheritedInjectableDef(type) {
  639. const def = type && (type[NG_PROV_DEF] || type[NG_INJECTABLE_DEF]);
  640. if (def) {
  641. ngDevMode &&
  642. console.warn(`DEPRECATED: DI is instantiating a token "${type.name}" that inherits its @Injectable decorator but does not provide one itself.\n` +
  643. `This will become an error in a future version of Angular. Please add @Injectable() to the "${type.name}" class.`);
  644. return def;
  645. }
  646. else {
  647. return null;
  648. }
  649. }
  650. /**
  651. * Read the injector def type in a way which is immune to accidentally reading inherited value.
  652. *
  653. * @param type type which may have an injector def (`ɵinj`)
  654. */
  655. function getInjectorDef(type) {
  656. return type && (type.hasOwnProperty(NG_INJ_DEF) || type.hasOwnProperty(NG_INJECTOR_DEF))
  657. ? type[NG_INJ_DEF]
  658. : null;
  659. }
  660. const NG_PROV_DEF = getClosureSafeProperty({ ɵprov: getClosureSafeProperty });
  661. const NG_INJ_DEF = getClosureSafeProperty({ ɵinj: getClosureSafeProperty });
  662. // We need to keep these around so we can read off old defs if new defs are unavailable
  663. const NG_INJECTABLE_DEF = getClosureSafeProperty({
  664. ngInjectableDef: getClosureSafeProperty,
  665. });
  666. const NG_INJECTOR_DEF = getClosureSafeProperty({
  667. ngInjectorDef: getClosureSafeProperty,
  668. });
  669. /**
  670. * Creates a token that can be used in a DI Provider.
  671. *
  672. * Use an `InjectionToken` whenever the type you are injecting is not reified (does not have a
  673. * runtime representation) such as when injecting an interface, callable type, array or
  674. * parameterized type.
  675. *
  676. * `InjectionToken` is parameterized on `T` which is the type of object which will be returned by
  677. * the `Injector`. This provides an additional level of type safety.
  678. *
  679. * <div class="docs-alert docs-alert-helpful">
  680. *
  681. * **Important Note**: Ensure that you use the same instance of the `InjectionToken` in both the
  682. * provider and the injection call. Creating a new instance of `InjectionToken` in different places,
  683. * even with the same description, will be treated as different tokens by Angular's DI system,
  684. * leading to a `NullInjectorError`.
  685. *
  686. * </div>
  687. *
  688. * {@example injection-token/src/main.ts region='InjectionToken'}
  689. *
  690. * When creating an `InjectionToken`, you can optionally specify a factory function which returns
  691. * (possibly by creating) a default value of the parameterized type `T`. This sets up the
  692. * `InjectionToken` using this factory as a provider as if it was defined explicitly in the
  693. * application's root injector. If the factory function, which takes zero arguments, needs to inject
  694. * dependencies, it can do so using the [`inject`](api/core/inject) function.
  695. * As you can see in the Tree-shakable InjectionToken example below.
  696. *
  697. * Additionally, if a `factory` is specified you can also specify the `providedIn` option, which
  698. * overrides the above behavior and marks the token as belonging to a particular `@NgModule` (note:
  699. * this option is now deprecated). As mentioned above, `'root'` is the default value for
  700. * `providedIn`.
  701. *
  702. * The `providedIn: NgModule` and `providedIn: 'any'` options are deprecated.
  703. *
  704. * @usageNotes
  705. * ### Basic Examples
  706. *
  707. * ### Plain InjectionToken
  708. *
  709. * {@example core/di/ts/injector_spec.ts region='InjectionToken'}
  710. *
  711. * ### Tree-shakable InjectionToken
  712. *
  713. * {@example core/di/ts/injector_spec.ts region='ShakableInjectionToken'}
  714. *
  715. * @publicApi
  716. */
  717. class InjectionToken {
  718. _desc;
  719. /** @internal */
  720. ngMetadataName = 'InjectionToken';
  721. ɵprov;
  722. /**
  723. * @param _desc Description for the token,
  724. * used only for debugging purposes,
  725. * it should but does not need to be unique
  726. * @param options Options for the token's usage, as described above
  727. */
  728. constructor(_desc, options) {
  729. this._desc = _desc;
  730. this.ɵprov = undefined;
  731. if (typeof options == 'number') {
  732. (typeof ngDevMode === 'undefined' || ngDevMode) &&
  733. assertLessThan(options, 0, 'Only negative numbers are supported here');
  734. // This is a special hack to assign __NG_ELEMENT_ID__ to this instance.
  735. // See `InjectorMarkers`
  736. this.__NG_ELEMENT_ID__ = options;
  737. }
  738. else if (options !== undefined) {
  739. this.ɵprov = ɵɵdefineInjectable({
  740. token: this,
  741. providedIn: options.providedIn || 'root',
  742. factory: options.factory,
  743. });
  744. }
  745. }
  746. /**
  747. * @internal
  748. */
  749. get multi() {
  750. return this;
  751. }
  752. toString() {
  753. return `InjectionToken ${this._desc}`;
  754. }
  755. }
  756. let _injectorProfilerContext;
  757. function getInjectorProfilerContext() {
  758. !ngDevMode && throwError('getInjectorProfilerContext should never be called in production mode');
  759. return _injectorProfilerContext;
  760. }
  761. function setInjectorProfilerContext(context) {
  762. !ngDevMode && throwError('setInjectorProfilerContext should never be called in production mode');
  763. const previous = _injectorProfilerContext;
  764. _injectorProfilerContext = context;
  765. return previous;
  766. }
  767. let injectorProfilerCallback = null;
  768. /**
  769. * Sets the callback function which will be invoked during certain DI events within the
  770. * runtime (for example: injecting services, creating injectable instances, configuring providers)
  771. *
  772. * Warning: this function is *INTERNAL* and should not be relied upon in application's code.
  773. * The contract of the function might be changed in any release and/or the function can be removed
  774. * completely.
  775. *
  776. * @param profiler function provided by the caller or null value to disable profiling.
  777. */
  778. const setInjectorProfiler = (injectorProfiler) => {
  779. !ngDevMode && throwError('setInjectorProfiler should never be called in production mode');
  780. injectorProfilerCallback = injectorProfiler;
  781. };
  782. /**
  783. * Injector profiler function which emits on DI events executed by the runtime.
  784. *
  785. * @param event InjectorProfilerEvent corresponding to the DI event being emitted
  786. */
  787. function injectorProfiler(event) {
  788. !ngDevMode && throwError('Injector profiler should never be called in production mode');
  789. if (injectorProfilerCallback != null /* both `null` and `undefined` */) {
  790. injectorProfilerCallback(event);
  791. }
  792. }
  793. /**
  794. * Emits an InjectorProfilerEventType.ProviderConfigured to the injector profiler. The data in the
  795. * emitted event includes the raw provider, as well as the token that provider is providing.
  796. *
  797. * @param eventProvider A provider object
  798. */
  799. function emitProviderConfiguredEvent(eventProvider, isViewProvider = false) {
  800. !ngDevMode && throwError('Injector profiler should never be called in production mode');
  801. let token;
  802. // if the provider is a TypeProvider (typeof provider is function) then the token is the
  803. // provider itself
  804. if (typeof eventProvider === 'function') {
  805. token = eventProvider;
  806. }
  807. // if the provider is an injection token, then the token is the injection token.
  808. else if (eventProvider instanceof InjectionToken) {
  809. token = eventProvider;
  810. }
  811. // in all other cases we can access the token via the `provide` property of the provider
  812. else {
  813. token = resolveForwardRef(eventProvider.provide);
  814. }
  815. let provider = eventProvider;
  816. // Injection tokens may define their own default provider which gets attached to the token itself
  817. // as `ɵprov`. In this case, we want to emit the provider that is attached to the token, not the
  818. // token itself.
  819. if (eventProvider instanceof InjectionToken) {
  820. provider = eventProvider.ɵprov || eventProvider;
  821. }
  822. injectorProfiler({
  823. type: 2 /* InjectorProfilerEventType.ProviderConfigured */,
  824. context: getInjectorProfilerContext(),
  825. providerRecord: { token, provider, isViewProvider },
  826. });
  827. }
  828. /**
  829. * Emits an event to the injector profiler with the instance that was created. Note that
  830. * the injector associated with this emission can be accessed by using getDebugInjectContext()
  831. *
  832. * @param instance an object created by an injector
  833. */
  834. function emitInstanceCreatedByInjectorEvent(instance) {
  835. !ngDevMode && throwError('Injector profiler should never be called in production mode');
  836. injectorProfiler({
  837. type: 1 /* InjectorProfilerEventType.InstanceCreatedByInjector */,
  838. context: getInjectorProfilerContext(),
  839. instance: { value: instance },
  840. });
  841. }
  842. /**
  843. * @param token DI token associated with injected service
  844. * @param value the instance of the injected service (i.e the result of `inject(token)`)
  845. * @param flags the flags that the token was injected with
  846. */
  847. function emitInjectEvent(token, value, flags) {
  848. !ngDevMode && throwError('Injector profiler should never be called in production mode');
  849. injectorProfiler({
  850. type: 0 /* InjectorProfilerEventType.Inject */,
  851. context: getInjectorProfilerContext(),
  852. service: { token, value, flags },
  853. });
  854. }
  855. function emitEffectCreatedEvent(effect) {
  856. !ngDevMode && throwError('Injector profiler should never be called in production mode');
  857. injectorProfiler({
  858. type: 3 /* InjectorProfilerEventType.EffectCreated */,
  859. context: getInjectorProfilerContext(),
  860. effect,
  861. });
  862. }
  863. function runInInjectorProfilerContext(injector, token, callback) {
  864. !ngDevMode &&
  865. throwError('runInInjectorProfilerContext should never be called in production mode');
  866. const prevInjectContext = setInjectorProfilerContext({ injector, token });
  867. try {
  868. callback();
  869. }
  870. finally {
  871. setInjectorProfilerContext(prevInjectContext);
  872. }
  873. }
  874. function isEnvironmentProviders(value) {
  875. return value && !!value.ɵproviders;
  876. }
  877. const NG_COMP_DEF = getClosureSafeProperty({ ɵcmp: getClosureSafeProperty });
  878. const NG_DIR_DEF = getClosureSafeProperty({ ɵdir: getClosureSafeProperty });
  879. const NG_PIPE_DEF = getClosureSafeProperty({ ɵpipe: getClosureSafeProperty });
  880. const NG_MOD_DEF = getClosureSafeProperty({ ɵmod: getClosureSafeProperty });
  881. const NG_FACTORY_DEF = getClosureSafeProperty({ ɵfac: getClosureSafeProperty });
  882. /**
  883. * If a directive is diPublic, bloomAdd sets a property on the type with this constant as
  884. * the key and the directive's unique ID as the value. This allows us to map directives to their
  885. * bloom filter bit for DI.
  886. */
  887. // TODO(misko): This is wrong. The NG_ELEMENT_ID should never be minified.
  888. const NG_ELEMENT_ID = getClosureSafeProperty({
  889. __NG_ELEMENT_ID__: getClosureSafeProperty,
  890. });
  891. /**
  892. * The `NG_ENV_ID` field on a DI token indicates special processing in the `EnvironmentInjector`:
  893. * getting such tokens from the `EnvironmentInjector` will bypass the standard DI resolution
  894. * strategy and instead will return implementation produced by the `NG_ENV_ID` factory function.
  895. *
  896. * This particular retrieval of DI tokens is mostly done to eliminate circular dependencies and
  897. * improve tree-shaking.
  898. */
  899. const NG_ENV_ID = getClosureSafeProperty({ __NG_ENV_ID__: getClosureSafeProperty });
  900. /**
  901. * Used for stringify render output in Ivy.
  902. * Important! This function is very performance-sensitive and we should
  903. * be extra careful not to introduce megamorphic reads in it.
  904. * Check `core/test/render3/perf/render_stringify` for benchmarks and alternate implementations.
  905. */
  906. function renderStringify(value) {
  907. if (typeof value === 'string')
  908. return value;
  909. if (value == null)
  910. return '';
  911. // Use `String` so that it invokes the `toString` method of the value. Note that this
  912. // appears to be faster than calling `value.toString` (see `render_stringify` benchmark).
  913. return String(value);
  914. }
  915. /**
  916. * Used to stringify a value so that it can be displayed in an error message.
  917. *
  918. * Important! This function contains a megamorphic read and should only be
  919. * used for error messages.
  920. */
  921. function stringifyForError(value) {
  922. if (typeof value === 'function')
  923. return value.name || value.toString();
  924. if (typeof value === 'object' && value != null && typeof value.type === 'function') {
  925. return value.type.name || value.type.toString();
  926. }
  927. return renderStringify(value);
  928. }
  929. /**
  930. * Used to stringify a `Type` and including the file path and line number in which it is defined, if
  931. * possible, for better debugging experience.
  932. *
  933. * Important! This function contains a megamorphic read and should only be used for error messages.
  934. */
  935. function debugStringifyTypeForError(type) {
  936. // TODO(pmvald): Do some refactoring so that we can use getComponentDef here without creating
  937. // circular deps.
  938. let componentDef = type[NG_COMP_DEF] || null;
  939. if (componentDef !== null && componentDef.debugInfo) {
  940. return stringifyTypeFromDebugInfo(componentDef.debugInfo);
  941. }
  942. return stringifyForError(type);
  943. }
  944. // TODO(pmvald): Do some refactoring so that we can use the type ClassDebugInfo for the param
  945. // debugInfo here without creating circular deps.
  946. function stringifyTypeFromDebugInfo(debugInfo) {
  947. if (!debugInfo.filePath || !debugInfo.lineNumber) {
  948. return debugInfo.className;
  949. }
  950. else {
  951. return `${debugInfo.className} (at ${debugInfo.filePath}:${debugInfo.lineNumber})`;
  952. }
  953. }
  954. /** Called when directives inject each other (creating a circular dependency) */
  955. function throwCyclicDependencyError(token, path) {
  956. throw new RuntimeError(-200 /* RuntimeErrorCode.CYCLIC_DI_DEPENDENCY */, ngDevMode
  957. ? `Circular dependency in DI detected for ${token}${path ? `. Dependency path: ${path.join(' > ')} > ${token}` : ''}`
  958. : token);
  959. }
  960. function throwMixedMultiProviderError() {
  961. throw new Error(`Cannot mix multi providers and regular providers`);
  962. }
  963. function throwInvalidProviderError(ngModuleType, providers, provider) {
  964. if (ngModuleType && providers) {
  965. const providerDetail = providers.map((v) => (v == provider ? '?' + provider + '?' : '...'));
  966. throw new Error(`Invalid provider for the NgModule '${stringify(ngModuleType)}' - only instances of Provider and Type are allowed, got: [${providerDetail.join(', ')}]`);
  967. }
  968. else if (isEnvironmentProviders(provider)) {
  969. if (provider.ɵfromNgModule) {
  970. 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.`);
  971. }
  972. else {
  973. 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.`);
  974. }
  975. }
  976. else {
  977. throw new Error('Invalid provider');
  978. }
  979. }
  980. /** Throws an error when a token is not found in DI. */
  981. function throwProviderNotFoundError(token, injectorName) {
  982. const errorMessage = ngDevMode &&
  983. `No provider for ${stringifyForError(token)} found${injectorName ? ` in ${injectorName}` : ''}`;
  984. throw new RuntimeError(-201 /* RuntimeErrorCode.PROVIDER_NOT_FOUND */, errorMessage);
  985. }
  986. /**
  987. * Injection flags for DI.
  988. *
  989. * @publicApi
  990. * @deprecated use an options object for [`inject`](api/core/inject) instead.
  991. */
  992. var InjectFlags;
  993. (function (InjectFlags) {
  994. // TODO(alxhub): make this 'const' (and remove `InternalInjectFlags` enum) when ngc no longer
  995. // writes exports of it into ngfactory files.
  996. /** Check self and check parent injector if needed */
  997. InjectFlags[InjectFlags["Default"] = 0] = "Default";
  998. /**
  999. * Specifies that an injector should retrieve a dependency from any injector until reaching the
  1000. * host element of the current component. (Only used with Element Injector)
  1001. */
  1002. InjectFlags[InjectFlags["Host"] = 1] = "Host";
  1003. /** Don't ascend to ancestors of the node requesting injection. */
  1004. InjectFlags[InjectFlags["Self"] = 2] = "Self";
  1005. /** Skip the node that is requesting injection. */
  1006. InjectFlags[InjectFlags["SkipSelf"] = 4] = "SkipSelf";
  1007. /** Inject `defaultValue` instead if token not found. */
  1008. InjectFlags[InjectFlags["Optional"] = 8] = "Optional";
  1009. })(InjectFlags || (InjectFlags = {}));
  1010. /**
  1011. * Current implementation of inject.
  1012. *
  1013. * By default, it is `injectInjectorOnly`, which makes it `Injector`-only aware. It can be changed
  1014. * to `directiveInject`, which brings in the `NodeInjector` system of ivy. It is designed this
  1015. * way for two reasons:
  1016. * 1. `Injector` should not depend on ivy logic.
  1017. * 2. To maintain tree shake-ability we don't want to bring in unnecessary code.
  1018. */
  1019. let _injectImplementation;
  1020. function getInjectImplementation() {
  1021. return _injectImplementation;
  1022. }
  1023. /**
  1024. * Sets the current inject implementation.
  1025. */
  1026. function setInjectImplementation(impl) {
  1027. const previous = _injectImplementation;
  1028. _injectImplementation = impl;
  1029. return previous;
  1030. }
  1031. /**
  1032. * Injects `root` tokens in limp mode.
  1033. *
  1034. * If no injector exists, we can still inject tree-shakable providers which have `providedIn` set to
  1035. * `"root"`. This is known as the limp mode injection. In such case the value is stored in the
  1036. * injectable definition.
  1037. */
  1038. function injectRootLimpMode(token, notFoundValue, flags) {
  1039. const injectableDef = getInjectableDef(token);
  1040. if (injectableDef && injectableDef.providedIn == 'root') {
  1041. return injectableDef.value === undefined
  1042. ? (injectableDef.value = injectableDef.factory())
  1043. : injectableDef.value;
  1044. }
  1045. if (flags & InjectFlags.Optional)
  1046. return null;
  1047. if (notFoundValue !== undefined)
  1048. return notFoundValue;
  1049. throwProviderNotFoundError(token, 'Injector');
  1050. }
  1051. /**
  1052. * Assert that `_injectImplementation` is not `fn`.
  1053. *
  1054. * This is useful, to prevent infinite recursion.
  1055. *
  1056. * @param fn Function which it should not equal to
  1057. */
  1058. function assertInjectImplementationNotEqual(fn) {
  1059. ngDevMode &&
  1060. assertNotEqual(_injectImplementation, fn, 'Calling ɵɵinject would cause infinite recursion');
  1061. }
  1062. const _THROW_IF_NOT_FOUND = {};
  1063. const THROW_IF_NOT_FOUND = _THROW_IF_NOT_FOUND;
  1064. /*
  1065. * Name of a property (that we patch onto DI decorator), which is used as an annotation of which
  1066. * InjectFlag this decorator represents. This allows to avoid direct references to the DI decorators
  1067. * in the code, thus making them tree-shakable.
  1068. */
  1069. const DI_DECORATOR_FLAG = '__NG_DI_FLAG__';
  1070. class RetrievingInjector {
  1071. injector;
  1072. constructor(injector) {
  1073. this.injector = injector;
  1074. }
  1075. retrieve(token, options) {
  1076. const ngOptions = options;
  1077. return this.injector.get(token, ngOptions.optional ? NOT_FOUND$1 : THROW_IF_NOT_FOUND, ngOptions);
  1078. }
  1079. }
  1080. const NG_TEMP_TOKEN_PATH = 'ngTempTokenPath';
  1081. const NG_TOKEN_PATH = 'ngTokenPath';
  1082. const NEW_LINE = /\n/gm;
  1083. const NO_NEW_LINE = 'ɵ';
  1084. const SOURCE = '__source';
  1085. function injectInjectorOnly(token, flags = InjectFlags.Default) {
  1086. if (getCurrentInjector() === undefined) {
  1087. throw new RuntimeError(-203 /* RuntimeErrorCode.MISSING_INJECTION_CONTEXT */, ngDevMode &&
  1088. `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\`.`);
  1089. }
  1090. else if (getCurrentInjector() === null) {
  1091. return injectRootLimpMode(token, undefined, flags);
  1092. }
  1093. else {
  1094. const currentInjector = getCurrentInjector();
  1095. let injector;
  1096. if (currentInjector instanceof RetrievingInjector) {
  1097. injector = currentInjector.injector;
  1098. }
  1099. else {
  1100. injector = currentInjector;
  1101. }
  1102. const value = injector.get(token, flags & InjectFlags.Optional ? null : undefined, flags);
  1103. ngDevMode && emitInjectEvent(token, value, flags);
  1104. return value;
  1105. }
  1106. }
  1107. function ɵɵinject(token, flags = InjectFlags.Default) {
  1108. return (getInjectImplementation() || injectInjectorOnly)(resolveForwardRef(token), flags);
  1109. }
  1110. /**
  1111. * Throws an error indicating that a factory function could not be generated by the compiler for a
  1112. * particular class.
  1113. *
  1114. * The name of the class is not mentioned here, but will be in the generated factory function name
  1115. * and thus in the stack trace.
  1116. *
  1117. * @codeGenApi
  1118. */
  1119. function ɵɵinvalidFactoryDep(index) {
  1120. throw new RuntimeError(202 /* RuntimeErrorCode.INVALID_FACTORY_DEPENDENCY */, ngDevMode &&
  1121. `This constructor is not compatible with Angular Dependency Injection because its dependency at index ${index} of the parameter list is invalid.
  1122. 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.
  1123. 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.`);
  1124. }
  1125. /**
  1126. * Injects a token from the currently active injector.
  1127. * `inject` is only supported in an [injection context](guide/di/dependency-injection-context). It
  1128. * can be used during:
  1129. * - Construction (via the `constructor`) of a class being instantiated by the DI system, such
  1130. * as an `@Injectable` or `@Component`.
  1131. * - In the initializer for fields of such classes.
  1132. * - In the factory function specified for `useFactory` of a `Provider` or an `@Injectable`.
  1133. * - In the `factory` function specified for an `InjectionToken`.
  1134. * - In a stackframe of a function call in a DI context
  1135. *
  1136. * @param token A token that represents a dependency that should be injected.
  1137. * @param flags Optional flags that control how injection is executed.
  1138. * The flags correspond to injection strategies that can be specified with
  1139. * parameter decorators `@Host`, `@Self`, `@SkipSelf`, and `@Optional`.
  1140. * @returns the injected value if operation is successful, `null` otherwise.
  1141. * @throws if called outside of a supported context.
  1142. *
  1143. * @usageNotes
  1144. * In practice the `inject()` calls are allowed in a constructor, a constructor parameter and a
  1145. * field initializer:
  1146. *
  1147. * ```ts
  1148. * @Injectable({providedIn: 'root'})
  1149. * export class Car {
  1150. * radio: Radio|undefined;
  1151. * // OK: field initializer
  1152. * spareTyre = inject(Tyre);
  1153. *
  1154. * constructor() {
  1155. * // OK: constructor body
  1156. * this.radio = inject(Radio);
  1157. * }
  1158. * }
  1159. * ```
  1160. *
  1161. * It is also legal to call `inject` from a provider's factory:
  1162. *
  1163. * ```ts
  1164. * providers: [
  1165. * {provide: Car, useFactory: () => {
  1166. * // OK: a class factory
  1167. * const engine = inject(Engine);
  1168. * return new Car(engine);
  1169. * }}
  1170. * ]
  1171. * ```
  1172. *
  1173. * Calls to the `inject()` function outside of the class creation context will result in error. Most
  1174. * notably, calls to `inject()` are disallowed after a class instance was created, in methods
  1175. * (including lifecycle hooks):
  1176. *
  1177. * ```ts
  1178. * @Component({ ... })
  1179. * export class CarComponent {
  1180. * ngOnInit() {
  1181. * // ERROR: too late, the component instance was already created
  1182. * const engine = inject(Engine);
  1183. * engine.start();
  1184. * }
  1185. * }
  1186. * ```
  1187. *
  1188. * @publicApi
  1189. */
  1190. function inject(token, flags = InjectFlags.Default) {
  1191. // The `as any` here _shouldn't_ be necessary, but without it JSCompiler
  1192. // throws a disambiguation error due to the multiple signatures.
  1193. return ɵɵinject(token, convertToBitFlags(flags));
  1194. }
  1195. // Converts object-based DI flags (`InjectOptions`) to bit flags (`InjectFlags`).
  1196. function convertToBitFlags(flags) {
  1197. if (typeof flags === 'undefined' || typeof flags === 'number') {
  1198. return flags;
  1199. }
  1200. // While TypeScript doesn't accept it without a cast, bitwise OR with false-y values in
  1201. // JavaScript is a no-op. We can use that for a very codesize-efficient conversion from
  1202. // `InjectOptions` to `InjectFlags`.
  1203. return (0 /* InternalInjectFlags.Default */ | // comment to force a line break in the formatter
  1204. (flags.optional && 8 /* InternalInjectFlags.Optional */) |
  1205. (flags.host && 1 /* InternalInjectFlags.Host */) |
  1206. (flags.self && 2 /* InternalInjectFlags.Self */) |
  1207. (flags.skipSelf && 4 /* InternalInjectFlags.SkipSelf */));
  1208. }
  1209. function injectArgs(types) {
  1210. const args = [];
  1211. for (let i = 0; i < types.length; i++) {
  1212. const arg = resolveForwardRef(types[i]);
  1213. if (Array.isArray(arg)) {
  1214. if (arg.length === 0) {
  1215. throw new RuntimeError(900 /* RuntimeErrorCode.INVALID_DIFFER_INPUT */, ngDevMode && 'Arguments array must have arguments.');
  1216. }
  1217. let type = undefined;
  1218. let flags = InjectFlags.Default;
  1219. for (let j = 0; j < arg.length; j++) {
  1220. const meta = arg[j];
  1221. const flag = getInjectFlag(meta);
  1222. if (typeof flag === 'number') {
  1223. // Special case when we handle @Inject decorator.
  1224. if (flag === -1 /* DecoratorFlags.Inject */) {
  1225. type = meta.token;
  1226. }
  1227. else {
  1228. flags |= flag;
  1229. }
  1230. }
  1231. else {
  1232. type = meta;
  1233. }
  1234. }
  1235. args.push(ɵɵinject(type, flags));
  1236. }
  1237. else {
  1238. args.push(ɵɵinject(arg));
  1239. }
  1240. }
  1241. return args;
  1242. }
  1243. /**
  1244. * Attaches a given InjectFlag to a given decorator using monkey-patching.
  1245. * Since DI decorators can be used in providers `deps` array (when provider is configured using
  1246. * `useFactory`) without initialization (e.g. `Host`) and as an instance (e.g. `new Host()`), we
  1247. * attach the flag to make it available both as a static property and as a field on decorator
  1248. * instance.
  1249. *
  1250. * @param decorator Provided DI decorator.
  1251. * @param flag InjectFlag that should be applied.
  1252. */
  1253. function attachInjectFlag(decorator, flag) {
  1254. decorator[DI_DECORATOR_FLAG] = flag;
  1255. decorator.prototype[DI_DECORATOR_FLAG] = flag;
  1256. return decorator;
  1257. }
  1258. /**
  1259. * Reads monkey-patched property that contains InjectFlag attached to a decorator.
  1260. *
  1261. * @param token Token that may contain monkey-patched DI flags property.
  1262. */
  1263. function getInjectFlag(token) {
  1264. return token[DI_DECORATOR_FLAG];
  1265. }
  1266. function catchInjectorError(e, token, injectorErrorName, source) {
  1267. const tokenPath = e[NG_TEMP_TOKEN_PATH];
  1268. if (token[SOURCE]) {
  1269. tokenPath.unshift(token[SOURCE]);
  1270. }
  1271. e.message = formatError('\n' + e.message, tokenPath, injectorErrorName, source);
  1272. e[NG_TOKEN_PATH] = tokenPath;
  1273. e[NG_TEMP_TOKEN_PATH] = null;
  1274. throw e;
  1275. }
  1276. function formatError(text, obj, injectorErrorName, source = null) {
  1277. text = text && text.charAt(0) === '\n' && text.charAt(1) == NO_NEW_LINE ? text.slice(2) : text;
  1278. let context = stringify(obj);
  1279. if (Array.isArray(obj)) {
  1280. context = obj.map(stringify).join(' -> ');
  1281. }
  1282. else if (typeof obj === 'object') {
  1283. let parts = [];
  1284. for (let key in obj) {
  1285. if (obj.hasOwnProperty(key)) {
  1286. let value = obj[key];
  1287. parts.push(key + ':' + (typeof value === 'string' ? JSON.stringify(value) : stringify(value)));
  1288. }
  1289. }
  1290. context = `{${parts.join(', ')}}`;
  1291. }
  1292. return `${injectorErrorName}${source ? '(' + source + ')' : ''}[${context}]: ${text.replace(NEW_LINE, '\n ')}`;
  1293. }
  1294. /**
  1295. * Inject decorator and metadata.
  1296. *
  1297. * @Annotation
  1298. * @publicApi
  1299. */
  1300. const Inject = attachInjectFlag(
  1301. // Disable tslint because `DecoratorFlags` is a const enum which gets inlined.
  1302. makeParamDecorator('Inject', (token) => ({ token })), -1 /* DecoratorFlags.Inject */);
  1303. /**
  1304. * Optional decorator and metadata.
  1305. *
  1306. * @Annotation
  1307. * @publicApi
  1308. */
  1309. const Optional =
  1310. // Disable tslint because `InternalInjectFlags` is a const enum which gets inlined.
  1311. // tslint:disable-next-line: no-toplevel-property-access
  1312. attachInjectFlag(makeParamDecorator('Optional'), 8 /* InternalInjectFlags.Optional */);
  1313. /**
  1314. * Self decorator and metadata.
  1315. *
  1316. * @Annotation
  1317. * @publicApi
  1318. */
  1319. const Self =
  1320. // Disable tslint because `InternalInjectFlags` is a const enum which gets inlined.
  1321. // tslint:disable-next-line: no-toplevel-property-access
  1322. attachInjectFlag(makeParamDecorator('Self'), 2 /* InternalInjectFlags.Self */);
  1323. /**
  1324. * `SkipSelf` decorator and metadata.
  1325. *
  1326. * @Annotation
  1327. * @publicApi
  1328. */
  1329. const SkipSelf =
  1330. // Disable tslint because `InternalInjectFlags` is a const enum which gets inlined.
  1331. // tslint:disable-next-line: no-toplevel-property-access
  1332. attachInjectFlag(makeParamDecorator('SkipSelf'), 4 /* InternalInjectFlags.SkipSelf */);
  1333. /**
  1334. * Host decorator and metadata.
  1335. *
  1336. * @Annotation
  1337. * @publicApi
  1338. */
  1339. const Host =
  1340. // Disable tslint because `InternalInjectFlags` is a const enum which gets inlined.
  1341. // tslint:disable-next-line: no-toplevel-property-access
  1342. attachInjectFlag(makeParamDecorator('Host'), 1 /* InternalInjectFlags.Host */);
  1343. function getFactoryDef(type, throwNotFound) {
  1344. const hasFactoryDef = type.hasOwnProperty(NG_FACTORY_DEF);
  1345. if (!hasFactoryDef && throwNotFound === true && ngDevMode) {
  1346. throw new Error(`Type ${stringify(type)} does not have 'ɵfac' property.`);
  1347. }
  1348. return hasFactoryDef ? type[NG_FACTORY_DEF] : null;
  1349. }
  1350. /**
  1351. * Determines if the contents of two arrays is identical
  1352. *
  1353. * @param a first array
  1354. * @param b second array
  1355. * @param identityAccessor Optional function for extracting stable object identity from a value in
  1356. * the array.
  1357. */
  1358. function arrayEquals(a, b, identityAccessor) {
  1359. if (a.length !== b.length)
  1360. return false;
  1361. for (let i = 0; i < a.length; i++) {
  1362. let valueA = a[i];
  1363. let valueB = b[i];
  1364. if (identityAccessor) {
  1365. valueA = identityAccessor(valueA);
  1366. valueB = identityAccessor(valueB);
  1367. }
  1368. if (valueB !== valueA) {
  1369. return false;
  1370. }
  1371. }
  1372. return true;
  1373. }
  1374. /**
  1375. * Flattens an array.
  1376. */
  1377. function flatten(list) {
  1378. return list.flat(Number.POSITIVE_INFINITY);
  1379. }
  1380. function deepForEach(input, fn) {
  1381. input.forEach((value) => (Array.isArray(value) ? deepForEach(value, fn) : fn(value)));
  1382. }
  1383. function addToArray(arr, index, value) {
  1384. // perf: array.push is faster than array.splice!
  1385. if (index >= arr.length) {
  1386. arr.push(value);
  1387. }
  1388. else {
  1389. arr.splice(index, 0, value);
  1390. }
  1391. }
  1392. function removeFromArray(arr, index) {
  1393. // perf: array.pop is faster than array.splice!
  1394. if (index >= arr.length - 1) {
  1395. return arr.pop();
  1396. }
  1397. else {
  1398. return arr.splice(index, 1)[0];
  1399. }
  1400. }
  1401. function newArray(size, value) {
  1402. const list = [];
  1403. for (let i = 0; i < size; i++) {
  1404. list.push(value);
  1405. }
  1406. return list;
  1407. }
  1408. /**
  1409. * Remove item from array (Same as `Array.splice()` but faster.)
  1410. *
  1411. * `Array.splice()` is not as fast because it has to allocate an array for the elements which were
  1412. * removed. This causes memory pressure and slows down code when most of the time we don't
  1413. * care about the deleted items array.
  1414. *
  1415. * https://jsperf.com/fast-array-splice (About 20x faster)
  1416. *
  1417. * @param array Array to splice
  1418. * @param index Index of element in array to remove.
  1419. * @param count Number of items to remove.
  1420. */
  1421. function arraySplice(array, index, count) {
  1422. const length = array.length - count;
  1423. while (index < length) {
  1424. array[index] = array[index + count];
  1425. index++;
  1426. }
  1427. while (count--) {
  1428. array.pop(); // shrink the array
  1429. }
  1430. }
  1431. /**
  1432. * Same as `Array.splice2(index, 0, value1, value2)` but faster.
  1433. *
  1434. * `Array.splice()` is not fast because it has to allocate an array for the elements which were
  1435. * removed. This causes memory pressure and slows down code when most of the time we don't
  1436. * care about the deleted items array.
  1437. *
  1438. * @param array Array to splice.
  1439. * @param index Index in array where the `value` should be added.
  1440. * @param value1 Value to add to array.
  1441. * @param value2 Value to add to array.
  1442. */
  1443. function arrayInsert2(array, index, value1, value2) {
  1444. ngDevMode && assertLessThanOrEqual(index, array.length, "Can't insert past array end.");
  1445. let end = array.length;
  1446. if (end == index) {
  1447. // inserting at the end.
  1448. array.push(value1, value2);
  1449. }
  1450. else if (end === 1) {
  1451. // corner case when we have less items in array than we have items to insert.
  1452. array.push(value2, array[0]);
  1453. array[0] = value1;
  1454. }
  1455. else {
  1456. end--;
  1457. array.push(array[end - 1], array[end]);
  1458. while (end > index) {
  1459. const previousEnd = end - 2;
  1460. array[end] = array[previousEnd];
  1461. end--;
  1462. }
  1463. array[index] = value1;
  1464. array[index + 1] = value2;
  1465. }
  1466. }
  1467. /**
  1468. * Set a `value` for a `key`.
  1469. *
  1470. * @param keyValueArray to modify.
  1471. * @param key The key to locate or create.
  1472. * @param value The value to set for a `key`.
  1473. * @returns index (always even) of where the value vas set.
  1474. */
  1475. function keyValueArraySet(keyValueArray, key, value) {
  1476. let index = keyValueArrayIndexOf(keyValueArray, key);
  1477. if (index >= 0) {
  1478. // if we found it set it.
  1479. keyValueArray[index | 1] = value;
  1480. }
  1481. else {
  1482. index = ~index;
  1483. arrayInsert2(keyValueArray, index, key, value);
  1484. }
  1485. return index;
  1486. }
  1487. /**
  1488. * Retrieve a `value` for a `key` (on `undefined` if not found.)
  1489. *
  1490. * @param keyValueArray to search.
  1491. * @param key The key to locate.
  1492. * @return The `value` stored at the `key` location or `undefined if not found.
  1493. */
  1494. function keyValueArrayGet(keyValueArray, key) {
  1495. const index = keyValueArrayIndexOf(keyValueArray, key);
  1496. if (index >= 0) {
  1497. // if we found it retrieve it.
  1498. return keyValueArray[index | 1];
  1499. }
  1500. return undefined;
  1501. }
  1502. /**
  1503. * Retrieve a `key` index value in the array or `-1` if not found.
  1504. *
  1505. * @param keyValueArray to search.
  1506. * @param key The key to locate.
  1507. * @returns index of where the key is (or should have been.)
  1508. * - positive (even) index if key found.
  1509. * - negative index if key not found. (`~index` (even) to get the index where it should have
  1510. * been inserted.)
  1511. */
  1512. function keyValueArrayIndexOf(keyValueArray, key) {
  1513. return _arrayIndexOfSorted(keyValueArray, key, 1);
  1514. }
  1515. /**
  1516. * INTERNAL: Get an index of an `value` in a sorted `array` by grouping search by `shift`.
  1517. *
  1518. * NOTE:
  1519. * - This uses binary search algorithm for fast removals.
  1520. *
  1521. * @param array A sorted array to binary search.
  1522. * @param value The value to look for.
  1523. * @param shift grouping shift.
  1524. * - `0` means look at every location
  1525. * - `1` means only look at every other (even) location (the odd locations are to be ignored as
  1526. * they are values.)
  1527. * @returns index of the value.
  1528. * - positive index if value found.
  1529. * - negative index if value not found. (`~index` to get the value where it should have been
  1530. * inserted)
  1531. */
  1532. function _arrayIndexOfSorted(array, value, shift) {
  1533. ngDevMode && assertEqual(Array.isArray(array), true, 'Expecting an array');
  1534. let start = 0;
  1535. let end = array.length >> shift;
  1536. while (end !== start) {
  1537. const middle = start + ((end - start) >> 1); // find the middle.
  1538. const current = array[middle << shift];
  1539. if (value === current) {
  1540. return middle << shift;
  1541. }
  1542. else if (current > value) {
  1543. end = middle;
  1544. }
  1545. else {
  1546. start = middle + 1; // We already searched middle so make it non-inclusive by adding 1
  1547. }
  1548. }
  1549. return ~(end << shift);
  1550. }
  1551. /**
  1552. * This file contains reuseable "empty" symbols that can be used as default return values
  1553. * in different parts of the rendering code. Because the same symbols are returned, this
  1554. * allows for identity checks against these values to be consistently used by the framework
  1555. * code.
  1556. */
  1557. const EMPTY_OBJ = {};
  1558. const EMPTY_ARRAY = [];
  1559. // freezing the values prevents any code from accidentally inserting new values in
  1560. if ((typeof ngDevMode === 'undefined' || ngDevMode) && initNgDevMode()) {
  1561. // These property accesses can be ignored because ngDevMode will be set to false
  1562. // when optimizing code and the whole if statement will be dropped.
  1563. // tslint:disable-next-line:no-toplevel-property-access
  1564. Object.freeze(EMPTY_OBJ);
  1565. // tslint:disable-next-line:no-toplevel-property-access
  1566. Object.freeze(EMPTY_ARRAY);
  1567. }
  1568. /**
  1569. * A multi-provider token for initialization functions that will run upon construction of an
  1570. * environment injector.
  1571. *
  1572. * @deprecated from v19.0.0, use provideEnvironmentInitializer instead
  1573. *
  1574. * @see {@link provideEnvironmentInitializer}
  1575. *
  1576. * Note: As opposed to the `APP_INITIALIZER` token, the `ENVIRONMENT_INITIALIZER` functions are not awaited,
  1577. * hence they should not be `async`.
  1578. *
  1579. * @publicApi
  1580. */
  1581. const ENVIRONMENT_INITIALIZER = new InjectionToken(ngDevMode ? 'ENVIRONMENT_INITIALIZER' : '');
  1582. /**
  1583. * An InjectionToken that gets the current `Injector` for `createInjector()`-style injectors.
  1584. *
  1585. * Requesting this token instead of `Injector` allows `StaticInjector` to be tree-shaken from a
  1586. * project.
  1587. *
  1588. * @publicApi
  1589. */
  1590. const INJECTOR$1 = new InjectionToken(ngDevMode ? 'INJECTOR' : '',
  1591. // Disable tslint because this is const enum which gets inlined not top level prop access.
  1592. // tslint:disable-next-line: no-toplevel-property-access
  1593. -1 /* InjectorMarkers.Injector */);
  1594. const INJECTOR_DEF_TYPES = new InjectionToken(ngDevMode ? 'INJECTOR_DEF_TYPES' : '');
  1595. class NullInjector {
  1596. get(token, notFoundValue = THROW_IF_NOT_FOUND) {
  1597. if (notFoundValue === THROW_IF_NOT_FOUND) {
  1598. const error = new Error(`NullInjectorError: No provider for ${stringify(token)}!`);
  1599. error.name = 'NullInjectorError';
  1600. throw error;
  1601. }
  1602. return notFoundValue;
  1603. }
  1604. }
  1605. function getNgModuleDef(type, throwNotFound) {
  1606. const ngModuleDef = type[NG_MOD_DEF] || null;
  1607. if (!ngModuleDef && throwNotFound === true) {
  1608. throw new Error(`Type ${stringify(type)} does not have 'ɵmod' property.`);
  1609. }
  1610. return ngModuleDef;
  1611. }
  1612. /**
  1613. * The following getter methods retrieve the definition from the type. Currently the retrieval
  1614. * honors inheritance, but in the future we may change the rule to require that definitions are
  1615. * explicit. This would require some sort of migration strategy.
  1616. */
  1617. function getComponentDef(type) {
  1618. return type[NG_COMP_DEF] || null;
  1619. }
  1620. function getDirectiveDef(type) {
  1621. return type[NG_DIR_DEF] || null;
  1622. }
  1623. function getPipeDef$1(type) {
  1624. return type[NG_PIPE_DEF] || null;
  1625. }
  1626. /**
  1627. * Checks whether a given Component, Directive or Pipe is marked as standalone.
  1628. * This will return false if passed anything other than a Component, Directive, or Pipe class
  1629. * See [this guide](guide/components/importing) for additional information:
  1630. *
  1631. * @param type A reference to a Component, Directive or Pipe.
  1632. * @publicApi
  1633. */
  1634. function isStandalone(type) {
  1635. const def = getComponentDef(type) || getDirectiveDef(type) || getPipeDef$1(type);
  1636. return def !== null && def.standalone;
  1637. }
  1638. /**
  1639. * Wrap an array of `Provider`s into `EnvironmentProviders`, preventing them from being accidentally
  1640. * referenced in `@Component` in a component injector.
  1641. *
  1642. * @publicApi
  1643. */
  1644. function makeEnvironmentProviders(providers) {
  1645. return {
  1646. ɵproviders: providers,
  1647. };
  1648. }
  1649. /**
  1650. * @description
  1651. * This function is used to provide initialization functions that will be executed upon construction
  1652. * of an environment injector.
  1653. *
  1654. * Note that the provided initializer is run in the injection context.
  1655. *
  1656. * Previously, this was achieved using the `ENVIRONMENT_INITIALIZER` token which is now deprecated.
  1657. *
  1658. * @see {@link ENVIRONMENT_INITIALIZER}
  1659. *
  1660. * @usageNotes
  1661. * The following example illustrates how to configure an initialization function using
  1662. * `provideEnvironmentInitializer()`
  1663. * ```ts
  1664. * createEnvironmentInjector(
  1665. * [
  1666. * provideEnvironmentInitializer(() => {
  1667. * console.log('environment initialized');
  1668. * }),
  1669. * ],
  1670. * parentInjector
  1671. * );
  1672. * ```
  1673. *
  1674. * @publicApi
  1675. */
  1676. function provideEnvironmentInitializer(initializerFn) {
  1677. return makeEnvironmentProviders([
  1678. {
  1679. provide: ENVIRONMENT_INITIALIZER,
  1680. multi: true,
  1681. useValue: initializerFn,
  1682. },
  1683. ]);
  1684. }
  1685. /**
  1686. * Collects providers from all NgModules and standalone components, including transitively imported
  1687. * ones.
  1688. *
  1689. * Providers extracted via `importProvidersFrom` are only usable in an application injector or
  1690. * another environment injector (such as a route injector). They should not be used in component
  1691. * providers.
  1692. *
  1693. * More information about standalone components can be found in [this
  1694. * guide](guide/components/importing).
  1695. *
  1696. * @usageNotes
  1697. * The results of the `importProvidersFrom` call can be used in the `bootstrapApplication` call:
  1698. *
  1699. * ```ts
  1700. * await bootstrapApplication(RootComponent, {
  1701. * providers: [
  1702. * importProvidersFrom(NgModuleOne, NgModuleTwo)
  1703. * ]
  1704. * });
  1705. * ```
  1706. *
  1707. * You can also use the `importProvidersFrom` results in the `providers` field of a route, when a
  1708. * standalone component is used:
  1709. *
  1710. * ```ts
  1711. * export const ROUTES: Route[] = [
  1712. * {
  1713. * path: 'foo',
  1714. * providers: [
  1715. * importProvidersFrom(NgModuleOne, NgModuleTwo)
  1716. * ],
  1717. * component: YourStandaloneComponent
  1718. * }
  1719. * ];
  1720. * ```
  1721. *
  1722. * @returns Collected providers from the specified list of types.
  1723. * @publicApi
  1724. */
  1725. function importProvidersFrom(...sources) {
  1726. return {
  1727. ɵproviders: internalImportProvidersFrom(true, sources),
  1728. ɵfromNgModule: true,
  1729. };
  1730. }
  1731. function internalImportProvidersFrom(checkForStandaloneCmp, ...sources) {
  1732. const providersOut = [];
  1733. const dedup = new Set(); // already seen types
  1734. let injectorTypesWithProviders;
  1735. const collectProviders = (provider) => {
  1736. providersOut.push(provider);
  1737. };
  1738. deepForEach(sources, (source) => {
  1739. if ((typeof ngDevMode === 'undefined' || ngDevMode) && checkForStandaloneCmp) {
  1740. const cmpDef = getComponentDef(source);
  1741. if (cmpDef?.standalone) {
  1742. throw new RuntimeError(800 /* RuntimeErrorCode.IMPORT_PROVIDERS_FROM_STANDALONE */, `Importing providers supports NgModule or ModuleWithProviders but got a standalone component "${stringifyForError(source)}"`);
  1743. }
  1744. }
  1745. // Narrow `source` to access the internal type analogue for `ModuleWithProviders`.
  1746. const internalSource = source;
  1747. if (walkProviderTree(internalSource, collectProviders, [], dedup)) {
  1748. injectorTypesWithProviders ||= [];
  1749. injectorTypesWithProviders.push(internalSource);
  1750. }
  1751. });
  1752. // Collect all providers from `ModuleWithProviders` types.
  1753. if (injectorTypesWithProviders !== undefined) {
  1754. processInjectorTypesWithProviders(injectorTypesWithProviders, collectProviders);
  1755. }
  1756. return providersOut;
  1757. }
  1758. /**
  1759. * Collects all providers from the list of `ModuleWithProviders` and appends them to the provided
  1760. * array.
  1761. */
  1762. function processInjectorTypesWithProviders(typesWithProviders, visitor) {
  1763. for (let i = 0; i < typesWithProviders.length; i++) {
  1764. const { ngModule, providers } = typesWithProviders[i];
  1765. deepForEachProvider(providers, (provider) => {
  1766. ngDevMode && validateProvider(provider, providers || EMPTY_ARRAY, ngModule);
  1767. visitor(provider, ngModule);
  1768. });
  1769. }
  1770. }
  1771. /**
  1772. * The logic visits an `InjectorType`, an `InjectorTypeWithProviders`, or a standalone
  1773. * `ComponentType`, and all of its transitive providers and collects providers.
  1774. *
  1775. * If an `InjectorTypeWithProviders` that declares providers besides the type is specified,
  1776. * the function will return "true" to indicate that the providers of the type definition need
  1777. * to be processed. This allows us to process providers of injector types after all imports of
  1778. * an injector definition are processed. (following View Engine semantics: see FW-1349)
  1779. */
  1780. function walkProviderTree(container, visitor, parents, dedup) {
  1781. container = resolveForwardRef(container);
  1782. if (!container)
  1783. return false;
  1784. // The actual type which had the definition. Usually `container`, but may be an unwrapped type
  1785. // from `InjectorTypeWithProviders`.
  1786. let defType = null;
  1787. let injDef = getInjectorDef(container);
  1788. const cmpDef = !injDef && getComponentDef(container);
  1789. if (!injDef && !cmpDef) {
  1790. // `container` is not an injector type or a component type. It might be:
  1791. // * An `InjectorTypeWithProviders` that wraps an injector type.
  1792. // * A standalone directive or pipe that got pulled in from a standalone component's
  1793. // dependencies.
  1794. // Try to unwrap it as an `InjectorTypeWithProviders` first.
  1795. const ngModule = container
  1796. .ngModule;
  1797. injDef = getInjectorDef(ngModule);
  1798. if (injDef) {
  1799. defType = ngModule;
  1800. }
  1801. else {
  1802. // Not a component or injector type, so ignore it.
  1803. return false;
  1804. }
  1805. }
  1806. else if (cmpDef && !cmpDef.standalone) {
  1807. return false;
  1808. }
  1809. else {
  1810. defType = container;
  1811. }
  1812. // Check for circular dependencies.
  1813. if (ngDevMode && parents.indexOf(defType) !== -1) {
  1814. const defName = stringify(defType);
  1815. const path = parents.map(stringify);
  1816. throwCyclicDependencyError(defName, path);
  1817. }
  1818. // Check for multiple imports of the same module
  1819. const isDuplicate = dedup.has(defType);
  1820. if (cmpDef) {
  1821. if (isDuplicate) {
  1822. // This component definition has already been processed.
  1823. return false;
  1824. }
  1825. dedup.add(defType);
  1826. if (cmpDef.dependencies) {
  1827. const deps = typeof cmpDef.dependencies === 'function' ? cmpDef.dependencies() : cmpDef.dependencies;
  1828. for (const dep of deps) {
  1829. walkProviderTree(dep, visitor, parents, dedup);
  1830. }
  1831. }
  1832. }
  1833. else if (injDef) {
  1834. // First, include providers from any imports.
  1835. if (injDef.imports != null && !isDuplicate) {
  1836. // Before processing defType's imports, add it to the set of parents. This way, if it ends
  1837. // up deeply importing itself, this can be detected.
  1838. ngDevMode && parents.push(defType);
  1839. // Add it to the set of dedups. This way we can detect multiple imports of the same module
  1840. dedup.add(defType);
  1841. let importTypesWithProviders;
  1842. try {
  1843. deepForEach(injDef.imports, (imported) => {
  1844. if (walkProviderTree(imported, visitor, parents, dedup)) {
  1845. importTypesWithProviders ||= [];
  1846. // If the processed import is an injector type with providers, we store it in the
  1847. // list of import types with providers, so that we can process those afterwards.
  1848. importTypesWithProviders.push(imported);
  1849. }
  1850. });
  1851. }
  1852. finally {
  1853. // Remove it from the parents set when finished.
  1854. ngDevMode && parents.pop();
  1855. }
  1856. // Imports which are declared with providers (TypeWithProviders) need to be processed
  1857. // after all imported modules are processed. This is similar to how View Engine
  1858. // processes/merges module imports in the metadata resolver. See: FW-1349.
  1859. if (importTypesWithProviders !== undefined) {
  1860. processInjectorTypesWithProviders(importTypesWithProviders, visitor);
  1861. }
  1862. }
  1863. if (!isDuplicate) {
  1864. // Track the InjectorType and add a provider for it.
  1865. // It's important that this is done after the def's imports.
  1866. const factory = getFactoryDef(defType) || (() => new defType());
  1867. // Append extra providers to make more info available for consumers (to retrieve an injector
  1868. // type), as well as internally (to calculate an injection scope correctly and eagerly
  1869. // instantiate a `defType` when an injector is created).
  1870. // Provider to create `defType` using its factory.
  1871. visitor({ provide: defType, useFactory: factory, deps: EMPTY_ARRAY }, defType);
  1872. // Make this `defType` available to an internal logic that calculates injector scope.
  1873. visitor({ provide: INJECTOR_DEF_TYPES, useValue: defType, multi: true }, defType);
  1874. // Provider to eagerly instantiate `defType` via `INJECTOR_INITIALIZER`.
  1875. visitor({ provide: ENVIRONMENT_INITIALIZER, useValue: () => ɵɵinject(defType), multi: true }, defType);
  1876. }
  1877. // Next, include providers listed on the definition itself.
  1878. const defProviders = injDef.providers;
  1879. if (defProviders != null && !isDuplicate) {
  1880. const injectorType = container;
  1881. deepForEachProvider(defProviders, (provider) => {
  1882. ngDevMode && validateProvider(provider, defProviders, injectorType);
  1883. visitor(provider, injectorType);
  1884. });
  1885. }
  1886. }
  1887. else {
  1888. // Should not happen, but just in case.
  1889. return false;
  1890. }
  1891. return (defType !== container && container.providers !== undefined);
  1892. }
  1893. function validateProvider(provider, providers, containerType) {
  1894. if (isTypeProvider(provider) ||
  1895. isValueProvider(provider) ||
  1896. isFactoryProvider(provider) ||
  1897. isExistingProvider(provider)) {
  1898. return;
  1899. }
  1900. // Here we expect the provider to be a `useClass` provider (by elimination).
  1901. const classRef = resolveForwardRef(provider && (provider.useClass || provider.provide));
  1902. if (!classRef) {
  1903. throwInvalidProviderError(containerType, providers, provider);
  1904. }
  1905. }
  1906. function deepForEachProvider(providers, fn) {
  1907. for (let provider of providers) {
  1908. if (isEnvironmentProviders(provider)) {
  1909. provider = provider.ɵproviders;
  1910. }
  1911. if (Array.isArray(provider)) {
  1912. deepForEachProvider(provider, fn);
  1913. }
  1914. else {
  1915. fn(provider);
  1916. }
  1917. }
  1918. }
  1919. const USE_VALUE$1 = getClosureSafeProperty({
  1920. provide: String,
  1921. useValue: getClosureSafeProperty,
  1922. });
  1923. function isValueProvider(value) {
  1924. return value !== null && typeof value == 'object' && USE_VALUE$1 in value;
  1925. }
  1926. function isExistingProvider(value) {
  1927. return !!(value && value.useExisting);
  1928. }
  1929. function isFactoryProvider(value) {
  1930. return !!(value && value.useFactory);
  1931. }
  1932. function isTypeProvider(value) {
  1933. return typeof value === 'function';
  1934. }
  1935. function isClassProvider(value) {
  1936. return !!value.useClass;
  1937. }
  1938. /**
  1939. * An internal token whose presence in an injector indicates that the injector should treat itself
  1940. * as a root scoped injector when processing requests for unknown tokens which may indicate
  1941. * they are provided in the root scope.
  1942. */
  1943. const INJECTOR_SCOPE = new InjectionToken(ngDevMode ? 'Set Injector scope.' : '');
  1944. /**
  1945. * Marker which indicates that a value has not yet been created from the factory function.
  1946. */
  1947. const NOT_YET = {};
  1948. /**
  1949. * Marker which indicates that the factory function for a token is in the process of being called.
  1950. *
  1951. * If the injector is asked to inject a token with its value set to CIRCULAR, that indicates
  1952. * injection of a dependency has recursively attempted to inject the original token, and there is
  1953. * a circular dependency among the providers.
  1954. */
  1955. const CIRCULAR = {};
  1956. /**
  1957. * A lazily initialized NullInjector.
  1958. */
  1959. let NULL_INJECTOR = undefined;
  1960. function getNullInjector() {
  1961. if (NULL_INJECTOR === undefined) {
  1962. NULL_INJECTOR = new NullInjector();
  1963. }
  1964. return NULL_INJECTOR;
  1965. }
  1966. /**
  1967. * An `Injector` that's part of the environment injector hierarchy, which exists outside of the
  1968. * component tree.
  1969. */
  1970. class EnvironmentInjector {
  1971. }
  1972. class R3Injector extends EnvironmentInjector {
  1973. parent;
  1974. source;
  1975. scopes;
  1976. /**
  1977. * Map of tokens to records which contain the instances of those tokens.
  1978. * - `null` value implies that we don't have the record. Used by tree-shakable injectors
  1979. * to prevent further searches.
  1980. */
  1981. records = new Map();
  1982. /**
  1983. * Set of values instantiated by this injector which contain `ngOnDestroy` lifecycle hooks.
  1984. */
  1985. _ngOnDestroyHooks = new Set();
  1986. _onDestroyHooks = [];
  1987. /**
  1988. * Flag indicating that this injector was previously destroyed.
  1989. */
  1990. get destroyed() {
  1991. return this._destroyed;
  1992. }
  1993. _destroyed = false;
  1994. injectorDefTypes;
  1995. constructor(providers, parent, source, scopes) {
  1996. super();
  1997. this.parent = parent;
  1998. this.source = source;
  1999. this.scopes = scopes;
  2000. // Start off by creating Records for every provider.
  2001. forEachSingleProvider(providers, (provider) => this.processProvider(provider));
  2002. // Make sure the INJECTOR token provides this injector.
  2003. this.records.set(INJECTOR$1, makeRecord(undefined, this));
  2004. // And `EnvironmentInjector` if the current injector is supposed to be env-scoped.
  2005. if (scopes.has('environment')) {
  2006. this.records.set(EnvironmentInjector, makeRecord(undefined, this));
  2007. }
  2008. // Detect whether this injector has the APP_ROOT_SCOPE token and thus should provide
  2009. // any injectable scoped to APP_ROOT_SCOPE.
  2010. const record = this.records.get(INJECTOR_SCOPE);
  2011. if (record != null && typeof record.value === 'string') {
  2012. this.scopes.add(record.value);
  2013. }
  2014. this.injectorDefTypes = new Set(this.get(INJECTOR_DEF_TYPES, EMPTY_ARRAY, InjectFlags.Self));
  2015. }
  2016. retrieve(token, options) {
  2017. const ngOptions = options;
  2018. return this.get(token, ngOptions.optional ? NOT_FOUND$2 : THROW_IF_NOT_FOUND, ngOptions);
  2019. }
  2020. /**
  2021. * Destroy the injector and release references to every instance or provider associated with it.
  2022. *
  2023. * Also calls the `OnDestroy` lifecycle hooks of every instance that was created for which a
  2024. * hook was found.
  2025. */
  2026. destroy() {
  2027. assertNotDestroyed(this);
  2028. // Set destroyed = true first, in case lifecycle hooks re-enter destroy().
  2029. this._destroyed = true;
  2030. const prevConsumer = setActiveConsumer(null);
  2031. try {
  2032. // Call all the lifecycle hooks.
  2033. for (const service of this._ngOnDestroyHooks) {
  2034. service.ngOnDestroy();
  2035. }
  2036. const onDestroyHooks = this._onDestroyHooks;
  2037. // Reset the _onDestroyHooks array before iterating over it to prevent hooks that unregister
  2038. // themselves from mutating the array during iteration.
  2039. this._onDestroyHooks = [];
  2040. for (const hook of onDestroyHooks) {
  2041. hook();
  2042. }
  2043. }
  2044. finally {
  2045. // Release all references.
  2046. this.records.clear();
  2047. this._ngOnDestroyHooks.clear();
  2048. this.injectorDefTypes.clear();
  2049. setActiveConsumer(prevConsumer);
  2050. }
  2051. }
  2052. onDestroy(callback) {
  2053. assertNotDestroyed(this);
  2054. this._onDestroyHooks.push(callback);
  2055. return () => this.removeOnDestroy(callback);
  2056. }
  2057. runInContext(fn) {
  2058. assertNotDestroyed(this);
  2059. const previousInjector = setCurrentInjector(this);
  2060. const previousInjectImplementation = setInjectImplementation(undefined);
  2061. let prevInjectContext;
  2062. if (ngDevMode) {
  2063. prevInjectContext = setInjectorProfilerContext({ injector: this, token: null });
  2064. }
  2065. try {
  2066. return fn();
  2067. }
  2068. finally {
  2069. setCurrentInjector(previousInjector);
  2070. setInjectImplementation(previousInjectImplementation);
  2071. ngDevMode && setInjectorProfilerContext(prevInjectContext);
  2072. }
  2073. }
  2074. get(token, notFoundValue = THROW_IF_NOT_FOUND, flags = InjectFlags.Default) {
  2075. assertNotDestroyed(this);
  2076. if (token.hasOwnProperty(NG_ENV_ID)) {
  2077. return token[NG_ENV_ID](this);
  2078. }
  2079. flags = convertToBitFlags(flags);
  2080. // Set the injection context.
  2081. let prevInjectContext;
  2082. if (ngDevMode) {
  2083. prevInjectContext = setInjectorProfilerContext({ injector: this, token: token });
  2084. }
  2085. const previousInjector = setCurrentInjector(this);
  2086. const previousInjectImplementation = setInjectImplementation(undefined);
  2087. try {
  2088. // Check for the SkipSelf flag.
  2089. if (!(flags & InjectFlags.SkipSelf)) {
  2090. // SkipSelf isn't set, check if the record belongs to this injector.
  2091. let record = this.records.get(token);
  2092. if (record === undefined) {
  2093. // No record, but maybe the token is scoped to this injector. Look for an injectable
  2094. // def with a scope matching this injector.
  2095. const def = couldBeInjectableType(token) && getInjectableDef(token);
  2096. if (def && this.injectableDefInScope(def)) {
  2097. // Found an injectable def and it's scoped to this injector. Pretend as if it was here
  2098. // all along.
  2099. if (ngDevMode) {
  2100. runInInjectorProfilerContext(this, token, () => {
  2101. emitProviderConfiguredEvent(token);
  2102. });
  2103. }
  2104. record = makeRecord(injectableDefOrInjectorDefFactory(token), NOT_YET);
  2105. }
  2106. else {
  2107. record = null;
  2108. }
  2109. this.records.set(token, record);
  2110. }
  2111. // If a record was found, get the instance for it and return it.
  2112. if (record != null /* NOT null || undefined */) {
  2113. return this.hydrate(token, record, flags);
  2114. }
  2115. }
  2116. // Select the next injector based on the Self flag - if self is set, the next injector is
  2117. // the NullInjector, otherwise it's the parent.
  2118. const nextInjector = !(flags & InjectFlags.Self) ? this.parent : getNullInjector();
  2119. // Set the notFoundValue based on the Optional flag - if optional is set and notFoundValue
  2120. // is undefined, the value is null, otherwise it's the notFoundValue.
  2121. notFoundValue =
  2122. flags & InjectFlags.Optional && notFoundValue === THROW_IF_NOT_FOUND ? null : notFoundValue;
  2123. return nextInjector.get(token, notFoundValue);
  2124. }
  2125. catch (e) {
  2126. if (e.name === 'NullInjectorError') {
  2127. const path = (e[NG_TEMP_TOKEN_PATH] = e[NG_TEMP_TOKEN_PATH] || []);
  2128. path.unshift(stringify(token));
  2129. if (previousInjector) {
  2130. // We still have a parent injector, keep throwing
  2131. throw e;
  2132. }
  2133. else {
  2134. // Format & throw the final error message when we don't have any previous injector
  2135. return catchInjectorError(e, token, 'R3InjectorError', this.source);
  2136. }
  2137. }
  2138. else {
  2139. throw e;
  2140. }
  2141. }
  2142. finally {
  2143. // Lastly, restore the previous injection context.
  2144. setInjectImplementation(previousInjectImplementation);
  2145. setCurrentInjector(previousInjector);
  2146. ngDevMode && setInjectorProfilerContext(prevInjectContext);
  2147. }
  2148. }
  2149. /** @internal */
  2150. resolveInjectorInitializers() {
  2151. const prevConsumer = setActiveConsumer(null);
  2152. const previousInjector = setCurrentInjector(this);
  2153. const previousInjectImplementation = setInjectImplementation(undefined);
  2154. let prevInjectContext;
  2155. if (ngDevMode) {
  2156. prevInjectContext = setInjectorProfilerContext({ injector: this, token: null });
  2157. }
  2158. try {
  2159. const initializers = this.get(ENVIRONMENT_INITIALIZER, EMPTY_ARRAY, InjectFlags.Self);
  2160. if (ngDevMode && !Array.isArray(initializers)) {
  2161. throw new RuntimeError(-209 /* RuntimeErrorCode.INVALID_MULTI_PROVIDER */, 'Unexpected type of the `ENVIRONMENT_INITIALIZER` token value ' +
  2162. `(expected an array, but got ${typeof initializers}). ` +
  2163. 'Please check that the `ENVIRONMENT_INITIALIZER` token is configured as a ' +
  2164. '`multi: true` provider.');
  2165. }
  2166. for (const initializer of initializers) {
  2167. initializer();
  2168. }
  2169. }
  2170. finally {
  2171. setCurrentInjector(previousInjector);
  2172. setInjectImplementation(previousInjectImplementation);
  2173. ngDevMode && setInjectorProfilerContext(prevInjectContext);
  2174. setActiveConsumer(prevConsumer);
  2175. }
  2176. }
  2177. toString() {
  2178. const tokens = [];
  2179. const records = this.records;
  2180. for (const token of records.keys()) {
  2181. tokens.push(stringify(token));
  2182. }
  2183. return `R3Injector[${tokens.join(', ')}]`;
  2184. }
  2185. /**
  2186. * Process a `SingleProvider` and add it.
  2187. */
  2188. processProvider(provider) {
  2189. // Determine the token from the provider. Either it's its own token, or has a {provide: ...}
  2190. // property.
  2191. provider = resolveForwardRef(provider);
  2192. let token = isTypeProvider(provider)
  2193. ? provider
  2194. : resolveForwardRef(provider && provider.provide);
  2195. // Construct a `Record` for the provider.
  2196. const record = providerToRecord(provider);
  2197. if (ngDevMode) {
  2198. runInInjectorProfilerContext(this, token, () => {
  2199. // Emit InjectorProfilerEventType.Create if provider is a value provider because
  2200. // these are the only providers that do not go through the value hydration logic
  2201. // where this event would normally be emitted from.
  2202. if (isValueProvider(provider)) {
  2203. emitInstanceCreatedByInjectorEvent(provider.useValue);
  2204. }
  2205. emitProviderConfiguredEvent(provider);
  2206. });
  2207. }
  2208. if (!isTypeProvider(provider) && provider.multi === true) {
  2209. // If the provider indicates that it's a multi-provider, process it specially.
  2210. // First check whether it's been defined already.
  2211. let multiRecord = this.records.get(token);
  2212. if (multiRecord) {
  2213. // It has. Throw a nice error if
  2214. if (ngDevMode && multiRecord.multi === undefined) {
  2215. throwMixedMultiProviderError();
  2216. }
  2217. }
  2218. else {
  2219. multiRecord = makeRecord(undefined, NOT_YET, true);
  2220. multiRecord.factory = () => injectArgs(multiRecord.multi);
  2221. this.records.set(token, multiRecord);
  2222. }
  2223. token = provider;
  2224. multiRecord.multi.push(provider);
  2225. }
  2226. else {
  2227. if (ngDevMode) {
  2228. const existing = this.records.get(token);
  2229. if (existing && existing.multi !== undefined) {
  2230. throwMixedMultiProviderError();
  2231. }
  2232. }
  2233. }
  2234. this.records.set(token, record);
  2235. }
  2236. hydrate(token, record, flags) {
  2237. const prevConsumer = setActiveConsumer(null);
  2238. try {
  2239. if (record.value === CIRCULAR) {
  2240. throwCyclicDependencyError(stringify(token));
  2241. }
  2242. else if (record.value === NOT_YET) {
  2243. record.value = CIRCULAR;
  2244. if (ngDevMode) {
  2245. runInInjectorProfilerContext(this, token, () => {
  2246. record.value = record.factory(undefined, flags);
  2247. emitInstanceCreatedByInjectorEvent(record.value);
  2248. });
  2249. }
  2250. else {
  2251. record.value = record.factory(undefined, flags);
  2252. }
  2253. }
  2254. if (typeof record.value === 'object' && record.value && hasOnDestroy(record.value)) {
  2255. this._ngOnDestroyHooks.add(record.value);
  2256. }
  2257. return record.value;
  2258. }
  2259. finally {
  2260. setActiveConsumer(prevConsumer);
  2261. }
  2262. }
  2263. injectableDefInScope(def) {
  2264. if (!def.providedIn) {
  2265. return false;
  2266. }
  2267. const providedIn = resolveForwardRef(def.providedIn);
  2268. if (typeof providedIn === 'string') {
  2269. return providedIn === 'any' || this.scopes.has(providedIn);
  2270. }
  2271. else {
  2272. return this.injectorDefTypes.has(providedIn);
  2273. }
  2274. }
  2275. removeOnDestroy(callback) {
  2276. const destroyCBIdx = this._onDestroyHooks.indexOf(callback);
  2277. if (destroyCBIdx !== -1) {
  2278. this._onDestroyHooks.splice(destroyCBIdx, 1);
  2279. }
  2280. }
  2281. }
  2282. function injectableDefOrInjectorDefFactory(token) {
  2283. // Most tokens will have an injectable def directly on them, which specifies a factory directly.
  2284. const injectableDef = getInjectableDef(token);
  2285. const factory = injectableDef !== null ? injectableDef.factory : getFactoryDef(token);
  2286. if (factory !== null) {
  2287. return factory;
  2288. }
  2289. // InjectionTokens should have an injectable def (ɵprov) and thus should be handled above.
  2290. // If it's missing that, it's an error.
  2291. if (token instanceof InjectionToken) {
  2292. throw new RuntimeError(204 /* RuntimeErrorCode.INVALID_INJECTION_TOKEN */, ngDevMode && `Token ${stringify(token)} is missing a ɵprov definition.`);
  2293. }
  2294. // Undecorated types can sometimes be created if they have no constructor arguments.
  2295. if (token instanceof Function) {
  2296. return getUndecoratedInjectableFactory(token);
  2297. }
  2298. // There was no way to resolve a factory for this token.
  2299. throw new RuntimeError(204 /* RuntimeErrorCode.INVALID_INJECTION_TOKEN */, ngDevMode && 'unreachable');
  2300. }
  2301. function getUndecoratedInjectableFactory(token) {
  2302. // If the token has parameters then it has dependencies that we cannot resolve implicitly.
  2303. const paramLength = token.length;
  2304. if (paramLength > 0) {
  2305. throw new RuntimeError(204 /* RuntimeErrorCode.INVALID_INJECTION_TOKEN */, ngDevMode &&
  2306. `Can't resolve all parameters for ${stringify(token)}: (${newArray(paramLength, '?').join(', ')}).`);
  2307. }
  2308. // The constructor function appears to have no parameters.
  2309. // This might be because it inherits from a super-class. In which case, use an injectable
  2310. // def from an ancestor if there is one.
  2311. // Otherwise this really is a simple class with no dependencies, so return a factory that
  2312. // just instantiates the zero-arg constructor.
  2313. const inheritedInjectableDef = getInheritedInjectableDef(token);
  2314. if (inheritedInjectableDef !== null) {
  2315. return () => inheritedInjectableDef.factory(token);
  2316. }
  2317. else {
  2318. return () => new token();
  2319. }
  2320. }
  2321. function providerToRecord(provider) {
  2322. if (isValueProvider(provider)) {
  2323. return makeRecord(undefined, provider.useValue);
  2324. }
  2325. else {
  2326. const factory = providerToFactory(provider);
  2327. return makeRecord(factory, NOT_YET);
  2328. }
  2329. }
  2330. /**
  2331. * Converts a `SingleProvider` into a factory function.
  2332. *
  2333. * @param provider provider to convert to factory
  2334. */
  2335. function providerToFactory(provider, ngModuleType, providers) {
  2336. let factory = undefined;
  2337. if (ngDevMode && isEnvironmentProviders(provider)) {
  2338. throwInvalidProviderError(undefined, providers, provider);
  2339. }
  2340. if (isTypeProvider(provider)) {
  2341. const unwrappedProvider = resolveForwardRef(provider);
  2342. return getFactoryDef(unwrappedProvider) || injectableDefOrInjectorDefFactory(unwrappedProvider);
  2343. }
  2344. else {
  2345. if (isValueProvider(provider)) {
  2346. factory = () => resolveForwardRef(provider.useValue);
  2347. }
  2348. else if (isFactoryProvider(provider)) {
  2349. factory = () => provider.useFactory(...injectArgs(provider.deps || []));
  2350. }
  2351. else if (isExistingProvider(provider)) {
  2352. factory = (_, flags) => ɵɵinject(resolveForwardRef(provider.useExisting), flags !== undefined && flags & InjectFlags.Optional ? InjectFlags.Optional : undefined);
  2353. }
  2354. else {
  2355. const classRef = resolveForwardRef(provider &&
  2356. (provider.useClass || provider.provide));
  2357. if (ngDevMode && !classRef) {
  2358. throwInvalidProviderError(ngModuleType, providers, provider);
  2359. }
  2360. if (hasDeps(provider)) {
  2361. factory = () => new classRef(...injectArgs(provider.deps));
  2362. }
  2363. else {
  2364. return getFactoryDef(classRef) || injectableDefOrInjectorDefFactory(classRef);
  2365. }
  2366. }
  2367. }
  2368. return factory;
  2369. }
  2370. function assertNotDestroyed(injector) {
  2371. if (injector.destroyed) {
  2372. throw new RuntimeError(205 /* RuntimeErrorCode.INJECTOR_ALREADY_DESTROYED */, ngDevMode && 'Injector has already been destroyed.');
  2373. }
  2374. }
  2375. function makeRecord(factory, value, multi = false) {
  2376. return {
  2377. factory: factory,
  2378. value: value,
  2379. multi: multi ? [] : undefined,
  2380. };
  2381. }
  2382. function hasDeps(value) {
  2383. return !!value.deps;
  2384. }
  2385. function hasOnDestroy(value) {
  2386. return (value !== null &&
  2387. typeof value === 'object' &&
  2388. typeof value.ngOnDestroy === 'function');
  2389. }
  2390. function couldBeInjectableType(value) {
  2391. return (typeof value === 'function' || (typeof value === 'object' && value instanceof InjectionToken));
  2392. }
  2393. function forEachSingleProvider(providers, fn) {
  2394. for (const provider of providers) {
  2395. if (Array.isArray(provider)) {
  2396. forEachSingleProvider(provider, fn);
  2397. }
  2398. else if (provider && isEnvironmentProviders(provider)) {
  2399. forEachSingleProvider(provider.ɵproviders, fn);
  2400. }
  2401. else {
  2402. fn(provider);
  2403. }
  2404. }
  2405. }
  2406. /**
  2407. * Runs the given function in the [context](guide/di/dependency-injection-context) of the given
  2408. * `Injector`.
  2409. *
  2410. * Within the function's stack frame, [`inject`](api/core/inject) can be used to inject dependencies
  2411. * from the given `Injector`. Note that `inject` is only usable synchronously, and cannot be used in
  2412. * any asynchronous callbacks or after any `await` points.
  2413. *
  2414. * @param injector the injector which will satisfy calls to [`inject`](api/core/inject) while `fn`
  2415. * is executing
  2416. * @param fn the closure to be run in the context of `injector`
  2417. * @returns the return value of the function, if any
  2418. * @publicApi
  2419. */
  2420. function runInInjectionContext(injector, fn) {
  2421. let internalInjector;
  2422. if (injector instanceof R3Injector) {
  2423. assertNotDestroyed(injector);
  2424. internalInjector = injector;
  2425. }
  2426. else {
  2427. internalInjector = new RetrievingInjector(injector);
  2428. }
  2429. let prevInjectorProfilerContext;
  2430. if (ngDevMode) {
  2431. prevInjectorProfilerContext = setInjectorProfilerContext({ injector, token: null });
  2432. }
  2433. const prevInjector = setCurrentInjector(internalInjector);
  2434. const previousInjectImplementation = setInjectImplementation(undefined);
  2435. try {
  2436. return fn();
  2437. }
  2438. finally {
  2439. setCurrentInjector(prevInjector);
  2440. ngDevMode && setInjectorProfilerContext(prevInjectorProfilerContext);
  2441. setInjectImplementation(previousInjectImplementation);
  2442. }
  2443. }
  2444. /**
  2445. * Whether the current stack frame is inside an injection context.
  2446. */
  2447. function isInInjectionContext() {
  2448. return getInjectImplementation() !== undefined || getCurrentInjector() != null;
  2449. }
  2450. /**
  2451. * Asserts that the current stack frame is within an [injection
  2452. * context](guide/di/dependency-injection-context) and has access to `inject`.
  2453. *
  2454. * @param debugFn a reference to the function making the assertion (used for the error message).
  2455. *
  2456. * @publicApi
  2457. */
  2458. function assertInInjectionContext(debugFn) {
  2459. // Taking a `Function` instead of a string name here prevents the unminified name of the function
  2460. // from being retained in the bundle regardless of minification.
  2461. if (!isInInjectionContext()) {
  2462. throw new RuntimeError(-203 /* RuntimeErrorCode.MISSING_INJECTION_CONTEXT */, ngDevMode &&
  2463. debugFn.name +
  2464. '() can only be used within an injection context such as a constructor, a factory function, a field initializer, or a function used with `runInInjectionContext`');
  2465. }
  2466. }
  2467. var FactoryTarget;
  2468. (function (FactoryTarget) {
  2469. FactoryTarget[FactoryTarget["Directive"] = 0] = "Directive";
  2470. FactoryTarget[FactoryTarget["Component"] = 1] = "Component";
  2471. FactoryTarget[FactoryTarget["Injectable"] = 2] = "Injectable";
  2472. FactoryTarget[FactoryTarget["Pipe"] = 3] = "Pipe";
  2473. FactoryTarget[FactoryTarget["NgModule"] = 4] = "NgModule";
  2474. })(FactoryTarget || (FactoryTarget = {}));
  2475. var R3TemplateDependencyKind;
  2476. (function (R3TemplateDependencyKind) {
  2477. R3TemplateDependencyKind[R3TemplateDependencyKind["Directive"] = 0] = "Directive";
  2478. R3TemplateDependencyKind[R3TemplateDependencyKind["Pipe"] = 1] = "Pipe";
  2479. R3TemplateDependencyKind[R3TemplateDependencyKind["NgModule"] = 2] = "NgModule";
  2480. })(R3TemplateDependencyKind || (R3TemplateDependencyKind = {}));
  2481. var ViewEncapsulation$1;
  2482. (function (ViewEncapsulation) {
  2483. ViewEncapsulation[ViewEncapsulation["Emulated"] = 0] = "Emulated";
  2484. // Historically the 1 value was for `Native` encapsulation which has been removed as of v11.
  2485. ViewEncapsulation[ViewEncapsulation["None"] = 2] = "None";
  2486. ViewEncapsulation[ViewEncapsulation["ShadowDom"] = 3] = "ShadowDom";
  2487. })(ViewEncapsulation$1 || (ViewEncapsulation$1 = {}));
  2488. function getCompilerFacade(request) {
  2489. const globalNg = _global['ng'];
  2490. if (globalNg && globalNg.ɵcompilerFacade) {
  2491. return globalNg.ɵcompilerFacade;
  2492. }
  2493. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  2494. // Log the type as an error so that a developer can easily navigate to the type from the
  2495. // console.
  2496. console.error(`JIT compilation failed for ${request.kind}`, request.type);
  2497. let message = `The ${request.kind} '${request.type.name}' needs to be compiled using the JIT compiler, but '@angular/compiler' is not available.\n\n`;
  2498. if (request.usage === 1 /* JitCompilerUsage.PartialDeclaration */) {
  2499. message += `The ${request.kind} is part of a library that has been partially compiled.\n`;
  2500. message += `However, the Angular Linker has not processed the library such that JIT compilation is used as fallback.\n`;
  2501. message += '\n';
  2502. message += `Ideally, the library is processed using the Angular Linker to become fully AOT compiled.\n`;
  2503. }
  2504. else {
  2505. message += `JIT compilation is discouraged for production use-cases! Consider using AOT mode instead.\n`;
  2506. }
  2507. message += `Alternatively, the JIT compiler should be loaded by bootstrapping using '@angular/platform-browser-dynamic' or '@angular/platform-server',\n`;
  2508. message += `or manually provide the compiler with 'import "@angular/compiler";' before bootstrapping.`;
  2509. throw new Error(message);
  2510. }
  2511. else {
  2512. throw new Error('JIT compiler unavailable');
  2513. }
  2514. }
  2515. /**
  2516. * A mapping of the @angular/core API surface used in generated expressions to the actual symbols.
  2517. *
  2518. * This should be kept up to date with the public exports of @angular/core.
  2519. */
  2520. const angularCoreDiEnv = {
  2521. 'ɵɵdefineInjectable': ɵɵdefineInjectable,
  2522. 'ɵɵdefineInjector': ɵɵdefineInjector,
  2523. 'ɵɵinject': ɵɵinject,
  2524. 'ɵɵinvalidFactoryDep': ɵɵinvalidFactoryDep,
  2525. 'resolveForwardRef': resolveForwardRef,
  2526. };
  2527. /**
  2528. * @description
  2529. *
  2530. * Represents a type that a Component or other object is instances of.
  2531. *
  2532. * An example of a `Type` is `MyCustomComponent` class, which in JavaScript is represented by
  2533. * the `MyCustomComponent` constructor function.
  2534. *
  2535. * @publicApi
  2536. */
  2537. const Type = Function;
  2538. function isType(v) {
  2539. return typeof v === 'function';
  2540. }
  2541. /*
  2542. * #########################
  2543. * Attention: These Regular expressions have to hold even if the code is minified!
  2544. * ##########################
  2545. */
  2546. /**
  2547. * Regular expression that detects pass-through constructors for ES5 output. This Regex
  2548. * intends to capture the common delegation pattern emitted by TypeScript and Babel. Also
  2549. * it intends to capture the pattern where existing constructors have been downleveled from
  2550. * ES2015 to ES5 using TypeScript w/ downlevel iteration. e.g.
  2551. *
  2552. * ```ts
  2553. * function MyClass() {
  2554. * var _this = _super.apply(this, arguments) || this;
  2555. * ```
  2556. *
  2557. * downleveled to ES5 with `downlevelIteration` for TypeScript < 4.2:
  2558. * ```ts
  2559. * function MyClass() {
  2560. * var _this = _super.apply(this, __spread(arguments)) || this;
  2561. * ```
  2562. *
  2563. * or downleveled to ES5 with `downlevelIteration` for TypeScript >= 4.2:
  2564. * ```ts
  2565. * function MyClass() {
  2566. * var _this = _super.apply(this, __spreadArray([], __read(arguments), false)) || this;
  2567. * ```
  2568. *
  2569. * More details can be found in: https://github.com/angular/angular/issues/38453.
  2570. */
  2571. const ES5_DELEGATE_CTOR = /^function\s+\S+\(\)\s*{[\s\S]+\.apply\(this,\s*(arguments|(?:[^()]+\(\[\],)?[^()]+\(arguments\).*)\)/;
  2572. /** Regular expression that detects ES2015 classes which extend from other classes. */
  2573. const ES2015_INHERITED_CLASS = /^class\s+[A-Za-z\d$_]*\s*extends\s+[^{]+{/;
  2574. /**
  2575. * Regular expression that detects ES2015 classes which extend from other classes and
  2576. * have an explicit constructor defined.
  2577. */
  2578. const ES2015_INHERITED_CLASS_WITH_CTOR = /^class\s+[A-Za-z\d$_]*\s*extends\s+[^{]+{[\s\S]*constructor\s*\(/;
  2579. /**
  2580. * Regular expression that detects ES2015 classes which extend from other classes
  2581. * and inherit a constructor.
  2582. */
  2583. const ES2015_INHERITED_CLASS_WITH_DELEGATE_CTOR = /^class\s+[A-Za-z\d$_]*\s*extends\s+[^{]+{[\s\S]*constructor\s*\(\)\s*{[^}]*super\(\.\.\.arguments\)/;
  2584. /**
  2585. * Determine whether a stringified type is a class which delegates its constructor
  2586. * to its parent.
  2587. *
  2588. * This is not trivial since compiled code can actually contain a constructor function
  2589. * even if the original source code did not. For instance, when the child class contains
  2590. * an initialized instance property.
  2591. */
  2592. function isDelegateCtor(typeStr) {
  2593. return (ES5_DELEGATE_CTOR.test(typeStr) ||
  2594. ES2015_INHERITED_CLASS_WITH_DELEGATE_CTOR.test(typeStr) ||
  2595. (ES2015_INHERITED_CLASS.test(typeStr) && !ES2015_INHERITED_CLASS_WITH_CTOR.test(typeStr)));
  2596. }
  2597. class ReflectionCapabilities {
  2598. _reflect;
  2599. constructor(reflect) {
  2600. this._reflect = reflect || _global['Reflect'];
  2601. }
  2602. factory(t) {
  2603. return (...args) => new t(...args);
  2604. }
  2605. /** @internal */
  2606. _zipTypesAndAnnotations(paramTypes, paramAnnotations) {
  2607. let result;
  2608. if (typeof paramTypes === 'undefined') {
  2609. result = newArray(paramAnnotations.length);
  2610. }
  2611. else {
  2612. result = newArray(paramTypes.length);
  2613. }
  2614. for (let i = 0; i < result.length; i++) {
  2615. // TS outputs Object for parameters without types, while Traceur omits
  2616. // the annotations. For now we preserve the Traceur behavior to aid
  2617. // migration, but this can be revisited.
  2618. if (typeof paramTypes === 'undefined') {
  2619. result[i] = [];
  2620. }
  2621. else if (paramTypes[i] && paramTypes[i] != Object) {
  2622. result[i] = [paramTypes[i]];
  2623. }
  2624. else {
  2625. result[i] = [];
  2626. }
  2627. if (paramAnnotations && paramAnnotations[i] != null) {
  2628. result[i] = result[i].concat(paramAnnotations[i]);
  2629. }
  2630. }
  2631. return result;
  2632. }
  2633. _ownParameters(type, parentCtor) {
  2634. const typeStr = type.toString();
  2635. // If we have no decorators, we only have function.length as metadata.
  2636. // In that case, to detect whether a child class declared an own constructor or not,
  2637. // we need to look inside of that constructor to check whether it is
  2638. // just calling the parent.
  2639. // This also helps to work around for https://github.com/Microsoft/TypeScript/issues/12439
  2640. // that sets 'design:paramtypes' to []
  2641. // if a class inherits from another class but has no ctor declared itself.
  2642. if (isDelegateCtor(typeStr)) {
  2643. return null;
  2644. }
  2645. // Prefer the direct API.
  2646. if (type.parameters && type.parameters !== parentCtor.parameters) {
  2647. return type.parameters;
  2648. }
  2649. // API of tsickle for lowering decorators to properties on the class.
  2650. const tsickleCtorParams = type.ctorParameters;
  2651. if (tsickleCtorParams && tsickleCtorParams !== parentCtor.ctorParameters) {
  2652. // Newer tsickle uses a function closure
  2653. // Retain the non-function case for compatibility with older tsickle
  2654. const ctorParameters = typeof tsickleCtorParams === 'function' ? tsickleCtorParams() : tsickleCtorParams;
  2655. const paramTypes = ctorParameters.map((ctorParam) => ctorParam && ctorParam.type);
  2656. const paramAnnotations = ctorParameters.map((ctorParam) => ctorParam && convertTsickleDecoratorIntoMetadata(ctorParam.decorators));
  2657. return this._zipTypesAndAnnotations(paramTypes, paramAnnotations);
  2658. }
  2659. // API for metadata created by invoking the decorators.
  2660. const paramAnnotations = type.hasOwnProperty(PARAMETERS) && type[PARAMETERS];
  2661. const paramTypes = this._reflect &&
  2662. this._reflect.getOwnMetadata &&
  2663. this._reflect.getOwnMetadata('design:paramtypes', type);
  2664. if (paramTypes || paramAnnotations) {
  2665. return this._zipTypesAndAnnotations(paramTypes, paramAnnotations);
  2666. }
  2667. // If a class has no decorators, at least create metadata
  2668. // based on function.length.
  2669. // Note: We know that this is a real constructor as we checked
  2670. // the content of the constructor above.
  2671. return newArray(type.length);
  2672. }
  2673. parameters(type) {
  2674. // Note: only report metadata if we have at least one class decorator
  2675. // to stay in sync with the static reflector.
  2676. if (!isType(type)) {
  2677. return [];
  2678. }
  2679. const parentCtor = getParentCtor(type);
  2680. let parameters = this._ownParameters(type, parentCtor);
  2681. if (!parameters && parentCtor !== Object) {
  2682. parameters = this.parameters(parentCtor);
  2683. }
  2684. return parameters || [];
  2685. }
  2686. _ownAnnotations(typeOrFunc, parentCtor) {
  2687. // Prefer the direct API.
  2688. if (typeOrFunc.annotations && typeOrFunc.annotations !== parentCtor.annotations) {
  2689. let annotations = typeOrFunc.annotations;
  2690. if (typeof annotations === 'function' && annotations.annotations) {
  2691. annotations = annotations.annotations;
  2692. }
  2693. return annotations;
  2694. }
  2695. // API of tsickle for lowering decorators to properties on the class.
  2696. if (typeOrFunc.decorators && typeOrFunc.decorators !== parentCtor.decorators) {
  2697. return convertTsickleDecoratorIntoMetadata(typeOrFunc.decorators);
  2698. }
  2699. // API for metadata created by invoking the decorators.
  2700. if (typeOrFunc.hasOwnProperty(ANNOTATIONS)) {
  2701. return typeOrFunc[ANNOTATIONS];
  2702. }
  2703. return null;
  2704. }
  2705. annotations(typeOrFunc) {
  2706. if (!isType(typeOrFunc)) {
  2707. return [];
  2708. }
  2709. const parentCtor = getParentCtor(typeOrFunc);
  2710. const ownAnnotations = this._ownAnnotations(typeOrFunc, parentCtor) || [];
  2711. const parentAnnotations = parentCtor !== Object ? this.annotations(parentCtor) : [];
  2712. return parentAnnotations.concat(ownAnnotations);
  2713. }
  2714. _ownPropMetadata(typeOrFunc, parentCtor) {
  2715. // Prefer the direct API.
  2716. if (typeOrFunc.propMetadata &&
  2717. typeOrFunc.propMetadata !== parentCtor.propMetadata) {
  2718. let propMetadata = typeOrFunc.propMetadata;
  2719. if (typeof propMetadata === 'function' && propMetadata.propMetadata) {
  2720. propMetadata = propMetadata.propMetadata;
  2721. }
  2722. return propMetadata;
  2723. }
  2724. // API of tsickle for lowering decorators to properties on the class.
  2725. if (typeOrFunc.propDecorators &&
  2726. typeOrFunc.propDecorators !== parentCtor.propDecorators) {
  2727. const propDecorators = typeOrFunc.propDecorators;
  2728. const propMetadata = {};
  2729. Object.keys(propDecorators).forEach((prop) => {
  2730. propMetadata[prop] = convertTsickleDecoratorIntoMetadata(propDecorators[prop]);
  2731. });
  2732. return propMetadata;
  2733. }
  2734. // API for metadata created by invoking the decorators.
  2735. if (typeOrFunc.hasOwnProperty(PROP_METADATA)) {
  2736. return typeOrFunc[PROP_METADATA];
  2737. }
  2738. return null;
  2739. }
  2740. propMetadata(typeOrFunc) {
  2741. if (!isType(typeOrFunc)) {
  2742. return {};
  2743. }
  2744. const parentCtor = getParentCtor(typeOrFunc);
  2745. const propMetadata = {};
  2746. if (parentCtor !== Object) {
  2747. const parentPropMetadata = this.propMetadata(parentCtor);
  2748. Object.keys(parentPropMetadata).forEach((propName) => {
  2749. propMetadata[propName] = parentPropMetadata[propName];
  2750. });
  2751. }
  2752. const ownPropMetadata = this._ownPropMetadata(typeOrFunc, parentCtor);
  2753. if (ownPropMetadata) {
  2754. Object.keys(ownPropMetadata).forEach((propName) => {
  2755. const decorators = [];
  2756. if (propMetadata.hasOwnProperty(propName)) {
  2757. decorators.push(...propMetadata[propName]);
  2758. }
  2759. decorators.push(...ownPropMetadata[propName]);
  2760. propMetadata[propName] = decorators;
  2761. });
  2762. }
  2763. return propMetadata;
  2764. }
  2765. ownPropMetadata(typeOrFunc) {
  2766. if (!isType(typeOrFunc)) {
  2767. return {};
  2768. }
  2769. return this._ownPropMetadata(typeOrFunc, getParentCtor(typeOrFunc)) || {};
  2770. }
  2771. hasLifecycleHook(type, lcProperty) {
  2772. return type instanceof Type && lcProperty in type.prototype;
  2773. }
  2774. }
  2775. function convertTsickleDecoratorIntoMetadata(decoratorInvocations) {
  2776. if (!decoratorInvocations) {
  2777. return [];
  2778. }
  2779. return decoratorInvocations.map((decoratorInvocation) => {
  2780. const decoratorType = decoratorInvocation.type;
  2781. const annotationCls = decoratorType.annotationCls;
  2782. const annotationArgs = decoratorInvocation.args ? decoratorInvocation.args : [];
  2783. return new annotationCls(...annotationArgs);
  2784. });
  2785. }
  2786. function getParentCtor(ctor) {
  2787. const parentProto = ctor.prototype ? Object.getPrototypeOf(ctor.prototype) : null;
  2788. const parentCtor = parentProto ? parentProto.constructor : null;
  2789. // Note: We always use `Object` as the null value
  2790. // to simplify checking later on.
  2791. return parentCtor || Object;
  2792. }
  2793. // Below are constants for LView indices to help us look up LView members
  2794. // without having to remember the specific indices.
  2795. // Uglify will inline these when minifying so there shouldn't be a cost.
  2796. const HOST = 0;
  2797. const TVIEW = 1;
  2798. // Shared with LContainer
  2799. const FLAGS = 2;
  2800. const PARENT = 3;
  2801. const NEXT = 4;
  2802. const T_HOST = 5;
  2803. // End shared with LContainer
  2804. const HYDRATION = 6;
  2805. const CLEANUP = 7;
  2806. const CONTEXT = 8;
  2807. const INJECTOR = 9;
  2808. const ENVIRONMENT = 10;
  2809. const RENDERER = 11;
  2810. const CHILD_HEAD = 12;
  2811. const CHILD_TAIL = 13;
  2812. // FIXME(misko): Investigate if the three declarations aren't all same thing.
  2813. const DECLARATION_VIEW = 14;
  2814. const DECLARATION_COMPONENT_VIEW = 15;
  2815. const DECLARATION_LCONTAINER = 16;
  2816. const PREORDER_HOOK_FLAGS = 17;
  2817. const QUERIES = 18;
  2818. const ID = 19;
  2819. const EMBEDDED_VIEW_INJECTOR = 20;
  2820. const ON_DESTROY_HOOKS = 21;
  2821. const EFFECTS_TO_SCHEDULE = 22;
  2822. const EFFECTS = 23;
  2823. const REACTIVE_TEMPLATE_CONSUMER = 24;
  2824. const AFTER_RENDER_SEQUENCES_TO_ADD = 25;
  2825. /**
  2826. * Size of LView's header. Necessary to adjust for it when setting slots.
  2827. *
  2828. * IMPORTANT: `HEADER_OFFSET` should only be referred to the in the `ɵɵ*` instructions to translate
  2829. * instruction index into `LView` index. All other indexes should be in the `LView` index space and
  2830. * there should be no need to refer to `HEADER_OFFSET` anywhere else.
  2831. */
  2832. const HEADER_OFFSET = 26;
  2833. /**
  2834. * Special location which allows easy identification of type. If we have an array which was
  2835. * retrieved from the `LView` and that array has `true` at `TYPE` location, we know it is
  2836. * `LContainer`.
  2837. */
  2838. const TYPE = 1;
  2839. /**
  2840. * Below are constants for LContainer indices to help us look up LContainer members
  2841. * without having to remember the specific indices.
  2842. * Uglify will inline these when minifying so there shouldn't be a cost.
  2843. */
  2844. // FLAGS, PARENT, NEXT, and T_HOST are indices 2, 3, 4, and 5
  2845. // As we already have these constants in LView, we don't need to re-create them.
  2846. const DEHYDRATED_VIEWS = 6;
  2847. const NATIVE = 7;
  2848. const VIEW_REFS = 8;
  2849. const MOVED_VIEWS = 9;
  2850. /**
  2851. * Size of LContainer's header. Represents the index after which all views in the
  2852. * container will be inserted. We need to keep a record of current views so we know
  2853. * which views are already in the DOM (and don't need to be re-added) and so we can
  2854. * remove views from the DOM when they are no longer required.
  2855. */
  2856. const CONTAINER_HEADER_OFFSET = 10;
  2857. /**
  2858. * True if `value` is `LView`.
  2859. * @param value wrapped value of `RNode`, `LView`, `LContainer`
  2860. */
  2861. function isLView(value) {
  2862. return Array.isArray(value) && typeof value[TYPE] === 'object';
  2863. }
  2864. /**
  2865. * True if `value` is `LContainer`.
  2866. * @param value wrapped value of `RNode`, `LView`, `LContainer`
  2867. */
  2868. function isLContainer(value) {
  2869. return Array.isArray(value) && value[TYPE] === true;
  2870. }
  2871. function isContentQueryHost(tNode) {
  2872. return (tNode.flags & 4 /* TNodeFlags.hasContentQuery */) !== 0;
  2873. }
  2874. function isComponentHost(tNode) {
  2875. return tNode.componentOffset > -1;
  2876. }
  2877. function isDirectiveHost(tNode) {
  2878. return (tNode.flags & 1 /* TNodeFlags.isDirectiveHost */) === 1 /* TNodeFlags.isDirectiveHost */;
  2879. }
  2880. function isComponentDef(def) {
  2881. return !!def.template;
  2882. }
  2883. function isRootView(target) {
  2884. // Determines whether a given LView is marked as a root view.
  2885. return (target[FLAGS] & 512 /* LViewFlags.IsRoot */) !== 0;
  2886. }
  2887. function isProjectionTNode(tNode) {
  2888. return (tNode.type & 16 /* TNodeType.Projection */) === 16 /* TNodeType.Projection */;
  2889. }
  2890. function hasI18n(lView) {
  2891. return (lView[FLAGS] & 32 /* LViewFlags.HasI18n */) === 32 /* LViewFlags.HasI18n */;
  2892. }
  2893. function isDestroyed(lView) {
  2894. // Determines whether a given LView is marked as destroyed.
  2895. return (lView[FLAGS] & 256 /* LViewFlags.Destroyed */) === 256 /* LViewFlags.Destroyed */;
  2896. }
  2897. // [Assert functions do not constraint type when they are guarded by a truthy
  2898. // expression.](https://github.com/microsoft/TypeScript/issues/37295)
  2899. function assertTNodeForLView(tNode, lView) {
  2900. assertTNodeForTView(tNode, lView[TVIEW]);
  2901. }
  2902. function assertTNodeForTView(tNode, tView) {
  2903. assertTNode(tNode);
  2904. const tData = tView.data;
  2905. for (let i = HEADER_OFFSET; i < tData.length; i++) {
  2906. if (tData[i] === tNode) {
  2907. return;
  2908. }
  2909. }
  2910. throwError('This TNode does not belong to this TView.');
  2911. }
  2912. function assertTNode(tNode) {
  2913. assertDefined(tNode, 'TNode must be defined');
  2914. if (!(tNode && typeof tNode === 'object' && tNode.hasOwnProperty('directiveStylingLast'))) {
  2915. throwError('Not of type TNode, got: ' + tNode);
  2916. }
  2917. }
  2918. function assertTIcu(tIcu) {
  2919. assertDefined(tIcu, 'Expected TIcu to be defined');
  2920. if (!(typeof tIcu.currentCaseLViewIndex === 'number')) {
  2921. throwError('Object is not of TIcu type.');
  2922. }
  2923. }
  2924. function assertComponentType(actual, msg = "Type passed in is not ComponentType, it does not have 'ɵcmp' property.") {
  2925. if (!getComponentDef(actual)) {
  2926. throwError(msg);
  2927. }
  2928. }
  2929. function assertNgModuleType(actual, msg = "Type passed in is not NgModuleType, it does not have 'ɵmod' property.") {
  2930. if (!getNgModuleDef(actual)) {
  2931. throwError(msg);
  2932. }
  2933. }
  2934. function assertHasParent(tNode) {
  2935. assertDefined(tNode, 'currentTNode should exist!');
  2936. assertDefined(tNode.parent, 'currentTNode should have a parent');
  2937. }
  2938. function assertLContainer(value) {
  2939. assertDefined(value, 'LContainer must be defined');
  2940. assertEqual(isLContainer(value), true, 'Expecting LContainer');
  2941. }
  2942. function assertLViewOrUndefined(value) {
  2943. value && assertEqual(isLView(value), true, 'Expecting LView or undefined or null');
  2944. }
  2945. function assertLView(value) {
  2946. assertDefined(value, 'LView must be defined');
  2947. assertEqual(isLView(value), true, 'Expecting LView');
  2948. }
  2949. function assertFirstCreatePass(tView, errMessage) {
  2950. assertEqual(tView.firstCreatePass, true, errMessage || 'Should only be called in first create pass.');
  2951. }
  2952. function assertFirstUpdatePass(tView, errMessage) {
  2953. assertEqual(tView.firstUpdatePass, true, 'Should only be called in first update pass.');
  2954. }
  2955. /**
  2956. * This is a basic sanity check that an object is probably a directive def. DirectiveDef is
  2957. * an interface, so we can't do a direct instanceof check.
  2958. */
  2959. function assertDirectiveDef(obj) {
  2960. if (obj.type === undefined || obj.selectors == undefined || obj.inputs === undefined) {
  2961. throwError(`Expected a DirectiveDef/ComponentDef and this object does not seem to have the expected shape.`);
  2962. }
  2963. }
  2964. function assertIndexInDeclRange(tView, index) {
  2965. assertBetween(HEADER_OFFSET, tView.bindingStartIndex, index);
  2966. }
  2967. function assertIndexInExpandoRange(lView, index) {
  2968. const tView = lView[1];
  2969. assertBetween(tView.expandoStartIndex, lView.length, index);
  2970. }
  2971. function assertBetween(lower, upper, index) {
  2972. if (!(lower <= index && index < upper)) {
  2973. throwError(`Index out of range (expecting ${lower} <= ${index} < ${upper})`);
  2974. }
  2975. }
  2976. function assertProjectionSlots(lView, errMessage) {
  2977. assertDefined(lView[DECLARATION_COMPONENT_VIEW], 'Component views should exist.');
  2978. assertDefined(lView[DECLARATION_COMPONENT_VIEW][T_HOST].projection, 'Components with projection nodes (<ng-content>) must have projection slots defined.');
  2979. }
  2980. function assertParentView(lView, errMessage) {
  2981. assertDefined(lView, "Component views should always have a parent view (component's host view)");
  2982. }
  2983. /**
  2984. * This is a basic sanity check that the `injectorIndex` seems to point to what looks like a
  2985. * NodeInjector data structure.
  2986. *
  2987. * @param lView `LView` which should be checked.
  2988. * @param injectorIndex index into the `LView` where the `NodeInjector` is expected.
  2989. */
  2990. function assertNodeInjector(lView, injectorIndex) {
  2991. assertIndexInExpandoRange(lView, injectorIndex);
  2992. assertIndexInExpandoRange(lView, injectorIndex + 8 /* NodeInjectorOffset.PARENT */);
  2993. assertNumber(lView[injectorIndex + 0], 'injectorIndex should point to a bloom filter');
  2994. assertNumber(lView[injectorIndex + 1], 'injectorIndex should point to a bloom filter');
  2995. assertNumber(lView[injectorIndex + 2], 'injectorIndex should point to a bloom filter');
  2996. assertNumber(lView[injectorIndex + 3], 'injectorIndex should point to a bloom filter');
  2997. assertNumber(lView[injectorIndex + 4], 'injectorIndex should point to a bloom filter');
  2998. assertNumber(lView[injectorIndex + 5], 'injectorIndex should point to a bloom filter');
  2999. assertNumber(lView[injectorIndex + 6], 'injectorIndex should point to a bloom filter');
  3000. assertNumber(lView[injectorIndex + 7], 'injectorIndex should point to a bloom filter');
  3001. assertNumber(lView[injectorIndex + 8 /* NodeInjectorOffset.PARENT */], 'injectorIndex should point to parent injector');
  3002. }
  3003. /**
  3004. * Represents a basic change from a previous to a new value for a single
  3005. * property on a directive instance. Passed as a value in a
  3006. * {@link SimpleChanges} object to the `ngOnChanges` hook.
  3007. *
  3008. * @see {@link OnChanges}
  3009. *
  3010. * @publicApi
  3011. */
  3012. class SimpleChange {
  3013. previousValue;
  3014. currentValue;
  3015. firstChange;
  3016. constructor(previousValue, currentValue, firstChange) {
  3017. this.previousValue = previousValue;
  3018. this.currentValue = currentValue;
  3019. this.firstChange = firstChange;
  3020. }
  3021. /**
  3022. * Check whether the new value is the first value assigned.
  3023. */
  3024. isFirstChange() {
  3025. return this.firstChange;
  3026. }
  3027. }
  3028. function applyValueToInputField(instance, inputSignalNode, privateName, value) {
  3029. if (inputSignalNode !== null) {
  3030. inputSignalNode.applyValueToInputSignal(inputSignalNode, value);
  3031. }
  3032. else {
  3033. instance[privateName] = value;
  3034. }
  3035. }
  3036. /**
  3037. * The NgOnChangesFeature decorates a component with support for the ngOnChanges
  3038. * lifecycle hook, so it should be included in any component that implements
  3039. * that hook.
  3040. *
  3041. * If the component or directive uses inheritance, the NgOnChangesFeature MUST
  3042. * be included as a feature AFTER {@link InheritDefinitionFeature}, otherwise
  3043. * inherited properties will not be propagated to the ngOnChanges lifecycle
  3044. * hook.
  3045. *
  3046. * Example usage:
  3047. *
  3048. * ```ts
  3049. * static ɵcmp = defineComponent({
  3050. * ...
  3051. * inputs: {name: 'publicName'},
  3052. * features: [NgOnChangesFeature]
  3053. * });
  3054. * ```
  3055. *
  3056. * @codeGenApi
  3057. */
  3058. const ɵɵNgOnChangesFeature = /* @__PURE__ */ (() => {
  3059. const ɵɵNgOnChangesFeatureImpl = () => NgOnChangesFeatureImpl;
  3060. // This option ensures that the ngOnChanges lifecycle hook will be inherited
  3061. // from superclasses (in InheritDefinitionFeature).
  3062. /** @nocollapse */
  3063. ɵɵNgOnChangesFeatureImpl.ngInherit = true;
  3064. return ɵɵNgOnChangesFeatureImpl;
  3065. })();
  3066. function NgOnChangesFeatureImpl(definition) {
  3067. if (definition.type.prototype.ngOnChanges) {
  3068. definition.setInput = ngOnChangesSetInput;
  3069. }
  3070. return rememberChangeHistoryAndInvokeOnChangesHook;
  3071. }
  3072. /**
  3073. * This is a synthetic lifecycle hook which gets inserted into `TView.preOrderHooks` to simulate
  3074. * `ngOnChanges`.
  3075. *
  3076. * The hook reads the `NgSimpleChangesStore` data from the component instance and if changes are
  3077. * found it invokes `ngOnChanges` on the component instance.
  3078. *
  3079. * @param this Component instance. Because this function gets inserted into `TView.preOrderHooks`,
  3080. * it is guaranteed to be called with component instance.
  3081. */
  3082. function rememberChangeHistoryAndInvokeOnChangesHook() {
  3083. const simpleChangesStore = getSimpleChangesStore(this);
  3084. const current = simpleChangesStore?.current;
  3085. if (current) {
  3086. const previous = simpleChangesStore.previous;
  3087. if (previous === EMPTY_OBJ) {
  3088. simpleChangesStore.previous = current;
  3089. }
  3090. else {
  3091. // New changes are copied to the previous store, so that we don't lose history for inputs
  3092. // which were not changed this time
  3093. for (let key in current) {
  3094. previous[key] = current[key];
  3095. }
  3096. }
  3097. simpleChangesStore.current = null;
  3098. this.ngOnChanges(current);
  3099. }
  3100. }
  3101. function ngOnChangesSetInput(instance, inputSignalNode, value, publicName, privateName) {
  3102. const declaredName = this.declaredInputs[publicName];
  3103. ngDevMode && assertString(declaredName, 'Name of input in ngOnChanges has to be a string');
  3104. const simpleChangesStore = getSimpleChangesStore(instance) ||
  3105. setSimpleChangesStore(instance, { previous: EMPTY_OBJ, current: null });
  3106. const current = simpleChangesStore.current || (simpleChangesStore.current = {});
  3107. const previous = simpleChangesStore.previous;
  3108. const previousChange = previous[declaredName];
  3109. current[declaredName] = new SimpleChange(previousChange && previousChange.currentValue, value, previous === EMPTY_OBJ);
  3110. applyValueToInputField(instance, inputSignalNode, privateName, value);
  3111. }
  3112. const SIMPLE_CHANGES_STORE = '__ngSimpleChanges__';
  3113. function getSimpleChangesStore(instance) {
  3114. return instance[SIMPLE_CHANGES_STORE] || null;
  3115. }
  3116. function setSimpleChangesStore(instance, store) {
  3117. return (instance[SIMPLE_CHANGES_STORE] = store);
  3118. }
  3119. let profilerCallback = null;
  3120. /**
  3121. * Sets the callback function which will be invoked before and after performing certain actions at
  3122. * runtime (for example, before and after running change detection).
  3123. *
  3124. * Warning: this function is *INTERNAL* and should not be relied upon in application's code.
  3125. * The contract of the function might be changed in any release and/or the function can be removed
  3126. * completely.
  3127. *
  3128. * @param profiler function provided by the caller or null value to disable profiling.
  3129. */
  3130. const setProfiler = (profiler) => {
  3131. profilerCallback = profiler;
  3132. };
  3133. /**
  3134. * Profiler function which wraps user code executed by the runtime.
  3135. *
  3136. * @param event ProfilerEvent corresponding to the execution context
  3137. * @param instance component instance
  3138. * @param hookOrListener lifecycle hook function or output listener. The value depends on the
  3139. * execution context
  3140. * @returns
  3141. */
  3142. const profiler = function (event, instance = null, hookOrListener) {
  3143. if (profilerCallback != null /* both `null` and `undefined` */) {
  3144. profilerCallback(event, instance, hookOrListener);
  3145. }
  3146. };
  3147. const SVG_NAMESPACE = 'svg';
  3148. const MATH_ML_NAMESPACE = 'math';
  3149. /**
  3150. * For efficiency reasons we often put several different data types (`RNode`, `LView`, `LContainer`)
  3151. * in same location in `LView`. This is because we don't want to pre-allocate space for it
  3152. * because the storage is sparse. This file contains utilities for dealing with such data types.
  3153. *
  3154. * How do we know what is stored at a given location in `LView`.
  3155. * - `Array.isArray(value) === false` => `RNode` (The normal storage value)
  3156. * - `Array.isArray(value) === true` => then the `value[0]` represents the wrapped value.
  3157. * - `typeof value[TYPE] === 'object'` => `LView`
  3158. * - This happens when we have a component at a given location
  3159. * - `typeof value[TYPE] === true` => `LContainer`
  3160. * - This happens when we have `LContainer` binding at a given location.
  3161. *
  3162. *
  3163. * NOTE: it is assumed that `Array.isArray` and `typeof` operations are very efficient.
  3164. */
  3165. /**
  3166. * Returns `RNode`.
  3167. * @param value wrapped value of `RNode`, `LView`, `LContainer`
  3168. */
  3169. function unwrapRNode(value) {
  3170. while (Array.isArray(value)) {
  3171. value = value[HOST];
  3172. }
  3173. return value;
  3174. }
  3175. /**
  3176. * Returns `LView` or `null` if not found.
  3177. * @param value wrapped value of `RNode`, `LView`, `LContainer`
  3178. */
  3179. function unwrapLView(value) {
  3180. while (Array.isArray(value)) {
  3181. // This check is same as `isLView()` but we don't call at as we don't want to call
  3182. // `Array.isArray()` twice and give JITer more work for inlining.
  3183. if (typeof value[TYPE] === 'object')
  3184. return value;
  3185. value = value[HOST];
  3186. }
  3187. return null;
  3188. }
  3189. /**
  3190. * Retrieves an element value from the provided `viewData`, by unwrapping
  3191. * from any containers, component views, or style contexts.
  3192. */
  3193. function getNativeByIndex(index, lView) {
  3194. ngDevMode && assertIndexInRange(lView, index);
  3195. ngDevMode && assertGreaterThanOrEqual(index, HEADER_OFFSET, 'Expected to be past HEADER_OFFSET');
  3196. return unwrapRNode(lView[index]);
  3197. }
  3198. /**
  3199. * Retrieve an `RNode` for a given `TNode` and `LView`.
  3200. *
  3201. * This function guarantees in dev mode to retrieve a non-null `RNode`.
  3202. *
  3203. * @param tNode
  3204. * @param lView
  3205. */
  3206. function getNativeByTNode(tNode, lView) {
  3207. ngDevMode && assertTNodeForLView(tNode, lView);
  3208. ngDevMode && assertIndexInRange(lView, tNode.index);
  3209. const node = unwrapRNode(lView[tNode.index]);
  3210. return node;
  3211. }
  3212. /**
  3213. * Retrieve an `RNode` or `null` for a given `TNode` and `LView`.
  3214. *
  3215. * Some `TNode`s don't have associated `RNode`s. For example `Projection`
  3216. *
  3217. * @param tNode
  3218. * @param lView
  3219. */
  3220. function getNativeByTNodeOrNull(tNode, lView) {
  3221. const index = tNode === null ? -1 : tNode.index;
  3222. if (index !== -1) {
  3223. ngDevMode && assertTNodeForLView(tNode, lView);
  3224. const node = unwrapRNode(lView[index]);
  3225. return node;
  3226. }
  3227. return null;
  3228. }
  3229. // fixme(misko): The return Type should be `TNode|null`
  3230. function getTNode(tView, index) {
  3231. ngDevMode && assertGreaterThan(index, -1, 'wrong index for TNode');
  3232. ngDevMode && assertLessThan(index, tView.data.length, 'wrong index for TNode');
  3233. const tNode = tView.data[index];
  3234. ngDevMode && tNode !== null && assertTNode(tNode);
  3235. return tNode;
  3236. }
  3237. /** Retrieves a value from any `LView` or `TData`. */
  3238. function load(view, index) {
  3239. ngDevMode && assertIndexInRange(view, index);
  3240. return view[index];
  3241. }
  3242. /** Store a value in the `data` at a given `index`. */
  3243. function store(tView, lView, index, value) {
  3244. // We don't store any static data for local variables, so the first time
  3245. // we see the template, we should store as null to avoid a sparse array
  3246. if (index >= tView.data.length) {
  3247. tView.data[index] = null;
  3248. tView.blueprint[index] = null;
  3249. }
  3250. lView[index] = value;
  3251. }
  3252. function getComponentLViewByIndex(nodeIndex, hostView) {
  3253. // Could be an LView or an LContainer. If LContainer, unwrap to find LView.
  3254. ngDevMode && assertIndexInRange(hostView, nodeIndex);
  3255. const slotValue = hostView[nodeIndex];
  3256. const lView = isLView(slotValue) ? slotValue : slotValue[HOST];
  3257. return lView;
  3258. }
  3259. /** Checks whether a given view is in creation mode */
  3260. function isCreationMode(view) {
  3261. return (view[FLAGS] & 4 /* LViewFlags.CreationMode */) === 4 /* LViewFlags.CreationMode */;
  3262. }
  3263. /**
  3264. * Returns a boolean for whether the view is attached to the change detection tree.
  3265. *
  3266. * Note: This determines whether a view should be checked, not whether it's inserted
  3267. * into a container. For that, you'll want `viewAttachedToContainer` below.
  3268. */
  3269. function viewAttachedToChangeDetector(view) {
  3270. return (view[FLAGS] & 128 /* LViewFlags.Attached */) === 128 /* LViewFlags.Attached */;
  3271. }
  3272. /** Returns a boolean for whether the view is attached to a container. */
  3273. function viewAttachedToContainer(view) {
  3274. return isLContainer(view[PARENT]);
  3275. }
  3276. function getConstant(consts, index) {
  3277. if (index === null || index === undefined)
  3278. return null;
  3279. ngDevMode && assertIndexInRange(consts, index);
  3280. return consts[index];
  3281. }
  3282. /**
  3283. * Resets the pre-order hook flags of the view.
  3284. * @param lView the LView on which the flags are reset
  3285. */
  3286. function resetPreOrderHookFlags(lView) {
  3287. lView[PREORDER_HOOK_FLAGS] = 0;
  3288. }
  3289. /**
  3290. * Adds the `RefreshView` flag from the lView and updates HAS_CHILD_VIEWS_TO_REFRESH flag of
  3291. * parents.
  3292. */
  3293. function markViewForRefresh(lView) {
  3294. if (lView[FLAGS] & 1024 /* LViewFlags.RefreshView */) {
  3295. return;
  3296. }
  3297. lView[FLAGS] |= 1024 /* LViewFlags.RefreshView */;
  3298. if (viewAttachedToChangeDetector(lView)) {
  3299. markAncestorsForTraversal(lView);
  3300. }
  3301. }
  3302. /**
  3303. * Walks up the LView hierarchy.
  3304. * @param nestingLevel Number of times to walk up in hierarchy.
  3305. * @param currentView View from which to start the lookup.
  3306. */
  3307. function walkUpViews(nestingLevel, currentView) {
  3308. while (nestingLevel > 0) {
  3309. ngDevMode &&
  3310. assertDefined(currentView[DECLARATION_VIEW], 'Declaration view should be defined if nesting level is greater than 0.');
  3311. currentView = currentView[DECLARATION_VIEW];
  3312. nestingLevel--;
  3313. }
  3314. return currentView;
  3315. }
  3316. function requiresRefreshOrTraversal(lView) {
  3317. return !!(lView[FLAGS] & (1024 /* LViewFlags.RefreshView */ | 8192 /* LViewFlags.HasChildViewsToRefresh */) ||
  3318. lView[REACTIVE_TEMPLATE_CONSUMER]?.dirty);
  3319. }
  3320. /**
  3321. * Updates the `HasChildViewsToRefresh` flag on the parents of the `LView` as well as the
  3322. * parents above.
  3323. */
  3324. function updateAncestorTraversalFlagsOnAttach(lView) {
  3325. lView[ENVIRONMENT].changeDetectionScheduler?.notify(8 /* NotificationSource.ViewAttached */);
  3326. if (lView[FLAGS] & 64 /* LViewFlags.Dirty */) {
  3327. lView[FLAGS] |= 1024 /* LViewFlags.RefreshView */;
  3328. }
  3329. if (requiresRefreshOrTraversal(lView)) {
  3330. markAncestorsForTraversal(lView);
  3331. }
  3332. }
  3333. /**
  3334. * Ensures views above the given `lView` are traversed during change detection even when they are
  3335. * not dirty.
  3336. *
  3337. * This is done by setting the `HAS_CHILD_VIEWS_TO_REFRESH` flag up to the root, stopping when the
  3338. * flag is already `true` or the `lView` is detached.
  3339. */
  3340. function markAncestorsForTraversal(lView) {
  3341. lView[ENVIRONMENT].changeDetectionScheduler?.notify(0 /* NotificationSource.MarkAncestorsForTraversal */);
  3342. let parent = getLViewParent(lView);
  3343. while (parent !== null) {
  3344. // We stop adding markers to the ancestors once we reach one that already has the marker. This
  3345. // is to avoid needlessly traversing all the way to the root when the marker already exists.
  3346. if (parent[FLAGS] & 8192 /* LViewFlags.HasChildViewsToRefresh */) {
  3347. break;
  3348. }
  3349. parent[FLAGS] |= 8192 /* LViewFlags.HasChildViewsToRefresh */;
  3350. if (!viewAttachedToChangeDetector(parent)) {
  3351. break;
  3352. }
  3353. parent = getLViewParent(parent);
  3354. }
  3355. }
  3356. /**
  3357. * Stores a LView-specific destroy callback.
  3358. */
  3359. function storeLViewOnDestroy(lView, onDestroyCallback) {
  3360. if (isDestroyed(lView)) {
  3361. throw new RuntimeError(911 /* RuntimeErrorCode.VIEW_ALREADY_DESTROYED */, ngDevMode && 'View has already been destroyed.');
  3362. }
  3363. if (lView[ON_DESTROY_HOOKS] === null) {
  3364. lView[ON_DESTROY_HOOKS] = [];
  3365. }
  3366. lView[ON_DESTROY_HOOKS].push(onDestroyCallback);
  3367. }
  3368. /**
  3369. * Removes previously registered LView-specific destroy callback.
  3370. */
  3371. function removeLViewOnDestroy(lView, onDestroyCallback) {
  3372. if (lView[ON_DESTROY_HOOKS] === null)
  3373. return;
  3374. const destroyCBIdx = lView[ON_DESTROY_HOOKS].indexOf(onDestroyCallback);
  3375. if (destroyCBIdx !== -1) {
  3376. lView[ON_DESTROY_HOOKS].splice(destroyCBIdx, 1);
  3377. }
  3378. }
  3379. /**
  3380. * Gets the parent LView of the passed LView, if the PARENT is an LContainer, will get the parent of
  3381. * that LContainer, which is an LView
  3382. * @param lView the lView whose parent to get
  3383. */
  3384. function getLViewParent(lView) {
  3385. ngDevMode && assertLView(lView);
  3386. const parent = lView[PARENT];
  3387. return isLContainer(parent) ? parent[PARENT] : parent;
  3388. }
  3389. function getOrCreateLViewCleanup(view) {
  3390. // top level variables should not be exported for performance reasons (PERF_NOTES.md)
  3391. return (view[CLEANUP] ??= []);
  3392. }
  3393. function getOrCreateTViewCleanup(tView) {
  3394. return (tView.cleanup ??= []);
  3395. }
  3396. /**
  3397. * Saves context for this cleanup function in LView.cleanupInstances.
  3398. *
  3399. * On the first template pass, saves in TView:
  3400. * - Cleanup function
  3401. * - Index of context we just saved in LView.cleanupInstances
  3402. */
  3403. function storeCleanupWithContext(tView, lView, context, cleanupFn) {
  3404. const lCleanup = getOrCreateLViewCleanup(lView);
  3405. // Historically the `storeCleanupWithContext` was used to register both framework-level and
  3406. // user-defined cleanup callbacks, but over time those two types of cleanups were separated.
  3407. // This dev mode checks assures that user-level cleanup callbacks are _not_ stored in data
  3408. // structures reserved for framework-specific hooks.
  3409. ngDevMode &&
  3410. assertDefined(context, 'Cleanup context is mandatory when registering framework-level destroy hooks');
  3411. lCleanup.push(context);
  3412. if (tView.firstCreatePass) {
  3413. getOrCreateTViewCleanup(tView).push(cleanupFn, lCleanup.length - 1);
  3414. }
  3415. else {
  3416. // Make sure that no new framework-level cleanup functions are registered after the first
  3417. // template pass is done (and TView data structures are meant to fully constructed).
  3418. if (ngDevMode) {
  3419. Object.freeze(getOrCreateTViewCleanup(tView));
  3420. }
  3421. }
  3422. }
  3423. const instructionState = {
  3424. lFrame: createLFrame(null),
  3425. bindingsEnabled: true,
  3426. skipHydrationRootTNode: null,
  3427. };
  3428. var CheckNoChangesMode;
  3429. (function (CheckNoChangesMode) {
  3430. CheckNoChangesMode[CheckNoChangesMode["Off"] = 0] = "Off";
  3431. CheckNoChangesMode[CheckNoChangesMode["Exhaustive"] = 1] = "Exhaustive";
  3432. CheckNoChangesMode[CheckNoChangesMode["OnlyDirtyViews"] = 2] = "OnlyDirtyViews";
  3433. })(CheckNoChangesMode || (CheckNoChangesMode = {}));
  3434. /**
  3435. * In this mode, any changes in bindings will throw an ExpressionChangedAfterChecked error.
  3436. *
  3437. * Necessary to support ChangeDetectorRef.checkNoChanges().
  3438. *
  3439. * The `checkNoChanges` function is invoked only in ngDevMode=true and verifies that no unintended
  3440. * changes exist in the change detector or its children.
  3441. */
  3442. let _checkNoChangesMode = 0; /* CheckNoChangesMode.Off */
  3443. /**
  3444. * Flag used to indicate that we are in the middle running change detection on a view
  3445. *
  3446. * @see detectChangesInViewWhileDirty
  3447. */
  3448. let _isRefreshingViews = false;
  3449. function getElementDepthCount() {
  3450. return instructionState.lFrame.elementDepthCount;
  3451. }
  3452. function increaseElementDepthCount() {
  3453. instructionState.lFrame.elementDepthCount++;
  3454. }
  3455. function decreaseElementDepthCount() {
  3456. instructionState.lFrame.elementDepthCount--;
  3457. }
  3458. function getBindingsEnabled() {
  3459. return instructionState.bindingsEnabled;
  3460. }
  3461. /**
  3462. * Returns true if currently inside a skip hydration block.
  3463. * @returns boolean
  3464. */
  3465. function isInSkipHydrationBlock$1() {
  3466. return instructionState.skipHydrationRootTNode !== null;
  3467. }
  3468. /**
  3469. * Returns true if this is the root TNode of the skip hydration block.
  3470. * @param tNode the current TNode
  3471. * @returns boolean
  3472. */
  3473. function isSkipHydrationRootTNode(tNode) {
  3474. return instructionState.skipHydrationRootTNode === tNode;
  3475. }
  3476. /**
  3477. * Enables directive matching on elements.
  3478. *
  3479. * * Example:
  3480. * ```html
  3481. * <my-comp my-directive>
  3482. * Should match component / directive.
  3483. * </my-comp>
  3484. * <div ngNonBindable>
  3485. * <!-- ɵɵdisableBindings() -->
  3486. * <my-comp my-directive>
  3487. * Should not match component / directive because we are in ngNonBindable.
  3488. * </my-comp>
  3489. * <!-- ɵɵenableBindings() -->
  3490. * </div>
  3491. * ```
  3492. *
  3493. * @codeGenApi
  3494. */
  3495. function ɵɵenableBindings() {
  3496. instructionState.bindingsEnabled = true;
  3497. }
  3498. /**
  3499. * Sets a flag to specify that the TNode is in a skip hydration block.
  3500. * @param tNode the current TNode
  3501. */
  3502. function enterSkipHydrationBlock(tNode) {
  3503. instructionState.skipHydrationRootTNode = tNode;
  3504. }
  3505. /**
  3506. * Disables directive matching on element.
  3507. *
  3508. * * Example:
  3509. * ```html
  3510. * <my-comp my-directive>
  3511. * Should match component / directive.
  3512. * </my-comp>
  3513. * <div ngNonBindable>
  3514. * <!-- ɵɵdisableBindings() -->
  3515. * <my-comp my-directive>
  3516. * Should not match component / directive because we are in ngNonBindable.
  3517. * </my-comp>
  3518. * <!-- ɵɵenableBindings() -->
  3519. * </div>
  3520. * ```
  3521. *
  3522. * @codeGenApi
  3523. */
  3524. function ɵɵdisableBindings() {
  3525. instructionState.bindingsEnabled = false;
  3526. }
  3527. /**
  3528. * Clears the root skip hydration node when leaving a skip hydration block.
  3529. */
  3530. function leaveSkipHydrationBlock() {
  3531. instructionState.skipHydrationRootTNode = null;
  3532. }
  3533. /**
  3534. * Return the current `LView`.
  3535. */
  3536. function getLView() {
  3537. return instructionState.lFrame.lView;
  3538. }
  3539. /**
  3540. * Return the current `TView`.
  3541. */
  3542. function getTView() {
  3543. return instructionState.lFrame.tView;
  3544. }
  3545. /**
  3546. * Restores `contextViewData` to the given OpaqueViewState instance.
  3547. *
  3548. * Used in conjunction with the getCurrentView() instruction to save a snapshot
  3549. * of the current view and restore it when listeners are invoked. This allows
  3550. * walking the declaration view tree in listeners to get vars from parent views.
  3551. *
  3552. * @param viewToRestore The OpaqueViewState instance to restore.
  3553. * @returns Context of the restored OpaqueViewState instance.
  3554. *
  3555. * @codeGenApi
  3556. */
  3557. function ɵɵrestoreView(viewToRestore) {
  3558. instructionState.lFrame.contextLView = viewToRestore;
  3559. return viewToRestore[CONTEXT];
  3560. }
  3561. /**
  3562. * Clears the view set in `ɵɵrestoreView` from memory. Returns the passed in
  3563. * value so that it can be used as a return value of an instruction.
  3564. *
  3565. * @codeGenApi
  3566. */
  3567. function ɵɵresetView(value) {
  3568. instructionState.lFrame.contextLView = null;
  3569. return value;
  3570. }
  3571. function getCurrentTNode() {
  3572. let currentTNode = getCurrentTNodePlaceholderOk();
  3573. while (currentTNode !== null && currentTNode.type === 64 /* TNodeType.Placeholder */) {
  3574. currentTNode = currentTNode.parent;
  3575. }
  3576. return currentTNode;
  3577. }
  3578. function getCurrentTNodePlaceholderOk() {
  3579. return instructionState.lFrame.currentTNode;
  3580. }
  3581. function getCurrentParentTNode() {
  3582. const lFrame = instructionState.lFrame;
  3583. const currentTNode = lFrame.currentTNode;
  3584. return lFrame.isParent ? currentTNode : currentTNode.parent;
  3585. }
  3586. function setCurrentTNode(tNode, isParent) {
  3587. ngDevMode && tNode && assertTNodeForTView(tNode, instructionState.lFrame.tView);
  3588. const lFrame = instructionState.lFrame;
  3589. lFrame.currentTNode = tNode;
  3590. lFrame.isParent = isParent;
  3591. }
  3592. function isCurrentTNodeParent() {
  3593. return instructionState.lFrame.isParent;
  3594. }
  3595. function setCurrentTNodeAsNotParent() {
  3596. instructionState.lFrame.isParent = false;
  3597. }
  3598. function getContextLView() {
  3599. const contextLView = instructionState.lFrame.contextLView;
  3600. ngDevMode && assertDefined(contextLView, 'contextLView must be defined.');
  3601. return contextLView;
  3602. }
  3603. function isInCheckNoChangesMode() {
  3604. !ngDevMode && throwError('Must never be called in production mode');
  3605. return _checkNoChangesMode !== CheckNoChangesMode.Off;
  3606. }
  3607. function isExhaustiveCheckNoChanges() {
  3608. !ngDevMode && throwError('Must never be called in production mode');
  3609. return _checkNoChangesMode === CheckNoChangesMode.Exhaustive;
  3610. }
  3611. function setIsInCheckNoChangesMode(mode) {
  3612. !ngDevMode && throwError('Must never be called in production mode');
  3613. _checkNoChangesMode = mode;
  3614. }
  3615. function isRefreshingViews() {
  3616. return _isRefreshingViews;
  3617. }
  3618. function setIsRefreshingViews(mode) {
  3619. const prev = _isRefreshingViews;
  3620. _isRefreshingViews = mode;
  3621. return prev;
  3622. }
  3623. // top level variables should not be exported for performance reasons (PERF_NOTES.md)
  3624. function getBindingRoot() {
  3625. const lFrame = instructionState.lFrame;
  3626. let index = lFrame.bindingRootIndex;
  3627. if (index === -1) {
  3628. index = lFrame.bindingRootIndex = lFrame.tView.bindingStartIndex;
  3629. }
  3630. return index;
  3631. }
  3632. function getBindingIndex() {
  3633. return instructionState.lFrame.bindingIndex;
  3634. }
  3635. function setBindingIndex(value) {
  3636. return (instructionState.lFrame.bindingIndex = value);
  3637. }
  3638. function nextBindingIndex() {
  3639. return instructionState.lFrame.bindingIndex++;
  3640. }
  3641. function incrementBindingIndex(count) {
  3642. const lFrame = instructionState.lFrame;
  3643. const index = lFrame.bindingIndex;
  3644. lFrame.bindingIndex = lFrame.bindingIndex + count;
  3645. return index;
  3646. }
  3647. function isInI18nBlock() {
  3648. return instructionState.lFrame.inI18n;
  3649. }
  3650. function setInI18nBlock(isInI18nBlock) {
  3651. instructionState.lFrame.inI18n = isInI18nBlock;
  3652. }
  3653. /**
  3654. * Set a new binding root index so that host template functions can execute.
  3655. *
  3656. * Bindings inside the host template are 0 index. But because we don't know ahead of time
  3657. * how many host bindings we have we can't pre-compute them. For this reason they are all
  3658. * 0 index and we just shift the root so that they match next available location in the LView.
  3659. *
  3660. * @param bindingRootIndex Root index for `hostBindings`
  3661. * @param currentDirectiveIndex `TData[currentDirectiveIndex]` will point to the current directive
  3662. * whose `hostBindings` are being processed.
  3663. */
  3664. function setBindingRootForHostBindings(bindingRootIndex, currentDirectiveIndex) {
  3665. const lFrame = instructionState.lFrame;
  3666. lFrame.bindingIndex = lFrame.bindingRootIndex = bindingRootIndex;
  3667. setCurrentDirectiveIndex(currentDirectiveIndex);
  3668. }
  3669. /**
  3670. * When host binding is executing this points to the directive index.
  3671. * `TView.data[getCurrentDirectiveIndex()]` is `DirectiveDef`
  3672. * `LView[getCurrentDirectiveIndex()]` is directive instance.
  3673. */
  3674. function getCurrentDirectiveIndex() {
  3675. return instructionState.lFrame.currentDirectiveIndex;
  3676. }
  3677. /**
  3678. * Sets an index of a directive whose `hostBindings` are being processed.
  3679. *
  3680. * @param currentDirectiveIndex `TData` index where current directive instance can be found.
  3681. */
  3682. function setCurrentDirectiveIndex(currentDirectiveIndex) {
  3683. instructionState.lFrame.currentDirectiveIndex = currentDirectiveIndex;
  3684. }
  3685. /**
  3686. * Retrieve the current `DirectiveDef` which is active when `hostBindings` instruction is being
  3687. * executed.
  3688. *
  3689. * @param tData Current `TData` where the `DirectiveDef` will be looked up at.
  3690. */
  3691. function getCurrentDirectiveDef(tData) {
  3692. const currentDirectiveIndex = instructionState.lFrame.currentDirectiveIndex;
  3693. return currentDirectiveIndex === -1 ? null : tData[currentDirectiveIndex];
  3694. }
  3695. function getCurrentQueryIndex() {
  3696. return instructionState.lFrame.currentQueryIndex;
  3697. }
  3698. function setCurrentQueryIndex(value) {
  3699. instructionState.lFrame.currentQueryIndex = value;
  3700. }
  3701. /**
  3702. * Returns a `TNode` of the location where the current `LView` is declared at.
  3703. *
  3704. * @param lView an `LView` that we want to find parent `TNode` for.
  3705. */
  3706. function getDeclarationTNode(lView) {
  3707. const tView = lView[TVIEW];
  3708. // Return the declaration parent for embedded views
  3709. if (tView.type === 2 /* TViewType.Embedded */) {
  3710. ngDevMode && assertDefined(tView.declTNode, 'Embedded TNodes should have declaration parents.');
  3711. return tView.declTNode;
  3712. }
  3713. // Components don't have `TView.declTNode` because each instance of component could be
  3714. // inserted in different location, hence `TView.declTNode` is meaningless.
  3715. // Falling back to `T_HOST` in case we cross component boundary.
  3716. if (tView.type === 1 /* TViewType.Component */) {
  3717. return lView[T_HOST];
  3718. }
  3719. // Remaining TNode type is `TViewType.Root` which doesn't have a parent TNode.
  3720. return null;
  3721. }
  3722. /**
  3723. * This is a light weight version of the `enterView` which is needed by the DI system.
  3724. *
  3725. * @param lView `LView` location of the DI context.
  3726. * @param tNode `TNode` for DI context
  3727. * @param flags DI context flags. if `SkipSelf` flag is set than we walk up the declaration
  3728. * tree from `tNode` until we find parent declared `TElementNode`.
  3729. * @returns `true` if we have successfully entered DI associated with `tNode` (or with declared
  3730. * `TNode` if `flags` has `SkipSelf`). Failing to enter DI implies that no associated
  3731. * `NodeInjector` can be found and we should instead use `ModuleInjector`.
  3732. * - If `true` than this call must be fallowed by `leaveDI`
  3733. * - If `false` than this call failed and we should NOT call `leaveDI`
  3734. */
  3735. function enterDI(lView, tNode, flags) {
  3736. ngDevMode && assertLViewOrUndefined(lView);
  3737. if (flags & InjectFlags.SkipSelf) {
  3738. ngDevMode && assertTNodeForTView(tNode, lView[TVIEW]);
  3739. let parentTNode = tNode;
  3740. let parentLView = lView;
  3741. while (true) {
  3742. ngDevMode && assertDefined(parentTNode, 'Parent TNode should be defined');
  3743. parentTNode = parentTNode.parent;
  3744. if (parentTNode === null && !(flags & InjectFlags.Host)) {
  3745. parentTNode = getDeclarationTNode(parentLView);
  3746. if (parentTNode === null)
  3747. break;
  3748. // In this case, a parent exists and is definitely an element. So it will definitely
  3749. // have an existing lView as the declaration view, which is why we can assume it's defined.
  3750. ngDevMode && assertDefined(parentLView, 'Parent LView should be defined');
  3751. parentLView = parentLView[DECLARATION_VIEW];
  3752. // In Ivy there are Comment nodes that correspond to ngIf and NgFor embedded directives
  3753. // We want to skip those and look only at Elements and ElementContainers to ensure
  3754. // we're looking at true parent nodes, and not content or other types.
  3755. if (parentTNode.type & (2 /* TNodeType.Element */ | 8 /* TNodeType.ElementContainer */)) {
  3756. break;
  3757. }
  3758. }
  3759. else {
  3760. break;
  3761. }
  3762. }
  3763. if (parentTNode === null) {
  3764. // If we failed to find a parent TNode this means that we should use module injector.
  3765. return false;
  3766. }
  3767. else {
  3768. tNode = parentTNode;
  3769. lView = parentLView;
  3770. }
  3771. }
  3772. ngDevMode && assertTNodeForLView(tNode, lView);
  3773. const lFrame = (instructionState.lFrame = allocLFrame());
  3774. lFrame.currentTNode = tNode;
  3775. lFrame.lView = lView;
  3776. return true;
  3777. }
  3778. /**
  3779. * Swap the current lView with a new lView.
  3780. *
  3781. * For performance reasons we store the lView in the top level of the module.
  3782. * This way we minimize the number of properties to read. Whenever a new view
  3783. * is entered we have to store the lView for later, and when the view is
  3784. * exited the state has to be restored
  3785. *
  3786. * @param newView New lView to become active
  3787. * @returns the previously active lView;
  3788. */
  3789. function enterView(newView) {
  3790. ngDevMode && assertNotEqual(newView[0], newView[1], '????');
  3791. ngDevMode && assertLViewOrUndefined(newView);
  3792. const newLFrame = allocLFrame();
  3793. if (ngDevMode) {
  3794. assertEqual(newLFrame.isParent, true, 'Expected clean LFrame');
  3795. assertEqual(newLFrame.lView, null, 'Expected clean LFrame');
  3796. assertEqual(newLFrame.tView, null, 'Expected clean LFrame');
  3797. assertEqual(newLFrame.selectedIndex, -1, 'Expected clean LFrame');
  3798. assertEqual(newLFrame.elementDepthCount, 0, 'Expected clean LFrame');
  3799. assertEqual(newLFrame.currentDirectiveIndex, -1, 'Expected clean LFrame');
  3800. assertEqual(newLFrame.currentNamespace, null, 'Expected clean LFrame');
  3801. assertEqual(newLFrame.bindingRootIndex, -1, 'Expected clean LFrame');
  3802. assertEqual(newLFrame.currentQueryIndex, 0, 'Expected clean LFrame');
  3803. }
  3804. const tView = newView[TVIEW];
  3805. instructionState.lFrame = newLFrame;
  3806. ngDevMode && tView.firstChild && assertTNodeForTView(tView.firstChild, tView);
  3807. newLFrame.currentTNode = tView.firstChild;
  3808. newLFrame.lView = newView;
  3809. newLFrame.tView = tView;
  3810. newLFrame.contextLView = newView;
  3811. newLFrame.bindingIndex = tView.bindingStartIndex;
  3812. newLFrame.inI18n = false;
  3813. }
  3814. /**
  3815. * Allocates next free LFrame. This function tries to reuse the `LFrame`s to lower memory pressure.
  3816. */
  3817. function allocLFrame() {
  3818. const currentLFrame = instructionState.lFrame;
  3819. const childLFrame = currentLFrame === null ? null : currentLFrame.child;
  3820. const newLFrame = childLFrame === null ? createLFrame(currentLFrame) : childLFrame;
  3821. return newLFrame;
  3822. }
  3823. function createLFrame(parent) {
  3824. const lFrame = {
  3825. currentTNode: null,
  3826. isParent: true,
  3827. lView: null,
  3828. tView: null,
  3829. selectedIndex: -1,
  3830. contextLView: null,
  3831. elementDepthCount: 0,
  3832. currentNamespace: null,
  3833. currentDirectiveIndex: -1,
  3834. bindingRootIndex: -1,
  3835. bindingIndex: -1,
  3836. currentQueryIndex: 0,
  3837. parent: parent,
  3838. child: null,
  3839. inI18n: false,
  3840. };
  3841. parent !== null && (parent.child = lFrame); // link the new LFrame for reuse.
  3842. return lFrame;
  3843. }
  3844. /**
  3845. * A lightweight version of leave which is used with DI.
  3846. *
  3847. * This function only resets `currentTNode` and `LView` as those are the only properties
  3848. * used with DI (`enterDI()`).
  3849. *
  3850. * NOTE: This function is reexported as `leaveDI`. However `leaveDI` has return type of `void` where
  3851. * as `leaveViewLight` has `LFrame`. This is so that `leaveViewLight` can be used in `leaveView`.
  3852. */
  3853. function leaveViewLight() {
  3854. const oldLFrame = instructionState.lFrame;
  3855. instructionState.lFrame = oldLFrame.parent;
  3856. oldLFrame.currentTNode = null;
  3857. oldLFrame.lView = null;
  3858. return oldLFrame;
  3859. }
  3860. /**
  3861. * This is a lightweight version of the `leaveView` which is needed by the DI system.
  3862. *
  3863. * NOTE: this function is an alias so that we can change the type of the function to have `void`
  3864. * return type.
  3865. */
  3866. const leaveDI = leaveViewLight;
  3867. /**
  3868. * Leave the current `LView`
  3869. *
  3870. * This pops the `LFrame` with the associated `LView` from the stack.
  3871. *
  3872. * IMPORTANT: We must zero out the `LFrame` values here otherwise they will be retained. This is
  3873. * because for performance reasons we don't release `LFrame` but rather keep it for next use.
  3874. */
  3875. function leaveView() {
  3876. const oldLFrame = leaveViewLight();
  3877. oldLFrame.isParent = true;
  3878. oldLFrame.tView = null;
  3879. oldLFrame.selectedIndex = -1;
  3880. oldLFrame.contextLView = null;
  3881. oldLFrame.elementDepthCount = 0;
  3882. oldLFrame.currentDirectiveIndex = -1;
  3883. oldLFrame.currentNamespace = null;
  3884. oldLFrame.bindingRootIndex = -1;
  3885. oldLFrame.bindingIndex = -1;
  3886. oldLFrame.currentQueryIndex = 0;
  3887. }
  3888. function nextContextImpl(level) {
  3889. const contextLView = (instructionState.lFrame.contextLView = walkUpViews(level, instructionState.lFrame.contextLView));
  3890. return contextLView[CONTEXT];
  3891. }
  3892. /**
  3893. * Gets the currently selected element index.
  3894. *
  3895. * Used with {@link property} instruction (and more in the future) to identify the index in the
  3896. * current `LView` to act on.
  3897. */
  3898. function getSelectedIndex() {
  3899. return instructionState.lFrame.selectedIndex;
  3900. }
  3901. /**
  3902. * Sets the most recent index passed to {@link select}
  3903. *
  3904. * Used with {@link property} instruction (and more in the future) to identify the index in the
  3905. * current `LView` to act on.
  3906. *
  3907. * (Note that if an "exit function" was set earlier (via `setElementExitFn()`) then that will be
  3908. * run if and when the provided `index` value is different from the current selected index value.)
  3909. */
  3910. function setSelectedIndex(index) {
  3911. ngDevMode &&
  3912. index !== -1 &&
  3913. assertGreaterThanOrEqual(index, HEADER_OFFSET, 'Index must be past HEADER_OFFSET (or -1).');
  3914. ngDevMode &&
  3915. assertLessThan(index, instructionState.lFrame.lView.length, "Can't set index passed end of LView");
  3916. instructionState.lFrame.selectedIndex = index;
  3917. }
  3918. /**
  3919. * Gets the `tNode` that represents currently selected element.
  3920. */
  3921. function getSelectedTNode() {
  3922. const lFrame = instructionState.lFrame;
  3923. return getTNode(lFrame.tView, lFrame.selectedIndex);
  3924. }
  3925. /**
  3926. * Sets the namespace used to create elements to `'http://www.w3.org/2000/svg'` in global state.
  3927. *
  3928. * @codeGenApi
  3929. */
  3930. function ɵɵnamespaceSVG() {
  3931. instructionState.lFrame.currentNamespace = SVG_NAMESPACE;
  3932. }
  3933. /**
  3934. * Sets the namespace used to create elements to `'http://www.w3.org/1998/MathML/'` in global state.
  3935. *
  3936. * @codeGenApi
  3937. */
  3938. function ɵɵnamespaceMathML() {
  3939. instructionState.lFrame.currentNamespace = MATH_ML_NAMESPACE;
  3940. }
  3941. /**
  3942. * Sets the namespace used to create elements to `null`, which forces element creation to use
  3943. * `createElement` rather than `createElementNS`.
  3944. *
  3945. * @codeGenApi
  3946. */
  3947. function ɵɵnamespaceHTML() {
  3948. namespaceHTMLInternal();
  3949. }
  3950. /**
  3951. * Sets the namespace used to create elements to `null`, which forces element creation to use
  3952. * `createElement` rather than `createElementNS`.
  3953. */
  3954. function namespaceHTMLInternal() {
  3955. instructionState.lFrame.currentNamespace = null;
  3956. }
  3957. function getNamespace() {
  3958. return instructionState.lFrame.currentNamespace;
  3959. }
  3960. let _wasLastNodeCreated = true;
  3961. /**
  3962. * Retrieves a global flag that indicates whether the most recent DOM node
  3963. * was created or hydrated.
  3964. */
  3965. function wasLastNodeCreated() {
  3966. return _wasLastNodeCreated;
  3967. }
  3968. /**
  3969. * Sets a global flag to indicate whether the most recent DOM node
  3970. * was created or hydrated.
  3971. */
  3972. function lastNodeWasCreated(flag) {
  3973. _wasLastNodeCreated = flag;
  3974. }
  3975. /**
  3976. * Adds all directive lifecycle hooks from the given `DirectiveDef` to the given `TView`.
  3977. *
  3978. * Must be run *only* on the first template pass.
  3979. *
  3980. * Sets up the pre-order hooks on the provided `tView`,
  3981. * see {@link HookData} for details about the data structure.
  3982. *
  3983. * @param directiveIndex The index of the directive in LView
  3984. * @param directiveDef The definition containing the hooks to setup in tView
  3985. * @param tView The current TView
  3986. */
  3987. function registerPreOrderHooks(directiveIndex, directiveDef, tView) {
  3988. ngDevMode && assertFirstCreatePass(tView);
  3989. const { ngOnChanges, ngOnInit, ngDoCheck } = directiveDef.type.prototype;
  3990. if (ngOnChanges) {
  3991. const wrappedOnChanges = NgOnChangesFeatureImpl(directiveDef);
  3992. (tView.preOrderHooks ??= []).push(directiveIndex, wrappedOnChanges);
  3993. (tView.preOrderCheckHooks ??= []).push(directiveIndex, wrappedOnChanges);
  3994. }
  3995. if (ngOnInit) {
  3996. (tView.preOrderHooks ??= []).push(0 - directiveIndex, ngOnInit);
  3997. }
  3998. if (ngDoCheck) {
  3999. (tView.preOrderHooks ??= []).push(directiveIndex, ngDoCheck);
  4000. (tView.preOrderCheckHooks ??= []).push(directiveIndex, ngDoCheck);
  4001. }
  4002. }
  4003. /**
  4004. *
  4005. * Loops through the directives on the provided `tNode` and queues hooks to be
  4006. * run that are not initialization hooks.
  4007. *
  4008. * Should be executed during `elementEnd()` and similar to
  4009. * preserve hook execution order. Content, view, and destroy hooks for projected
  4010. * components and directives must be called *before* their hosts.
  4011. *
  4012. * Sets up the content, view, and destroy hooks on the provided `tView`,
  4013. * see {@link HookData} for details about the data structure.
  4014. *
  4015. * NOTE: This does not set up `onChanges`, `onInit` or `doCheck`, those are set up
  4016. * separately at `elementStart`.
  4017. *
  4018. * @param tView The current TView
  4019. * @param tNode The TNode whose directives are to be searched for hooks to queue
  4020. */
  4021. function registerPostOrderHooks(tView, tNode) {
  4022. ngDevMode && assertFirstCreatePass(tView);
  4023. // It's necessary to loop through the directives at elementEnd() (rather than processing in
  4024. // directiveCreate) so we can preserve the current hook order. Content, view, and destroy
  4025. // hooks for projected components and directives must be called *before* their hosts.
  4026. for (let i = tNode.directiveStart, end = tNode.directiveEnd; i < end; i++) {
  4027. const directiveDef = tView.data[i];
  4028. ngDevMode && assertDefined(directiveDef, 'Expecting DirectiveDef');
  4029. const lifecycleHooks = directiveDef.type.prototype;
  4030. const { ngAfterContentInit, ngAfterContentChecked, ngAfterViewInit, ngAfterViewChecked, ngOnDestroy, } = lifecycleHooks;
  4031. if (ngAfterContentInit) {
  4032. (tView.contentHooks ??= []).push(-i, ngAfterContentInit);
  4033. }
  4034. if (ngAfterContentChecked) {
  4035. (tView.contentHooks ??= []).push(i, ngAfterContentChecked);
  4036. (tView.contentCheckHooks ??= []).push(i, ngAfterContentChecked);
  4037. }
  4038. if (ngAfterViewInit) {
  4039. (tView.viewHooks ??= []).push(-i, ngAfterViewInit);
  4040. }
  4041. if (ngAfterViewChecked) {
  4042. (tView.viewHooks ??= []).push(i, ngAfterViewChecked);
  4043. (tView.viewCheckHooks ??= []).push(i, ngAfterViewChecked);
  4044. }
  4045. if (ngOnDestroy != null) {
  4046. (tView.destroyHooks ??= []).push(i, ngOnDestroy);
  4047. }
  4048. }
  4049. }
  4050. /**
  4051. * Executing hooks requires complex logic as we need to deal with 2 constraints.
  4052. *
  4053. * 1. Init hooks (ngOnInit, ngAfterContentInit, ngAfterViewInit) must all be executed once and only
  4054. * once, across many change detection cycles. This must be true even if some hooks throw, or if
  4055. * some recursively trigger a change detection cycle.
  4056. * To solve that, it is required to track the state of the execution of these init hooks.
  4057. * This is done by storing and maintaining flags in the view: the {@link InitPhaseState},
  4058. * and the index within that phase. They can be seen as a cursor in the following structure:
  4059. * [[onInit1, onInit2], [afterContentInit1], [afterViewInit1, afterViewInit2, afterViewInit3]]
  4060. * They are stored as flags in LView[FLAGS].
  4061. *
  4062. * 2. Pre-order hooks can be executed in batches, because of the select instruction.
  4063. * To be able to pause and resume their execution, we also need some state about the hook's array
  4064. * that is being processed:
  4065. * - the index of the next hook to be executed
  4066. * - the number of init hooks already found in the processed part of the array
  4067. * They are stored as flags in LView[PREORDER_HOOK_FLAGS].
  4068. */
  4069. /**
  4070. * Executes pre-order check hooks ( OnChanges, DoChanges) given a view where all the init hooks were
  4071. * executed once. This is a light version of executeInitAndCheckPreOrderHooks where we can skip read
  4072. * / write of the init-hooks related flags.
  4073. * @param lView The LView where hooks are defined
  4074. * @param hooks Hooks to be run
  4075. * @param nodeIndex 3 cases depending on the value:
  4076. * - undefined: all hooks from the array should be executed (post-order case)
  4077. * - null: execute hooks only from the saved index until the end of the array (pre-order case, when
  4078. * flushing the remaining hooks)
  4079. * - number: execute hooks only from the saved index until that node index exclusive (pre-order
  4080. * case, when executing select(number))
  4081. */
  4082. function executeCheckHooks(lView, hooks, nodeIndex) {
  4083. callHooks(lView, hooks, 3 /* InitPhaseState.InitPhaseCompleted */, nodeIndex);
  4084. }
  4085. /**
  4086. * Executes post-order init and check hooks (one of AfterContentInit, AfterContentChecked,
  4087. * AfterViewInit, AfterViewChecked) given a view where there are pending init hooks to be executed.
  4088. * @param lView The LView where hooks are defined
  4089. * @param hooks Hooks to be run
  4090. * @param initPhase A phase for which hooks should be run
  4091. * @param nodeIndex 3 cases depending on the value:
  4092. * - undefined: all hooks from the array should be executed (post-order case)
  4093. * - null: execute hooks only from the saved index until the end of the array (pre-order case, when
  4094. * flushing the remaining hooks)
  4095. * - number: execute hooks only from the saved index until that node index exclusive (pre-order
  4096. * case, when executing select(number))
  4097. */
  4098. function executeInitAndCheckHooks(lView, hooks, initPhase, nodeIndex) {
  4099. ngDevMode &&
  4100. assertNotEqual(initPhase, 3 /* InitPhaseState.InitPhaseCompleted */, 'Init pre-order hooks should not be called more than once');
  4101. if ((lView[FLAGS] & 3 /* LViewFlags.InitPhaseStateMask */) === initPhase) {
  4102. callHooks(lView, hooks, initPhase, nodeIndex);
  4103. }
  4104. }
  4105. function incrementInitPhaseFlags(lView, initPhase) {
  4106. ngDevMode &&
  4107. assertNotEqual(initPhase, 3 /* InitPhaseState.InitPhaseCompleted */, 'Init hooks phase should not be incremented after all init hooks have been run.');
  4108. let flags = lView[FLAGS];
  4109. if ((flags & 3 /* LViewFlags.InitPhaseStateMask */) === initPhase) {
  4110. flags &= 16383 /* LViewFlags.IndexWithinInitPhaseReset */;
  4111. flags += 1 /* LViewFlags.InitPhaseStateIncrementer */;
  4112. lView[FLAGS] = flags;
  4113. }
  4114. }
  4115. /**
  4116. * Calls lifecycle hooks with their contexts, skipping init hooks if it's not
  4117. * the first LView pass
  4118. *
  4119. * @param currentView The current view
  4120. * @param arr The array in which the hooks are found
  4121. * @param initPhaseState the current state of the init phase
  4122. * @param currentNodeIndex 3 cases depending on the value:
  4123. * - undefined: all hooks from the array should be executed (post-order case)
  4124. * - null: execute hooks only from the saved index until the end of the array (pre-order case, when
  4125. * flushing the remaining hooks)
  4126. * - number: execute hooks only from the saved index until that node index exclusive (pre-order
  4127. * case, when executing select(number))
  4128. */
  4129. function callHooks(currentView, arr, initPhase, currentNodeIndex) {
  4130. ngDevMode &&
  4131. assertEqual(isInCheckNoChangesMode(), false, 'Hooks should never be run when in check no changes mode.');
  4132. const startIndex = currentNodeIndex !== undefined
  4133. ? currentView[PREORDER_HOOK_FLAGS] & 65535 /* PreOrderHookFlags.IndexOfTheNextPreOrderHookMaskMask */
  4134. : 0;
  4135. const nodeIndexLimit = currentNodeIndex != null ? currentNodeIndex : -1;
  4136. const max = arr.length - 1; // Stop the loop at length - 1, because we look for the hook at i + 1
  4137. let lastNodeIndexFound = 0;
  4138. for (let i = startIndex; i < max; i++) {
  4139. const hook = arr[i + 1];
  4140. if (typeof hook === 'number') {
  4141. lastNodeIndexFound = arr[i];
  4142. if (currentNodeIndex != null && lastNodeIndexFound >= currentNodeIndex) {
  4143. break;
  4144. }
  4145. }
  4146. else {
  4147. const isInitHook = arr[i] < 0;
  4148. if (isInitHook) {
  4149. currentView[PREORDER_HOOK_FLAGS] += 65536 /* PreOrderHookFlags.NumberOfInitHooksCalledIncrementer */;
  4150. }
  4151. if (lastNodeIndexFound < nodeIndexLimit || nodeIndexLimit == -1) {
  4152. callHook(currentView, initPhase, arr, i);
  4153. currentView[PREORDER_HOOK_FLAGS] =
  4154. (currentView[PREORDER_HOOK_FLAGS] & 4294901760 /* PreOrderHookFlags.NumberOfInitHooksCalledMask */) +
  4155. i +
  4156. 2;
  4157. }
  4158. i++;
  4159. }
  4160. }
  4161. }
  4162. /**
  4163. * Executes a single lifecycle hook, making sure that:
  4164. * - it is called in the non-reactive context;
  4165. * - profiling data are registered.
  4166. */
  4167. function callHookInternal(directive, hook) {
  4168. profiler(4 /* ProfilerEvent.LifecycleHookStart */, directive, hook);
  4169. const prevConsumer = setActiveConsumer$1(null);
  4170. try {
  4171. hook.call(directive);
  4172. }
  4173. finally {
  4174. setActiveConsumer$1(prevConsumer);
  4175. profiler(5 /* ProfilerEvent.LifecycleHookEnd */, directive, hook);
  4176. }
  4177. }
  4178. /**
  4179. * Execute one hook against the current `LView`.
  4180. *
  4181. * @param currentView The current view
  4182. * @param initPhaseState the current state of the init phase
  4183. * @param arr The array in which the hooks are found
  4184. * @param i The current index within the hook data array
  4185. */
  4186. function callHook(currentView, initPhase, arr, i) {
  4187. const isInitHook = arr[i] < 0;
  4188. const hook = arr[i + 1];
  4189. const directiveIndex = isInitHook ? -arr[i] : arr[i];
  4190. const directive = currentView[directiveIndex];
  4191. if (isInitHook) {
  4192. const indexWithintInitPhase = currentView[FLAGS] >> 14 /* LViewFlags.IndexWithinInitPhaseShift */;
  4193. // The init phase state must be always checked here as it may have been recursively updated.
  4194. if (indexWithintInitPhase <
  4195. currentView[PREORDER_HOOK_FLAGS] >> 16 /* PreOrderHookFlags.NumberOfInitHooksCalledShift */ &&
  4196. (currentView[FLAGS] & 3 /* LViewFlags.InitPhaseStateMask */) === initPhase) {
  4197. currentView[FLAGS] += 16384 /* LViewFlags.IndexWithinInitPhaseIncrementer */;
  4198. callHookInternal(directive, hook);
  4199. }
  4200. }
  4201. else {
  4202. callHookInternal(directive, hook);
  4203. }
  4204. }
  4205. const NO_PARENT_INJECTOR = -1;
  4206. /**
  4207. * Each injector is saved in 9 contiguous slots in `LView` and 9 contiguous slots in
  4208. * `TView.data`. This allows us to store information about the current node's tokens (which
  4209. * can be shared in `TView`) as well as the tokens of its ancestor nodes (which cannot be
  4210. * shared, so they live in `LView`).
  4211. *
  4212. * Each of these slots (aside from the last slot) contains a bloom filter. This bloom filter
  4213. * determines whether a directive is available on the associated node or not. This prevents us
  4214. * from searching the directives array at this level unless it's probable the directive is in it.
  4215. *
  4216. * See: https://en.wikipedia.org/wiki/Bloom_filter for more about bloom filters.
  4217. *
  4218. * Because all injectors have been flattened into `LView` and `TViewData`, they cannot typed
  4219. * using interfaces as they were previously. The start index of each `LInjector` and `TInjector`
  4220. * will differ based on where it is flattened into the main array, so it's not possible to know
  4221. * the indices ahead of time and save their types here. The interfaces are still included here
  4222. * for documentation purposes.
  4223. *
  4224. * export interface LInjector extends Array<any> {
  4225. *
  4226. * // Cumulative bloom for directive IDs 0-31 (IDs are % BLOOM_SIZE)
  4227. * [0]: number;
  4228. *
  4229. * // Cumulative bloom for directive IDs 32-63
  4230. * [1]: number;
  4231. *
  4232. * // Cumulative bloom for directive IDs 64-95
  4233. * [2]: number;
  4234. *
  4235. * // Cumulative bloom for directive IDs 96-127
  4236. * [3]: number;
  4237. *
  4238. * // Cumulative bloom for directive IDs 128-159
  4239. * [4]: number;
  4240. *
  4241. * // Cumulative bloom for directive IDs 160 - 191
  4242. * [5]: number;
  4243. *
  4244. * // Cumulative bloom for directive IDs 192 - 223
  4245. * [6]: number;
  4246. *
  4247. * // Cumulative bloom for directive IDs 224 - 255
  4248. * [7]: number;
  4249. *
  4250. * // We need to store a reference to the injector's parent so DI can keep looking up
  4251. * // the injector tree until it finds the dependency it's looking for.
  4252. * [PARENT_INJECTOR]: number;
  4253. * }
  4254. *
  4255. * export interface TInjector extends Array<any> {
  4256. *
  4257. * // Shared node bloom for directive IDs 0-31 (IDs are % BLOOM_SIZE)
  4258. * [0]: number;
  4259. *
  4260. * // Shared node bloom for directive IDs 32-63
  4261. * [1]: number;
  4262. *
  4263. * // Shared node bloom for directive IDs 64-95
  4264. * [2]: number;
  4265. *
  4266. * // Shared node bloom for directive IDs 96-127
  4267. * [3]: number;
  4268. *
  4269. * // Shared node bloom for directive IDs 128-159
  4270. * [4]: number;
  4271. *
  4272. * // Shared node bloom for directive IDs 160 - 191
  4273. * [5]: number;
  4274. *
  4275. * // Shared node bloom for directive IDs 192 - 223
  4276. * [6]: number;
  4277. *
  4278. * // Shared node bloom for directive IDs 224 - 255
  4279. * [7]: number;
  4280. *
  4281. * // Necessary to find directive indices for a particular node.
  4282. * [TNODE]: TElementNode|TElementContainerNode|TContainerNode;
  4283. * }
  4284. */
  4285. /**
  4286. * Factory for creating instances of injectors in the NodeInjector.
  4287. *
  4288. * This factory is complicated by the fact that it can resolve `multi` factories as well.
  4289. *
  4290. * NOTE: Some of the fields are optional which means that this class has two hidden classes.
  4291. * - One without `multi` support (most common)
  4292. * - One with `multi` values, (rare).
  4293. *
  4294. * Since VMs can cache up to 4 inline hidden classes this is OK.
  4295. *
  4296. * - Single factory: Only `resolving` and `factory` is defined.
  4297. * - `providers` factory: `componentProviders` is a number and `index = -1`.
  4298. * - `viewProviders` factory: `componentProviders` is a number and `index` points to `providers`.
  4299. */
  4300. class NodeInjectorFactory {
  4301. factory;
  4302. /**
  4303. * The inject implementation to be activated when using the factory.
  4304. */
  4305. injectImpl;
  4306. /**
  4307. * Marker set to true during factory invocation to see if we get into recursive loop.
  4308. * Recursive loop causes an error to be displayed.
  4309. */
  4310. resolving = false;
  4311. /**
  4312. * Marks that the token can see other Tokens declared in `viewProviders` on the same node.
  4313. */
  4314. canSeeViewProviders;
  4315. /**
  4316. * An array of factories to use in case of `multi` provider.
  4317. */
  4318. multi;
  4319. /**
  4320. * Number of `multi`-providers which belong to the component.
  4321. *
  4322. * This is needed because when multiple components and directives declare the `multi` provider
  4323. * they have to be concatenated in the correct order.
  4324. *
  4325. * Example:
  4326. *
  4327. * If we have a component and directive active an a single element as declared here
  4328. * ```ts
  4329. * component:
  4330. * providers: [ {provide: String, useValue: 'component', multi: true} ],
  4331. * viewProviders: [ {provide: String, useValue: 'componentView', multi: true} ],
  4332. *
  4333. * directive:
  4334. * providers: [ {provide: String, useValue: 'directive', multi: true} ],
  4335. * ```
  4336. *
  4337. * Then the expected results are:
  4338. *
  4339. * ```ts
  4340. * providers: ['component', 'directive']
  4341. * viewProviders: ['component', 'componentView', 'directive']
  4342. * ```
  4343. *
  4344. * The way to think about it is that the `viewProviders` have been inserted after the component
  4345. * but before the directives, which is why we need to know how many `multi`s have been declared by
  4346. * the component.
  4347. */
  4348. componentProviders;
  4349. /**
  4350. * Current index of the Factory in the `data`. Needed for `viewProviders` and `providers` merging.
  4351. * See `providerFactory`.
  4352. */
  4353. index;
  4354. /**
  4355. * Because the same `multi` provider can be declared in `providers` and `viewProviders` it is
  4356. * possible for `viewProviders` to shadow the `providers`. For this reason we store the
  4357. * `provideFactory` of the `providers` so that `providers` can be extended with `viewProviders`.
  4358. *
  4359. * Example:
  4360. *
  4361. * Given:
  4362. * ```ts
  4363. * providers: [ {provide: String, useValue: 'all', multi: true} ],
  4364. * viewProviders: [ {provide: String, useValue: 'viewOnly', multi: true} ],
  4365. * ```
  4366. *
  4367. * We have to return `['all']` in case of content injection, but `['all', 'viewOnly']` in case
  4368. * of view injection. We further have to make sure that the shared instances (in our case
  4369. * `all`) are the exact same instance in both the content as well as the view injection. (We
  4370. * have to make sure that we don't double instantiate.) For this reason the `viewProviders`
  4371. * `Factory` has a pointer to the shadowed `providers` factory so that it can instantiate the
  4372. * `providers` (`['all']`) and then extend it with `viewProviders` (`['all'] + ['viewOnly'] =
  4373. * ['all', 'viewOnly']`).
  4374. */
  4375. providerFactory;
  4376. constructor(
  4377. /**
  4378. * Factory to invoke in order to create a new instance.
  4379. */
  4380. factory,
  4381. /**
  4382. * Set to `true` if the token is declared in `viewProviders` (or if it is component).
  4383. */
  4384. isViewProvider, injectImplementation) {
  4385. this.factory = factory;
  4386. ngDevMode && assertDefined(factory, 'Factory not specified');
  4387. ngDevMode && assertEqual(typeof factory, 'function', 'Expected factory function.');
  4388. this.canSeeViewProviders = isViewProvider;
  4389. this.injectImpl = injectImplementation;
  4390. }
  4391. }
  4392. /**
  4393. * Converts `TNodeType` into human readable text.
  4394. * Make sure this matches with `TNodeType`
  4395. */
  4396. function toTNodeTypeAsString(tNodeType) {
  4397. let text = '';
  4398. tNodeType & 1 /* TNodeType.Text */ && (text += '|Text');
  4399. tNodeType & 2 /* TNodeType.Element */ && (text += '|Element');
  4400. tNodeType & 4 /* TNodeType.Container */ && (text += '|Container');
  4401. tNodeType & 8 /* TNodeType.ElementContainer */ && (text += '|ElementContainer');
  4402. tNodeType & 16 /* TNodeType.Projection */ && (text += '|Projection');
  4403. tNodeType & 32 /* TNodeType.Icu */ && (text += '|IcuContainer');
  4404. tNodeType & 64 /* TNodeType.Placeholder */ && (text += '|Placeholder');
  4405. tNodeType & 128 /* TNodeType.LetDeclaration */ && (text += '|LetDeclaration');
  4406. return text.length > 0 ? text.substring(1) : text;
  4407. }
  4408. /**
  4409. * Helper function to detect if a given value matches a `TNode` shape.
  4410. *
  4411. * The logic uses the `insertBeforeIndex` and its possible values as
  4412. * a way to differentiate a TNode shape from other types of objects
  4413. * within the `TView.data`. This is not a perfect check, but it can
  4414. * be a reasonable differentiator, since we control the shapes of objects
  4415. * within `TView.data`.
  4416. */
  4417. function isTNodeShape(value) {
  4418. return (value != null &&
  4419. typeof value === 'object' &&
  4420. (value.insertBeforeIndex === null ||
  4421. typeof value.insertBeforeIndex === 'number' ||
  4422. Array.isArray(value.insertBeforeIndex)));
  4423. }
  4424. function isLetDeclaration(tNode) {
  4425. return !!(tNode.type & 128 /* TNodeType.LetDeclaration */);
  4426. }
  4427. /**
  4428. * Returns `true` if the `TNode` has a directive which has `@Input()` for `class` binding.
  4429. *
  4430. * ```html
  4431. * <div my-dir [class]="exp"></div>
  4432. * ```
  4433. * and
  4434. * ```ts
  4435. * @Directive({
  4436. * })
  4437. * class MyDirective {
  4438. * @Input()
  4439. * class: string;
  4440. * }
  4441. * ```
  4442. *
  4443. * In the above case it is necessary to write the reconciled styling information into the
  4444. * directive's input.
  4445. *
  4446. * @param tNode
  4447. */
  4448. function hasClassInput(tNode) {
  4449. return (tNode.flags & 8 /* TNodeFlags.hasClassInput */) !== 0;
  4450. }
  4451. /**
  4452. * Returns `true` if the `TNode` has a directive which has `@Input()` for `style` binding.
  4453. *
  4454. * ```html
  4455. * <div my-dir [style]="exp"></div>
  4456. * ```
  4457. * and
  4458. * ```ts
  4459. * @Directive({
  4460. * })
  4461. * class MyDirective {
  4462. * @Input()
  4463. * class: string;
  4464. * }
  4465. * ```
  4466. *
  4467. * In the above case it is necessary to write the reconciled styling information into the
  4468. * directive's input.
  4469. *
  4470. * @param tNode
  4471. */
  4472. function hasStyleInput(tNode) {
  4473. return (tNode.flags & 16 /* TNodeFlags.hasStyleInput */) !== 0;
  4474. }
  4475. function assertTNodeType(tNode, expectedTypes, message) {
  4476. assertDefined(tNode, 'should be called with a TNode');
  4477. if ((tNode.type & expectedTypes) === 0) {
  4478. throwError(message ||
  4479. `Expected [${toTNodeTypeAsString(expectedTypes)}] but got ${toTNodeTypeAsString(tNode.type)}.`);
  4480. }
  4481. }
  4482. function assertPureTNodeType(type) {
  4483. if (!(type === 2 /* TNodeType.Element */ ||
  4484. type === 1 /* TNodeType.Text */ ||
  4485. type === 4 /* TNodeType.Container */ ||
  4486. type === 8 /* TNodeType.ElementContainer */ ||
  4487. type === 32 /* TNodeType.Icu */ ||
  4488. type === 16 /* TNodeType.Projection */ ||
  4489. type === 64 /* TNodeType.Placeholder */ ||
  4490. type === 128 /* TNodeType.LetDeclaration */)) {
  4491. throwError(`Expected TNodeType to have only a single type selected, but got ${toTNodeTypeAsString(type)}.`);
  4492. }
  4493. }
  4494. /**
  4495. * Assigns all attribute values to the provided element via the inferred renderer.
  4496. *
  4497. * This function accepts two forms of attribute entries:
  4498. *
  4499. * default: (key, value):
  4500. * attrs = [key1, value1, key2, value2]
  4501. *
  4502. * namespaced: (NAMESPACE_MARKER, uri, name, value)
  4503. * attrs = [NAMESPACE_MARKER, uri, name, value, NAMESPACE_MARKER, uri, name, value]
  4504. *
  4505. * The `attrs` array can contain a mix of both the default and namespaced entries.
  4506. * The "default" values are set without a marker, but if the function comes across
  4507. * a marker value then it will attempt to set a namespaced value. If the marker is
  4508. * not of a namespaced value then the function will quit and return the index value
  4509. * where it stopped during the iteration of the attrs array.
  4510. *
  4511. * See [AttributeMarker] to understand what the namespace marker value is.
  4512. *
  4513. * Note that this instruction does not support assigning style and class values to
  4514. * an element. See `elementStart` and `elementHostAttrs` to learn how styling values
  4515. * are applied to an element.
  4516. * @param renderer The renderer to be used
  4517. * @param native The element that the attributes will be assigned to
  4518. * @param attrs The attribute array of values that will be assigned to the element
  4519. * @returns the index value that was last accessed in the attributes array
  4520. */
  4521. function setUpAttributes(renderer, native, attrs) {
  4522. let i = 0;
  4523. while (i < attrs.length) {
  4524. const value = attrs[i];
  4525. if (typeof value === 'number') {
  4526. // only namespaces are supported. Other value types (such as style/class
  4527. // entries) are not supported in this function.
  4528. if (value !== 0 /* AttributeMarker.NamespaceURI */) {
  4529. break;
  4530. }
  4531. // we just landed on the marker value ... therefore
  4532. // we should skip to the next entry
  4533. i++;
  4534. const namespaceURI = attrs[i++];
  4535. const attrName = attrs[i++];
  4536. const attrVal = attrs[i++];
  4537. ngDevMode && ngDevMode.rendererSetAttribute++;
  4538. renderer.setAttribute(native, attrName, attrVal, namespaceURI);
  4539. }
  4540. else {
  4541. // attrName is string;
  4542. const attrName = value;
  4543. const attrVal = attrs[++i];
  4544. // Standard attributes
  4545. ngDevMode && ngDevMode.rendererSetAttribute++;
  4546. if (isAnimationProp(attrName)) {
  4547. renderer.setProperty(native, attrName, attrVal);
  4548. }
  4549. else {
  4550. renderer.setAttribute(native, attrName, attrVal);
  4551. }
  4552. i++;
  4553. }
  4554. }
  4555. // another piece of code may iterate over the same attributes array. Therefore
  4556. // it may be helpful to return the exact spot where the attributes array exited
  4557. // whether by running into an unsupported marker or if all the static values were
  4558. // iterated over.
  4559. return i;
  4560. }
  4561. /**
  4562. * Test whether the given value is a marker that indicates that the following
  4563. * attribute values in a `TAttributes` array are only the names of attributes,
  4564. * and not name-value pairs.
  4565. * @param marker The attribute marker to test.
  4566. * @returns true if the marker is a "name-only" marker (e.g. `Bindings`, `Template` or `I18n`).
  4567. */
  4568. function isNameOnlyAttributeMarker(marker) {
  4569. return (marker === 3 /* AttributeMarker.Bindings */ ||
  4570. marker === 4 /* AttributeMarker.Template */ ||
  4571. marker === 6 /* AttributeMarker.I18n */);
  4572. }
  4573. function isAnimationProp(name) {
  4574. // Perf note: accessing charCodeAt to check for the first character of a string is faster as
  4575. // compared to accessing a character at index 0 (ex. name[0]). The main reason for this is that
  4576. // charCodeAt doesn't allocate memory to return a substring.
  4577. return name.charCodeAt(0) === 64 /* CharCode.AT_SIGN */;
  4578. }
  4579. /**
  4580. * Merges `src` `TAttributes` into `dst` `TAttributes` removing any duplicates in the process.
  4581. *
  4582. * This merge function keeps the order of attrs same.
  4583. *
  4584. * @param dst Location of where the merged `TAttributes` should end up.
  4585. * @param src `TAttributes` which should be appended to `dst`
  4586. */
  4587. function mergeHostAttrs(dst, src) {
  4588. if (src === null || src.length === 0) ;
  4589. else if (dst === null || dst.length === 0) {
  4590. // We have source, but dst is empty, just make a copy.
  4591. dst = src.slice();
  4592. }
  4593. else {
  4594. let srcMarker = -1 /* AttributeMarker.ImplicitAttributes */;
  4595. for (let i = 0; i < src.length; i++) {
  4596. const item = src[i];
  4597. if (typeof item === 'number') {
  4598. srcMarker = item;
  4599. }
  4600. else {
  4601. if (srcMarker === 0 /* AttributeMarker.NamespaceURI */) ;
  4602. else if (srcMarker === -1 /* AttributeMarker.ImplicitAttributes */ ||
  4603. srcMarker === 2 /* AttributeMarker.Styles */) {
  4604. // Case where we have to consume `key1` and `value` only.
  4605. mergeHostAttribute(dst, srcMarker, item, null, src[++i]);
  4606. }
  4607. else {
  4608. // Case where we have to consume `key1` only.
  4609. mergeHostAttribute(dst, srcMarker, item, null, null);
  4610. }
  4611. }
  4612. }
  4613. }
  4614. return dst;
  4615. }
  4616. /**
  4617. * Append `key`/`value` to existing `TAttributes` taking region marker and duplicates into account.
  4618. *
  4619. * @param dst `TAttributes` to append to.
  4620. * @param marker Region where the `key`/`value` should be added.
  4621. * @param key1 Key to add to `TAttributes`
  4622. * @param key2 Key to add to `TAttributes` (in case of `AttributeMarker.NamespaceURI`)
  4623. * @param value Value to add or to overwrite to `TAttributes` Only used if `marker` is not Class.
  4624. */
  4625. function mergeHostAttribute(dst, marker, key1, key2, value) {
  4626. let i = 0;
  4627. // Assume that new markers will be inserted at the end.
  4628. let markerInsertPosition = dst.length;
  4629. // scan until correct type.
  4630. if (marker === -1 /* AttributeMarker.ImplicitAttributes */) {
  4631. markerInsertPosition = -1;
  4632. }
  4633. else {
  4634. while (i < dst.length) {
  4635. const dstValue = dst[i++];
  4636. if (typeof dstValue === 'number') {
  4637. if (dstValue === marker) {
  4638. markerInsertPosition = -1;
  4639. break;
  4640. }
  4641. else if (dstValue > marker) {
  4642. // We need to save this as we want the markers to be inserted in specific order.
  4643. markerInsertPosition = i - 1;
  4644. break;
  4645. }
  4646. }
  4647. }
  4648. }
  4649. // search until you find place of insertion
  4650. while (i < dst.length) {
  4651. const item = dst[i];
  4652. if (typeof item === 'number') {
  4653. // since `i` started as the index after the marker, we did not find it if we are at the next
  4654. // marker
  4655. break;
  4656. }
  4657. else if (item === key1) {
  4658. // We already have same token
  4659. {
  4660. if (value !== null) {
  4661. dst[i + 1] = value;
  4662. }
  4663. return;
  4664. }
  4665. }
  4666. // Increment counter.
  4667. i++;
  4668. if (value !== null)
  4669. i++;
  4670. }
  4671. // insert at location.
  4672. if (markerInsertPosition !== -1) {
  4673. dst.splice(markerInsertPosition, 0, marker);
  4674. i = markerInsertPosition + 1;
  4675. }
  4676. dst.splice(i++, 0, key1);
  4677. if (value !== null) {
  4678. dst.splice(i++, 0, value);
  4679. }
  4680. }
  4681. /// Parent Injector Utils ///////////////////////////////////////////////////////////////
  4682. function hasParentInjector(parentLocation) {
  4683. return parentLocation !== NO_PARENT_INJECTOR;
  4684. }
  4685. function getParentInjectorIndex(parentLocation) {
  4686. if (ngDevMode) {
  4687. assertNumber(parentLocation, 'Number expected');
  4688. assertNotEqual(parentLocation, -1, 'Not a valid state.');
  4689. const parentInjectorIndex = parentLocation & 32767 /* RelativeInjectorLocationFlags.InjectorIndexMask */;
  4690. assertGreaterThan(parentInjectorIndex, HEADER_OFFSET, 'Parent injector must be pointing past HEADER_OFFSET.');
  4691. }
  4692. return parentLocation & 32767 /* RelativeInjectorLocationFlags.InjectorIndexMask */;
  4693. }
  4694. function getParentInjectorViewOffset(parentLocation) {
  4695. return parentLocation >> 16 /* RelativeInjectorLocationFlags.ViewOffsetShift */;
  4696. }
  4697. /**
  4698. * Unwraps a parent injector location number to find the view offset from the current injector,
  4699. * then walks up the declaration view tree until the view is found that contains the parent
  4700. * injector.
  4701. *
  4702. * @param location The location of the parent injector, which contains the view offset
  4703. * @param startView The LView instance from which to start walking up the view tree
  4704. * @returns The LView instance that contains the parent injector
  4705. */
  4706. function getParentInjectorView(location, startView) {
  4707. let viewOffset = getParentInjectorViewOffset(location);
  4708. let parentView = startView;
  4709. // For most cases, the parent injector can be found on the host node (e.g. for component
  4710. // or container), but we must keep the loop here to support the rarer case of deeply nested
  4711. // <ng-template> tags or inline views, where the parent injector might live many views
  4712. // above the child injector.
  4713. while (viewOffset > 0) {
  4714. parentView = parentView[DECLARATION_VIEW];
  4715. viewOffset--;
  4716. }
  4717. return parentView;
  4718. }
  4719. /**
  4720. * Defines if the call to `inject` should include `viewProviders` in its resolution.
  4721. *
  4722. * This is set to true when we try to instantiate a component. This value is reset in
  4723. * `getNodeInjectable` to a value which matches the declaration location of the token about to be
  4724. * instantiated. This is done so that if we are injecting a token which was declared outside of
  4725. * `viewProviders` we don't accidentally pull `viewProviders` in.
  4726. *
  4727. * Example:
  4728. *
  4729. * ```ts
  4730. * @Injectable()
  4731. * class MyService {
  4732. * constructor(public value: String) {}
  4733. * }
  4734. *
  4735. * @Component({
  4736. * providers: [
  4737. * MyService,
  4738. * {provide: String, value: 'providers' }
  4739. * ]
  4740. * viewProviders: [
  4741. * {provide: String, value: 'viewProviders'}
  4742. * ]
  4743. * })
  4744. * class MyComponent {
  4745. * constructor(myService: MyService, value: String) {
  4746. * // We expect that Component can see into `viewProviders`.
  4747. * expect(value).toEqual('viewProviders');
  4748. * // `MyService` was not declared in `viewProviders` hence it can't see it.
  4749. * expect(myService.value).toEqual('providers');
  4750. * }
  4751. * }
  4752. *
  4753. * ```
  4754. */
  4755. let includeViewProviders = true;
  4756. function setIncludeViewProviders(v) {
  4757. const oldValue = includeViewProviders;
  4758. includeViewProviders = v;
  4759. return oldValue;
  4760. }
  4761. /**
  4762. * The number of slots in each bloom filter (used by DI). The larger this number, the fewer
  4763. * directives that will share slots, and thus, the fewer false positives when checking for
  4764. * the existence of a directive.
  4765. */
  4766. const BLOOM_SIZE = 256;
  4767. const BLOOM_MASK = BLOOM_SIZE - 1;
  4768. /**
  4769. * The number of bits that is represented by a single bloom bucket. JS bit operations are 32 bits,
  4770. * so each bucket represents 32 distinct tokens which accounts for log2(32) = 5 bits of a bloom hash
  4771. * number.
  4772. */
  4773. const BLOOM_BUCKET_BITS = 5;
  4774. /** Counter used to generate unique IDs for directives. */
  4775. let nextNgElementId = 0;
  4776. /** Value used when something wasn't found by an injector. */
  4777. const NOT_FOUND = {};
  4778. /**
  4779. * Registers this directive as present in its node's injector by flipping the directive's
  4780. * corresponding bit in the injector's bloom filter.
  4781. *
  4782. * @param injectorIndex The index of the node injector where this token should be registered
  4783. * @param tView The TView for the injector's bloom filters
  4784. * @param type The directive token to register
  4785. */
  4786. function bloomAdd(injectorIndex, tView, type) {
  4787. ngDevMode && assertEqual(tView.firstCreatePass, true, 'expected firstCreatePass to be true');
  4788. let id;
  4789. if (typeof type === 'string') {
  4790. id = type.charCodeAt(0) || 0;
  4791. }
  4792. else if (type.hasOwnProperty(NG_ELEMENT_ID)) {
  4793. id = type[NG_ELEMENT_ID];
  4794. }
  4795. // Set a unique ID on the directive type, so if something tries to inject the directive,
  4796. // we can easily retrieve the ID and hash it into the bloom bit that should be checked.
  4797. if (id == null) {
  4798. id = type[NG_ELEMENT_ID] = nextNgElementId++;
  4799. }
  4800. // We only have BLOOM_SIZE (256) slots in our bloom filter (8 buckets * 32 bits each),
  4801. // so all unique IDs must be modulo-ed into a number from 0 - 255 to fit into the filter.
  4802. const bloomHash = id & BLOOM_MASK;
  4803. // Create a mask that targets the specific bit associated with the directive.
  4804. // JS bit operations are 32 bits, so this will be a number between 2^0 and 2^31, corresponding
  4805. // to bit positions 0 - 31 in a 32 bit integer.
  4806. const mask = 1 << bloomHash;
  4807. // Each bloom bucket in `tData` represents `BLOOM_BUCKET_BITS` number of bits of `bloomHash`.
  4808. // Any bits in `bloomHash` beyond `BLOOM_BUCKET_BITS` indicate the bucket offset that the mask
  4809. // should be written to.
  4810. tView.data[injectorIndex + (bloomHash >> BLOOM_BUCKET_BITS)] |= mask;
  4811. }
  4812. /**
  4813. * Creates (or gets an existing) injector for a given element or container.
  4814. *
  4815. * @param tNode for which an injector should be retrieved / created.
  4816. * @param lView View where the node is stored
  4817. * @returns Node injector
  4818. */
  4819. function getOrCreateNodeInjectorForNode(tNode, lView) {
  4820. const existingInjectorIndex = getInjectorIndex(tNode, lView);
  4821. if (existingInjectorIndex !== -1) {
  4822. return existingInjectorIndex;
  4823. }
  4824. const tView = lView[TVIEW];
  4825. if (tView.firstCreatePass) {
  4826. tNode.injectorIndex = lView.length;
  4827. insertBloom(tView.data, tNode); // foundation for node bloom
  4828. insertBloom(lView, null); // foundation for cumulative bloom
  4829. insertBloom(tView.blueprint, null);
  4830. }
  4831. const parentLoc = getParentInjectorLocation(tNode, lView);
  4832. const injectorIndex = tNode.injectorIndex;
  4833. // If a parent injector can't be found, its location is set to -1.
  4834. // In that case, we don't need to set up a cumulative bloom
  4835. if (hasParentInjector(parentLoc)) {
  4836. const parentIndex = getParentInjectorIndex(parentLoc);
  4837. const parentLView = getParentInjectorView(parentLoc, lView);
  4838. const parentData = parentLView[TVIEW].data;
  4839. // Creates a cumulative bloom filter that merges the parent's bloom filter
  4840. // and its own cumulative bloom (which contains tokens for all ancestors)
  4841. for (let i = 0; i < 8 /* NodeInjectorOffset.BLOOM_SIZE */; i++) {
  4842. lView[injectorIndex + i] = parentLView[parentIndex + i] | parentData[parentIndex + i];
  4843. }
  4844. }
  4845. lView[injectorIndex + 8 /* NodeInjectorOffset.PARENT */] = parentLoc;
  4846. return injectorIndex;
  4847. }
  4848. function insertBloom(arr, footer) {
  4849. arr.push(0, 0, 0, 0, 0, 0, 0, 0, footer);
  4850. }
  4851. function getInjectorIndex(tNode, lView) {
  4852. if (tNode.injectorIndex === -1 ||
  4853. // If the injector index is the same as its parent's injector index, then the index has been
  4854. // copied down from the parent node. No injector has been created yet on this node.
  4855. (tNode.parent && tNode.parent.injectorIndex === tNode.injectorIndex) ||
  4856. // After the first template pass, the injector index might exist but the parent values
  4857. // might not have been calculated yet for this instance
  4858. lView[tNode.injectorIndex + 8 /* NodeInjectorOffset.PARENT */] === null) {
  4859. return -1;
  4860. }
  4861. else {
  4862. ngDevMode && assertIndexInRange(lView, tNode.injectorIndex);
  4863. return tNode.injectorIndex;
  4864. }
  4865. }
  4866. /**
  4867. * Finds the index of the parent injector, with a view offset if applicable. Used to set the
  4868. * parent injector initially.
  4869. *
  4870. * @returns Returns a number that is the combination of the number of LViews that we have to go up
  4871. * to find the LView containing the parent inject AND the index of the injector within that LView.
  4872. */
  4873. function getParentInjectorLocation(tNode, lView) {
  4874. if (tNode.parent && tNode.parent.injectorIndex !== -1) {
  4875. // If we have a parent `TNode` and there is an injector associated with it we are done, because
  4876. // the parent injector is within the current `LView`.
  4877. return tNode.parent.injectorIndex; // ViewOffset is 0
  4878. }
  4879. // When parent injector location is computed it may be outside of the current view. (ie it could
  4880. // be pointing to a declared parent location). This variable stores number of declaration parents
  4881. // we need to walk up in order to find the parent injector location.
  4882. let declarationViewOffset = 0;
  4883. let parentTNode = null;
  4884. let lViewCursor = lView;
  4885. // The parent injector is not in the current `LView`. We will have to walk the declared parent
  4886. // `LView` hierarchy and look for it. If we walk of the top, that means that there is no parent
  4887. // `NodeInjector`.
  4888. while (lViewCursor !== null) {
  4889. parentTNode = getTNodeFromLView(lViewCursor);
  4890. if (parentTNode === null) {
  4891. // If we have no parent, than we are done.
  4892. return NO_PARENT_INJECTOR;
  4893. }
  4894. ngDevMode && parentTNode && assertTNodeForLView(parentTNode, lViewCursor[DECLARATION_VIEW]);
  4895. // Every iteration of the loop requires that we go to the declared parent.
  4896. declarationViewOffset++;
  4897. lViewCursor = lViewCursor[DECLARATION_VIEW];
  4898. if (parentTNode.injectorIndex !== -1) {
  4899. // We found a NodeInjector which points to something.
  4900. return (parentTNode.injectorIndex |
  4901. (declarationViewOffset <<
  4902. 16 /* RelativeInjectorLocationFlags.ViewOffsetShift */));
  4903. }
  4904. }
  4905. return NO_PARENT_INJECTOR;
  4906. }
  4907. /**
  4908. * Makes a type or an injection token public to the DI system by adding it to an
  4909. * injector's bloom filter.
  4910. *
  4911. * @param di The node injector in which a directive will be added
  4912. * @param token The type or the injection token to be made public
  4913. */
  4914. function diPublicInInjector(injectorIndex, tView, token) {
  4915. bloomAdd(injectorIndex, tView, token);
  4916. }
  4917. /**
  4918. * Inject static attribute value into directive constructor.
  4919. *
  4920. * This method is used with `factory` functions which are generated as part of
  4921. * `defineDirective` or `defineComponent`. The method retrieves the static value
  4922. * of an attribute. (Dynamic attributes are not supported since they are not resolved
  4923. * at the time of injection and can change over time.)
  4924. *
  4925. * # Example
  4926. * Given:
  4927. * ```ts
  4928. * @Component(...)
  4929. * class MyComponent {
  4930. * constructor(@Attribute('title') title: string) { ... }
  4931. * }
  4932. * ```
  4933. * When instantiated with
  4934. * ```html
  4935. * <my-component title="Hello"></my-component>
  4936. * ```
  4937. *
  4938. * Then factory method generated is:
  4939. * ```ts
  4940. * MyComponent.ɵcmp = defineComponent({
  4941. * factory: () => new MyComponent(injectAttribute('title'))
  4942. * ...
  4943. * })
  4944. * ```
  4945. *
  4946. * @publicApi
  4947. */
  4948. function injectAttributeImpl(tNode, attrNameToInject) {
  4949. ngDevMode && assertTNodeType(tNode, 12 /* TNodeType.AnyContainer */ | 3 /* TNodeType.AnyRNode */);
  4950. ngDevMode && assertDefined(tNode, 'expecting tNode');
  4951. if (attrNameToInject === 'class') {
  4952. return tNode.classes;
  4953. }
  4954. if (attrNameToInject === 'style') {
  4955. return tNode.styles;
  4956. }
  4957. const attrs = tNode.attrs;
  4958. if (attrs) {
  4959. const attrsLength = attrs.length;
  4960. let i = 0;
  4961. while (i < attrsLength) {
  4962. const value = attrs[i];
  4963. // If we hit a `Bindings` or `Template` marker then we are done.
  4964. if (isNameOnlyAttributeMarker(value))
  4965. break;
  4966. // Skip namespaced attributes
  4967. if (value === 0 /* AttributeMarker.NamespaceURI */) {
  4968. // we skip the next two values
  4969. // as namespaced attributes looks like
  4970. // [..., AttributeMarker.NamespaceURI, 'http://someuri.com/test', 'test:exist',
  4971. // 'existValue', ...]
  4972. i = i + 2;
  4973. }
  4974. else if (typeof value === 'number') {
  4975. // Skip to the first value of the marked attribute.
  4976. i++;
  4977. while (i < attrsLength && typeof attrs[i] === 'string') {
  4978. i++;
  4979. }
  4980. }
  4981. else if (value === attrNameToInject) {
  4982. return attrs[i + 1];
  4983. }
  4984. else {
  4985. i = i + 2;
  4986. }
  4987. }
  4988. }
  4989. return null;
  4990. }
  4991. function notFoundValueOrThrow(notFoundValue, token, flags) {
  4992. if (flags & InjectFlags.Optional || notFoundValue !== undefined) {
  4993. return notFoundValue;
  4994. }
  4995. else {
  4996. throwProviderNotFoundError(token, 'NodeInjector');
  4997. }
  4998. }
  4999. /**
  5000. * Returns the value associated to the given token from the ModuleInjector or throws exception
  5001. *
  5002. * @param lView The `LView` that contains the `tNode`
  5003. * @param token The token to look for
  5004. * @param flags Injection flags
  5005. * @param notFoundValue The value to return when the injection flags is `InjectFlags.Optional`
  5006. * @returns the value from the injector or throws an exception
  5007. */
  5008. function lookupTokenUsingModuleInjector(lView, token, flags, notFoundValue) {
  5009. if (flags & InjectFlags.Optional && notFoundValue === undefined) {
  5010. // This must be set or the NullInjector will throw for optional deps
  5011. notFoundValue = null;
  5012. }
  5013. if ((flags & (InjectFlags.Self | InjectFlags.Host)) === 0) {
  5014. const moduleInjector = lView[INJECTOR];
  5015. // switch to `injectInjectorOnly` implementation for module injector, since module injector
  5016. // should not have access to Component/Directive DI scope (that may happen through
  5017. // `directiveInject` implementation)
  5018. const previousInjectImplementation = setInjectImplementation(undefined);
  5019. try {
  5020. if (moduleInjector) {
  5021. return moduleInjector.get(token, notFoundValue, flags & InjectFlags.Optional);
  5022. }
  5023. else {
  5024. return injectRootLimpMode(token, notFoundValue, flags & InjectFlags.Optional);
  5025. }
  5026. }
  5027. finally {
  5028. setInjectImplementation(previousInjectImplementation);
  5029. }
  5030. }
  5031. return notFoundValueOrThrow(notFoundValue, token, flags);
  5032. }
  5033. /**
  5034. * Returns the value associated to the given token from the NodeInjectors => ModuleInjector.
  5035. *
  5036. * Look for the injector providing the token by walking up the node injector tree and then
  5037. * the module injector tree.
  5038. *
  5039. * This function patches `token` with `__NG_ELEMENT_ID__` which contains the id for the bloom
  5040. * filter. `-1` is reserved for injecting `Injector` (implemented by `NodeInjector`)
  5041. *
  5042. * @param tNode The Node where the search for the injector should start
  5043. * @param lView The `LView` that contains the `tNode`
  5044. * @param token The token to look for
  5045. * @param flags Injection flags
  5046. * @param notFoundValue The value to return when the injection flags is `InjectFlags.Optional`
  5047. * @returns the value from the injector, `null` when not found, or `notFoundValue` if provided
  5048. */
  5049. function getOrCreateInjectable(tNode, lView, token, flags = InjectFlags.Default, notFoundValue) {
  5050. if (tNode !== null) {
  5051. // If the view or any of its ancestors have an embedded
  5052. // view injector, we have to look it up there first.
  5053. if (lView[FLAGS] & 2048 /* LViewFlags.HasEmbeddedViewInjector */ &&
  5054. // The token must be present on the current node injector when the `Self`
  5055. // flag is set, so the lookup on embedded view injector(s) can be skipped.
  5056. !(flags & InjectFlags.Self)) {
  5057. const embeddedInjectorValue = lookupTokenUsingEmbeddedInjector(tNode, lView, token, flags, NOT_FOUND);
  5058. if (embeddedInjectorValue !== NOT_FOUND) {
  5059. return embeddedInjectorValue;
  5060. }
  5061. }
  5062. // Otherwise try the node injector.
  5063. const value = lookupTokenUsingNodeInjector(tNode, lView, token, flags, NOT_FOUND);
  5064. if (value !== NOT_FOUND) {
  5065. return value;
  5066. }
  5067. }
  5068. // Finally, fall back to the module injector.
  5069. return lookupTokenUsingModuleInjector(lView, token, flags, notFoundValue);
  5070. }
  5071. /**
  5072. * Returns the value associated to the given token from the node injector.
  5073. *
  5074. * @param tNode The Node where the search for the injector should start
  5075. * @param lView The `LView` that contains the `tNode`
  5076. * @param token The token to look for
  5077. * @param flags Injection flags
  5078. * @param notFoundValue The value to return when the injection flags is `InjectFlags.Optional`
  5079. * @returns the value from the injector, `null` when not found, or `notFoundValue` if provided
  5080. */
  5081. function lookupTokenUsingNodeInjector(tNode, lView, token, flags, notFoundValue) {
  5082. const bloomHash = bloomHashBitOrFactory(token);
  5083. // If the ID stored here is a function, this is a special object like ElementRef or TemplateRef
  5084. // so just call the factory function to create it.
  5085. if (typeof bloomHash === 'function') {
  5086. if (!enterDI(lView, tNode, flags)) {
  5087. // Failed to enter DI, try module injector instead. If a token is injected with the @Host
  5088. // flag, the module injector is not searched for that token in Ivy.
  5089. return flags & InjectFlags.Host
  5090. ? notFoundValueOrThrow(notFoundValue, token, flags)
  5091. : lookupTokenUsingModuleInjector(lView, token, flags, notFoundValue);
  5092. }
  5093. try {
  5094. let value;
  5095. if (ngDevMode) {
  5096. runInInjectorProfilerContext(new NodeInjector(getCurrentTNode(), getLView()), token, () => {
  5097. value = bloomHash(flags);
  5098. if (value != null) {
  5099. emitInstanceCreatedByInjectorEvent(value);
  5100. }
  5101. });
  5102. }
  5103. else {
  5104. value = bloomHash(flags);
  5105. }
  5106. if (value == null && !(flags & InjectFlags.Optional)) {
  5107. throwProviderNotFoundError(token);
  5108. }
  5109. else {
  5110. return value;
  5111. }
  5112. }
  5113. finally {
  5114. leaveDI();
  5115. }
  5116. }
  5117. else if (typeof bloomHash === 'number') {
  5118. // A reference to the previous injector TView that was found while climbing the element
  5119. // injector tree. This is used to know if viewProviders can be accessed on the current
  5120. // injector.
  5121. let previousTView = null;
  5122. let injectorIndex = getInjectorIndex(tNode, lView);
  5123. let parentLocation = NO_PARENT_INJECTOR;
  5124. let hostTElementNode = flags & InjectFlags.Host ? lView[DECLARATION_COMPONENT_VIEW][T_HOST] : null;
  5125. // If we should skip this injector, or if there is no injector on this node, start by
  5126. // searching the parent injector.
  5127. if (injectorIndex === -1 || flags & InjectFlags.SkipSelf) {
  5128. parentLocation =
  5129. injectorIndex === -1
  5130. ? getParentInjectorLocation(tNode, lView)
  5131. : lView[injectorIndex + 8 /* NodeInjectorOffset.PARENT */];
  5132. if (parentLocation === NO_PARENT_INJECTOR || !shouldSearchParent(flags, false)) {
  5133. injectorIndex = -1;
  5134. }
  5135. else {
  5136. previousTView = lView[TVIEW];
  5137. injectorIndex = getParentInjectorIndex(parentLocation);
  5138. lView = getParentInjectorView(parentLocation, lView);
  5139. }
  5140. }
  5141. // Traverse up the injector tree until we find a potential match or until we know there
  5142. // *isn't* a match.
  5143. while (injectorIndex !== -1) {
  5144. ngDevMode && assertNodeInjector(lView, injectorIndex);
  5145. // Check the current injector. If it matches, see if it contains token.
  5146. const tView = lView[TVIEW];
  5147. ngDevMode &&
  5148. assertTNodeForLView(tView.data[injectorIndex + 8 /* NodeInjectorOffset.TNODE */], lView);
  5149. if (bloomHasToken(bloomHash, injectorIndex, tView.data)) {
  5150. // At this point, we have an injector which *may* contain the token, so we step through
  5151. // the providers and directives associated with the injector's corresponding node to get
  5152. // the instance.
  5153. const instance = searchTokensOnInjector(injectorIndex, lView, token, previousTView, flags, hostTElementNode);
  5154. if (instance !== NOT_FOUND) {
  5155. return instance;
  5156. }
  5157. }
  5158. parentLocation = lView[injectorIndex + 8 /* NodeInjectorOffset.PARENT */];
  5159. if (parentLocation !== NO_PARENT_INJECTOR &&
  5160. shouldSearchParent(flags, lView[TVIEW].data[injectorIndex + 8 /* NodeInjectorOffset.TNODE */] === hostTElementNode) &&
  5161. bloomHasToken(bloomHash, injectorIndex, lView)) {
  5162. // The def wasn't found anywhere on this node, so it was a false positive.
  5163. // Traverse up the tree and continue searching.
  5164. previousTView = tView;
  5165. injectorIndex = getParentInjectorIndex(parentLocation);
  5166. lView = getParentInjectorView(parentLocation, lView);
  5167. }
  5168. else {
  5169. // If we should not search parent OR If the ancestor bloom filter value does not have the
  5170. // bit corresponding to the directive we can give up on traversing up to find the specific
  5171. // injector.
  5172. injectorIndex = -1;
  5173. }
  5174. }
  5175. }
  5176. return notFoundValue;
  5177. }
  5178. function searchTokensOnInjector(injectorIndex, lView, token, previousTView, flags, hostTElementNode) {
  5179. const currentTView = lView[TVIEW];
  5180. const tNode = currentTView.data[injectorIndex + 8 /* NodeInjectorOffset.TNODE */];
  5181. // First, we need to determine if view providers can be accessed by the starting element.
  5182. // There are two possibilities
  5183. const canAccessViewProviders = previousTView == null
  5184. ? // 1) This is the first invocation `previousTView == null` which means that we are at the
  5185. // `TNode` of where injector is starting to look. In such a case the only time we are allowed
  5186. // to look into the ViewProviders is if:
  5187. // - we are on a component
  5188. // - AND the injector set `includeViewProviders` to true (implying that the token can see
  5189. // ViewProviders because it is the Component or a Service which itself was declared in
  5190. // ViewProviders)
  5191. isComponentHost(tNode) && includeViewProviders
  5192. : // 2) `previousTView != null` which means that we are now walking across the parent nodes.
  5193. // In such a case we are only allowed to look into the ViewProviders if:
  5194. // - We just crossed from child View to Parent View `previousTView != currentTView`
  5195. // - AND the parent TNode is an Element.
  5196. // This means that we just came from the Component's View and therefore are allowed to see
  5197. // into the ViewProviders.
  5198. previousTView != currentTView && (tNode.type & 3 /* TNodeType.AnyRNode */) !== 0;
  5199. // This special case happens when there is a @host on the inject and when we are searching
  5200. // on the host element node.
  5201. const isHostSpecialCase = flags & InjectFlags.Host && hostTElementNode === tNode;
  5202. const injectableIdx = locateDirectiveOrProvider(tNode, currentTView, token, canAccessViewProviders, isHostSpecialCase);
  5203. if (injectableIdx !== null) {
  5204. return getNodeInjectable(lView, currentTView, injectableIdx, tNode, flags);
  5205. }
  5206. else {
  5207. return NOT_FOUND;
  5208. }
  5209. }
  5210. /**
  5211. * Searches for the given token among the node's directives and providers.
  5212. *
  5213. * @param tNode TNode on which directives are present.
  5214. * @param tView The tView we are currently processing
  5215. * @param token Provider token or type of a directive to look for.
  5216. * @param canAccessViewProviders Whether view providers should be considered.
  5217. * @param isHostSpecialCase Whether the host special case applies.
  5218. * @returns Index of a found directive or provider, or null when none found.
  5219. */
  5220. function locateDirectiveOrProvider(tNode, tView, token, canAccessViewProviders, isHostSpecialCase) {
  5221. const nodeProviderIndexes = tNode.providerIndexes;
  5222. const tInjectables = tView.data;
  5223. const injectablesStart = nodeProviderIndexes & 1048575 /* TNodeProviderIndexes.ProvidersStartIndexMask */;
  5224. const directivesStart = tNode.directiveStart;
  5225. const directiveEnd = tNode.directiveEnd;
  5226. const cptViewProvidersCount = nodeProviderIndexes >> 20 /* TNodeProviderIndexes.CptViewProvidersCountShift */;
  5227. const startingIndex = canAccessViewProviders
  5228. ? injectablesStart
  5229. : injectablesStart + cptViewProvidersCount;
  5230. // When the host special case applies, only the viewProviders and the component are visible
  5231. const endIndex = isHostSpecialCase ? injectablesStart + cptViewProvidersCount : directiveEnd;
  5232. for (let i = startingIndex; i < endIndex; i++) {
  5233. const providerTokenOrDef = tInjectables[i];
  5234. if ((i < directivesStart && token === providerTokenOrDef) ||
  5235. (i >= directivesStart && providerTokenOrDef.type === token)) {
  5236. return i;
  5237. }
  5238. }
  5239. if (isHostSpecialCase) {
  5240. const dirDef = tInjectables[directivesStart];
  5241. if (dirDef && isComponentDef(dirDef) && dirDef.type === token) {
  5242. return directivesStart;
  5243. }
  5244. }
  5245. return null;
  5246. }
  5247. /**
  5248. * Retrieve or instantiate the injectable from the `LView` at particular `index`.
  5249. *
  5250. * This function checks to see if the value has already been instantiated and if so returns the
  5251. * cached `injectable`. Otherwise if it detects that the value is still a factory it
  5252. * instantiates the `injectable` and caches the value.
  5253. */
  5254. function getNodeInjectable(lView, tView, index, tNode, flags) {
  5255. let value = lView[index];
  5256. const tData = tView.data;
  5257. if (value instanceof NodeInjectorFactory) {
  5258. const factory = value;
  5259. if (factory.resolving) {
  5260. throwCyclicDependencyError(stringifyForError(tData[index]));
  5261. }
  5262. const previousIncludeViewProviders = setIncludeViewProviders(factory.canSeeViewProviders);
  5263. factory.resolving = true;
  5264. let prevInjectContext;
  5265. if (ngDevMode) {
  5266. // tData indexes mirror the concrete instances in its corresponding LView.
  5267. // lView[index] here is either the injectable instace itself or a factory,
  5268. // therefore tData[index] is the constructor of that injectable or a
  5269. // definition object that contains the constructor in a `.type` field.
  5270. const token = tData[index].type || tData[index];
  5271. const injector = new NodeInjector(tNode, lView);
  5272. prevInjectContext = setInjectorProfilerContext({ injector, token });
  5273. }
  5274. const previousInjectImplementation = factory.injectImpl
  5275. ? setInjectImplementation(factory.injectImpl)
  5276. : null;
  5277. const success = enterDI(lView, tNode, InjectFlags.Default);
  5278. ngDevMode &&
  5279. assertEqual(success, true, "Because flags do not contain `SkipSelf' we expect this to always succeed.");
  5280. try {
  5281. value = lView[index] = factory.factory(undefined, flags, tData, lView, tNode);
  5282. ngDevMode && emitInstanceCreatedByInjectorEvent(value);
  5283. // This code path is hit for both directives and providers.
  5284. // For perf reasons, we want to avoid searching for hooks on providers.
  5285. // It does no harm to try (the hooks just won't exist), but the extra
  5286. // checks are unnecessary and this is a hot path. So we check to see
  5287. // if the index of the dependency is in the directive range for this
  5288. // tNode. If it's not, we know it's a provider and skip hook registration.
  5289. if (tView.firstCreatePass && index >= tNode.directiveStart) {
  5290. ngDevMode && assertDirectiveDef(tData[index]);
  5291. registerPreOrderHooks(index, tData[index], tView);
  5292. }
  5293. }
  5294. finally {
  5295. ngDevMode && setInjectorProfilerContext(prevInjectContext);
  5296. previousInjectImplementation !== null &&
  5297. setInjectImplementation(previousInjectImplementation);
  5298. setIncludeViewProviders(previousIncludeViewProviders);
  5299. factory.resolving = false;
  5300. leaveDI();
  5301. }
  5302. }
  5303. return value;
  5304. }
  5305. /**
  5306. * Returns the bit in an injector's bloom filter that should be used to determine whether or not
  5307. * the directive might be provided by the injector.
  5308. *
  5309. * When a directive is public, it is added to the bloom filter and given a unique ID that can be
  5310. * retrieved on the Type. When the directive isn't public or the token is not a directive `null`
  5311. * is returned as the node injector can not possibly provide that token.
  5312. *
  5313. * @param token the injection token
  5314. * @returns the matching bit to check in the bloom filter or `null` if the token is not known.
  5315. * When the returned value is negative then it represents special values such as `Injector`.
  5316. */
  5317. function bloomHashBitOrFactory(token) {
  5318. ngDevMode && assertDefined(token, 'token must be defined');
  5319. if (typeof token === 'string') {
  5320. return token.charCodeAt(0) || 0;
  5321. }
  5322. const tokenId =
  5323. // First check with `hasOwnProperty` so we don't get an inherited ID.
  5324. token.hasOwnProperty(NG_ELEMENT_ID) ? token[NG_ELEMENT_ID] : undefined;
  5325. // Negative token IDs are used for special objects such as `Injector`
  5326. if (typeof tokenId === 'number') {
  5327. if (tokenId >= 0) {
  5328. return tokenId & BLOOM_MASK;
  5329. }
  5330. else {
  5331. ngDevMode &&
  5332. assertEqual(tokenId, -1 /* InjectorMarkers.Injector */, 'Expecting to get Special Injector Id');
  5333. return createNodeInjector;
  5334. }
  5335. }
  5336. else {
  5337. return tokenId;
  5338. }
  5339. }
  5340. function bloomHasToken(bloomHash, injectorIndex, injectorView) {
  5341. // Create a mask that targets the specific bit associated with the directive we're looking for.
  5342. // JS bit operations are 32 bits, so this will be a number between 2^0 and 2^31, corresponding
  5343. // to bit positions 0 - 31 in a 32 bit integer.
  5344. const mask = 1 << bloomHash;
  5345. // Each bloom bucket in `injectorView` represents `BLOOM_BUCKET_BITS` number of bits of
  5346. // `bloomHash`. Any bits in `bloomHash` beyond `BLOOM_BUCKET_BITS` indicate the bucket offset
  5347. // that should be used.
  5348. const value = injectorView[injectorIndex + (bloomHash >> BLOOM_BUCKET_BITS)];
  5349. // If the bloom filter value has the bit corresponding to the directive's bloomBit flipped on,
  5350. // this injector is a potential match.
  5351. return !!(value & mask);
  5352. }
  5353. /** Returns true if flags prevent parent injector from being searched for tokens */
  5354. function shouldSearchParent(flags, isFirstHostTNode) {
  5355. return !(flags & InjectFlags.Self) && !(flags & InjectFlags.Host && isFirstHostTNode);
  5356. }
  5357. function getNodeInjectorLView(nodeInjector) {
  5358. return nodeInjector._lView;
  5359. }
  5360. function getNodeInjectorTNode(nodeInjector) {
  5361. return nodeInjector._tNode;
  5362. }
  5363. class NodeInjector {
  5364. _tNode;
  5365. _lView;
  5366. constructor(_tNode, _lView) {
  5367. this._tNode = _tNode;
  5368. this._lView = _lView;
  5369. }
  5370. get(token, notFoundValue, flags) {
  5371. return getOrCreateInjectable(this._tNode, this._lView, token, convertToBitFlags(flags), notFoundValue);
  5372. }
  5373. }
  5374. /** Creates a `NodeInjector` for the current node. */
  5375. function createNodeInjector() {
  5376. return new NodeInjector(getCurrentTNode(), getLView());
  5377. }
  5378. /**
  5379. * @codeGenApi
  5380. */
  5381. function ɵɵgetInheritedFactory(type) {
  5382. return noSideEffects(() => {
  5383. const ownConstructor = type.prototype.constructor;
  5384. const ownFactory = ownConstructor[NG_FACTORY_DEF] || getFactoryOf(ownConstructor);
  5385. const objectPrototype = Object.prototype;
  5386. let parent = Object.getPrototypeOf(type.prototype).constructor;
  5387. // Go up the prototype until we hit `Object`.
  5388. while (parent && parent !== objectPrototype) {
  5389. const factory = parent[NG_FACTORY_DEF] || getFactoryOf(parent);
  5390. // If we hit something that has a factory and the factory isn't the same as the type,
  5391. // we've found the inherited factory. Note the check that the factory isn't the type's
  5392. // own factory is redundant in most cases, but if the user has custom decorators on the
  5393. // class, this lookup will start one level down in the prototype chain, causing us to
  5394. // find the own factory first and potentially triggering an infinite loop downstream.
  5395. if (factory && factory !== ownFactory) {
  5396. return factory;
  5397. }
  5398. parent = Object.getPrototypeOf(parent);
  5399. }
  5400. // There is no factory defined. Either this was improper usage of inheritance
  5401. // (no Angular decorator on the superclass) or there is no constructor at all
  5402. // in the inheritance chain. Since the two cases cannot be distinguished, the
  5403. // latter has to be assumed.
  5404. return (t) => new t();
  5405. });
  5406. }
  5407. function getFactoryOf(type) {
  5408. if (isForwardRef(type)) {
  5409. return () => {
  5410. const factory = getFactoryOf(resolveForwardRef(type));
  5411. return factory && factory();
  5412. };
  5413. }
  5414. return getFactoryDef(type);
  5415. }
  5416. /**
  5417. * Returns a value from the closest embedded or node injector.
  5418. *
  5419. * @param tNode The Node where the search for the injector should start
  5420. * @param lView The `LView` that contains the `tNode`
  5421. * @param token The token to look for
  5422. * @param flags Injection flags
  5423. * @param notFoundValue The value to return when the injection flags is `InjectFlags.Optional`
  5424. * @returns the value from the injector, `null` when not found, or `notFoundValue` if provided
  5425. */
  5426. function lookupTokenUsingEmbeddedInjector(tNode, lView, token, flags, notFoundValue) {
  5427. let currentTNode = tNode;
  5428. let currentLView = lView;
  5429. // When an LView with an embedded view injector is inserted, it'll likely be interlaced with
  5430. // nodes who may have injectors (e.g. node injector -> embedded view injector -> node injector).
  5431. // Since the bloom filters for the node injectors have already been constructed and we don't
  5432. // have a way of extracting the records from an injector, the only way to maintain the correct
  5433. // hierarchy when resolving the value is to walk it node-by-node while attempting to resolve
  5434. // the token at each level.
  5435. while (currentTNode !== null &&
  5436. currentLView !== null &&
  5437. currentLView[FLAGS] & 2048 /* LViewFlags.HasEmbeddedViewInjector */ &&
  5438. !isRootView(currentLView)) {
  5439. ngDevMode && assertTNodeForLView(currentTNode, currentLView);
  5440. // Note that this lookup on the node injector is using the `Self` flag, because
  5441. // we don't want the node injector to look at any parent injectors since we
  5442. // may hit the embedded view injector first.
  5443. const nodeInjectorValue = lookupTokenUsingNodeInjector(currentTNode, currentLView, token, flags | InjectFlags.Self, NOT_FOUND);
  5444. if (nodeInjectorValue !== NOT_FOUND) {
  5445. return nodeInjectorValue;
  5446. }
  5447. // Has an explicit type due to a TS bug: https://github.com/microsoft/TypeScript/issues/33191
  5448. let parentTNode = currentTNode.parent;
  5449. // `TNode.parent` includes the parent within the current view only. If it doesn't exist,
  5450. // it means that we've hit the view boundary and we need to go up to the next view.
  5451. if (!parentTNode) {
  5452. // Before we go to the next LView, check if the token exists on the current embedded injector.
  5453. const embeddedViewInjector = currentLView[EMBEDDED_VIEW_INJECTOR];
  5454. if (embeddedViewInjector) {
  5455. const embeddedViewInjectorValue = embeddedViewInjector.get(token, NOT_FOUND, flags);
  5456. if (embeddedViewInjectorValue !== NOT_FOUND) {
  5457. return embeddedViewInjectorValue;
  5458. }
  5459. }
  5460. // Otherwise keep going up the tree.
  5461. parentTNode = getTNodeFromLView(currentLView);
  5462. currentLView = currentLView[DECLARATION_VIEW];
  5463. }
  5464. currentTNode = parentTNode;
  5465. }
  5466. return notFoundValue;
  5467. }
  5468. /** Gets the TNode associated with an LView inside of the declaration view. */
  5469. function getTNodeFromLView(lView) {
  5470. const tView = lView[TVIEW];
  5471. const tViewType = tView.type;
  5472. // The parent pointer differs based on `TView.type`.
  5473. if (tViewType === 2 /* TViewType.Embedded */) {
  5474. ngDevMode && assertDefined(tView.declTNode, 'Embedded TNodes should have declaration parents.');
  5475. return tView.declTNode;
  5476. }
  5477. else if (tViewType === 1 /* TViewType.Component */) {
  5478. // Components don't have `TView.declTNode` because each instance of component could be
  5479. // inserted in different location, hence `TView.declTNode` is meaningless.
  5480. return lView[T_HOST];
  5481. }
  5482. return null;
  5483. }
  5484. /**
  5485. * Facade for the attribute injection from DI.
  5486. *
  5487. * @codeGenApi
  5488. */
  5489. function ɵɵinjectAttribute(attrNameToInject) {
  5490. return injectAttributeImpl(getCurrentTNode(), attrNameToInject);
  5491. }
  5492. /**
  5493. * Attribute decorator and metadata.
  5494. *
  5495. * @Annotation
  5496. * @publicApi
  5497. */
  5498. const Attribute = makeParamDecorator('Attribute', (attributeName) => ({
  5499. attributeName,
  5500. __NG_ELEMENT_ID__: () => ɵɵinjectAttribute(attributeName),
  5501. }));
  5502. let _reflect = null;
  5503. function getReflect() {
  5504. return (_reflect = _reflect || new ReflectionCapabilities());
  5505. }
  5506. function reflectDependencies(type) {
  5507. return convertDependencies(getReflect().parameters(type));
  5508. }
  5509. function convertDependencies(deps) {
  5510. return deps.map((dep) => reflectDependency(dep));
  5511. }
  5512. function reflectDependency(dep) {
  5513. const meta = {
  5514. token: null,
  5515. attribute: null,
  5516. host: false,
  5517. optional: false,
  5518. self: false,
  5519. skipSelf: false,
  5520. };
  5521. if (Array.isArray(dep) && dep.length > 0) {
  5522. for (let j = 0; j < dep.length; j++) {
  5523. const param = dep[j];
  5524. if (param === undefined) {
  5525. // param may be undefined if type of dep is not set by ngtsc
  5526. continue;
  5527. }
  5528. const proto = Object.getPrototypeOf(param);
  5529. if (param instanceof Optional || proto.ngMetadataName === 'Optional') {
  5530. meta.optional = true;
  5531. }
  5532. else if (param instanceof SkipSelf || proto.ngMetadataName === 'SkipSelf') {
  5533. meta.skipSelf = true;
  5534. }
  5535. else if (param instanceof Self || proto.ngMetadataName === 'Self') {
  5536. meta.self = true;
  5537. }
  5538. else if (param instanceof Host || proto.ngMetadataName === 'Host') {
  5539. meta.host = true;
  5540. }
  5541. else if (param instanceof Inject) {
  5542. meta.token = param.token;
  5543. }
  5544. else if (param instanceof Attribute) {
  5545. if (param.attributeName === undefined) {
  5546. throw new RuntimeError(204 /* RuntimeErrorCode.INVALID_INJECTION_TOKEN */, ngDevMode && `Attribute name must be defined.`);
  5547. }
  5548. meta.attribute = param.attributeName;
  5549. }
  5550. else {
  5551. meta.token = param;
  5552. }
  5553. }
  5554. }
  5555. else if (dep === undefined || (Array.isArray(dep) && dep.length === 0)) {
  5556. meta.token = null;
  5557. }
  5558. else {
  5559. meta.token = dep;
  5560. }
  5561. return meta;
  5562. }
  5563. /**
  5564. * Compile an Angular injectable according to its `Injectable` metadata, and patch the resulting
  5565. * injectable def (`ɵprov`) onto the injectable type.
  5566. */
  5567. function compileInjectable(type, meta) {
  5568. let ngInjectableDef = null;
  5569. let ngFactoryDef = null;
  5570. // if NG_PROV_DEF is already defined on this class then don't overwrite it
  5571. if (!type.hasOwnProperty(NG_PROV_DEF)) {
  5572. Object.defineProperty(type, NG_PROV_DEF, {
  5573. get: () => {
  5574. if (ngInjectableDef === null) {
  5575. const compiler = getCompilerFacade({
  5576. usage: 0 /* JitCompilerUsage.Decorator */,
  5577. kind: 'injectable',
  5578. type,
  5579. });
  5580. ngInjectableDef = compiler.compileInjectable(angularCoreDiEnv, `ng:///${type.name}/ɵprov.js`, getInjectableMetadata(type, meta));
  5581. }
  5582. return ngInjectableDef;
  5583. },
  5584. });
  5585. }
  5586. // if NG_FACTORY_DEF is already defined on this class then don't overwrite it
  5587. if (!type.hasOwnProperty(NG_FACTORY_DEF)) {
  5588. Object.defineProperty(type, NG_FACTORY_DEF, {
  5589. get: () => {
  5590. if (ngFactoryDef === null) {
  5591. const compiler = getCompilerFacade({
  5592. usage: 0 /* JitCompilerUsage.Decorator */,
  5593. kind: 'injectable',
  5594. type,
  5595. });
  5596. ngFactoryDef = compiler.compileFactory(angularCoreDiEnv, `ng:///${type.name}/ɵfac.js`, {
  5597. name: type.name,
  5598. type,
  5599. typeArgumentCount: 0, // In JIT mode types are not available nor used.
  5600. deps: reflectDependencies(type),
  5601. target: compiler.FactoryTarget.Injectable,
  5602. });
  5603. }
  5604. return ngFactoryDef;
  5605. },
  5606. // Leave this configurable so that the factories from directives or pipes can take precedence.
  5607. configurable: true,
  5608. });
  5609. }
  5610. }
  5611. const USE_VALUE = getClosureSafeProperty({
  5612. provide: String,
  5613. useValue: getClosureSafeProperty,
  5614. });
  5615. function isUseClassProvider(meta) {
  5616. return meta.useClass !== undefined;
  5617. }
  5618. function isUseValueProvider(meta) {
  5619. return USE_VALUE in meta;
  5620. }
  5621. function isUseFactoryProvider(meta) {
  5622. return meta.useFactory !== undefined;
  5623. }
  5624. function isUseExistingProvider(meta) {
  5625. return meta.useExisting !== undefined;
  5626. }
  5627. function getInjectableMetadata(type, srcMeta) {
  5628. // Allow the compilation of a class with a `@Injectable()` decorator without parameters
  5629. const meta = srcMeta || { providedIn: null };
  5630. const compilerMeta = {
  5631. name: type.name,
  5632. type: type,
  5633. typeArgumentCount: 0,
  5634. providedIn: meta.providedIn,
  5635. };
  5636. if ((isUseClassProvider(meta) || isUseFactoryProvider(meta)) && meta.deps !== undefined) {
  5637. compilerMeta.deps = convertDependencies(meta.deps);
  5638. }
  5639. // Check to see if the user explicitly provided a `useXxxx` property.
  5640. if (isUseClassProvider(meta)) {
  5641. compilerMeta.useClass = meta.useClass;
  5642. }
  5643. else if (isUseValueProvider(meta)) {
  5644. compilerMeta.useValue = meta.useValue;
  5645. }
  5646. else if (isUseFactoryProvider(meta)) {
  5647. compilerMeta.useFactory = meta.useFactory;
  5648. }
  5649. else if (isUseExistingProvider(meta)) {
  5650. compilerMeta.useExisting = meta.useExisting;
  5651. }
  5652. return compilerMeta;
  5653. }
  5654. /**
  5655. * Injectable decorator and metadata.
  5656. *
  5657. * @Annotation
  5658. * @publicApi
  5659. */
  5660. const Injectable = makeDecorator('Injectable', undefined, undefined, undefined, (type, meta) => compileInjectable(type, meta));
  5661. /**
  5662. * Create a new `Injector` which is configured using a `defType` of `InjectorType<any>`s.
  5663. */
  5664. function createInjector(defType, parent = null, additionalProviders = null, name) {
  5665. const injector = createInjectorWithoutInjectorInstances(defType, parent, additionalProviders, name);
  5666. injector.resolveInjectorInitializers();
  5667. return injector;
  5668. }
  5669. /**
  5670. * Creates a new injector without eagerly resolving its injector types. Can be used in places
  5671. * where resolving the injector types immediately can lead to an infinite loop. The injector types
  5672. * should be resolved at a later point by calling `_resolveInjectorDefTypes`.
  5673. */
  5674. function createInjectorWithoutInjectorInstances(defType, parent = null, additionalProviders = null, name, scopes = new Set()) {
  5675. const providers = [additionalProviders || EMPTY_ARRAY, importProvidersFrom(defType)];
  5676. name = name || (typeof defType === 'object' ? undefined : stringify(defType));
  5677. return new R3Injector(providers, parent || getNullInjector(), name || null, scopes);
  5678. }
  5679. /**
  5680. * Concrete injectors implement this interface. Injectors are configured
  5681. * with [providers](guide/di/dependency-injection-providers) that associate
  5682. * dependencies of various types with [injection tokens](guide/di/dependency-injection-providers).
  5683. *
  5684. * @see [DI Providers](guide/di/dependency-injection-providers).
  5685. * @see {@link StaticProvider}
  5686. *
  5687. * @usageNotes
  5688. *
  5689. * The following example creates a service injector instance.
  5690. *
  5691. * {@example core/di/ts/provider_spec.ts region='ConstructorProvider'}
  5692. *
  5693. * ### Usage example
  5694. *
  5695. * {@example core/di/ts/injector_spec.ts region='Injector'}
  5696. *
  5697. * `Injector` returns itself when given `Injector` as a token:
  5698. *
  5699. * {@example core/di/ts/injector_spec.ts region='injectInjector'}
  5700. *
  5701. * @publicApi
  5702. */
  5703. class Injector {
  5704. static THROW_IF_NOT_FOUND = THROW_IF_NOT_FOUND;
  5705. static NULL = new NullInjector();
  5706. static create(options, parent) {
  5707. if (Array.isArray(options)) {
  5708. return createInjector({ name: '' }, parent, options, '');
  5709. }
  5710. else {
  5711. const name = options.name ?? '';
  5712. return createInjector({ name }, options.parent, options.providers, name);
  5713. }
  5714. }
  5715. /** @nocollapse */
  5716. static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
  5717. token: Injector,
  5718. providedIn: 'any',
  5719. factory: () => ɵɵinject(INJECTOR$1),
  5720. });
  5721. /**
  5722. * @internal
  5723. * @nocollapse
  5724. */
  5725. static __NG_ELEMENT_ID__ = -1 /* InjectorMarkers.Injector */;
  5726. }
  5727. /*!
  5728. * @license
  5729. * Copyright Google LLC All Rights Reserved.
  5730. *
  5731. * Use of this source code is governed by an MIT-style license that can be
  5732. * found in the LICENSE file at https://angular.dev/license
  5733. */
  5734. /**
  5735. * Creates a token that can be used to inject static attributes of the host node.
  5736. *
  5737. * @usageNotes
  5738. * ### Injecting an attribute that is known to exist
  5739. * ```ts
  5740. * @Directive()
  5741. * class MyDir {
  5742. * attr: string = inject(new HostAttributeToken('some-attr'));
  5743. * }
  5744. * ```
  5745. *
  5746. * ### Optionally injecting an attribute
  5747. * ```ts
  5748. * @Directive()
  5749. * class MyDir {
  5750. * attr: string | null = inject(new HostAttributeToken('some-attr'), {optional: true});
  5751. * }
  5752. * ```
  5753. * @publicApi
  5754. */
  5755. class HostAttributeToken {
  5756. attributeName;
  5757. constructor(attributeName) {
  5758. this.attributeName = attributeName;
  5759. }
  5760. /** @internal */
  5761. __NG_ELEMENT_ID__ = () => ɵɵinjectAttribute(this.attributeName);
  5762. toString() {
  5763. return `HostAttributeToken ${this.attributeName}`;
  5764. }
  5765. }
  5766. /**
  5767. * A token that can be used to inject the tag name of the host node.
  5768. *
  5769. * @usageNotes
  5770. * ### Injecting a tag name that is known to exist
  5771. * ```ts
  5772. * @Directive()
  5773. * class MyDir {
  5774. * tagName: string = inject(HOST_TAG_NAME);
  5775. * }
  5776. * ```
  5777. *
  5778. * ### Optionally injecting a tag name
  5779. * ```ts
  5780. * @Directive()
  5781. * class MyDir {
  5782. * tagName: string | null = inject(HOST_TAG_NAME, {optional: true});
  5783. * }
  5784. * ```
  5785. * @publicApi
  5786. */
  5787. const HOST_TAG_NAME = new InjectionToken(ngDevMode ? 'HOST_TAG_NAME' : '');
  5788. // HOST_TAG_NAME should be resolved at the current node, similar to e.g. ElementRef,
  5789. // so we manually specify __NG_ELEMENT_ID__ here, instead of using a factory.
  5790. // tslint:disable-next-line:no-toplevel-property-access
  5791. HOST_TAG_NAME.__NG_ELEMENT_ID__ = (flags) => {
  5792. const tNode = getCurrentTNode();
  5793. if (tNode === null) {
  5794. throw new RuntimeError(204 /* RuntimeErrorCode.INVALID_INJECTION_TOKEN */, ngDevMode &&
  5795. 'HOST_TAG_NAME can only be injected in directives and components ' +
  5796. 'during construction time (in a class constructor or as a class field initializer)');
  5797. }
  5798. if (tNode.type & 2 /* TNodeType.Element */) {
  5799. return tNode.value;
  5800. }
  5801. if (flags & InjectFlags.Optional) {
  5802. return null;
  5803. }
  5804. throw new RuntimeError(204 /* RuntimeErrorCode.INVALID_INJECTION_TOKEN */, ngDevMode &&
  5805. `HOST_TAG_NAME was used on ${getDevModeNodeName(tNode)} which doesn't have an underlying element in the DOM. ` +
  5806. `This is invalid, and so the dependency should be marked as optional.`);
  5807. };
  5808. function getDevModeNodeName(tNode) {
  5809. if (tNode.type & 8 /* TNodeType.ElementContainer */) {
  5810. return 'an <ng-container>';
  5811. }
  5812. else if (tNode.type & 4 /* TNodeType.Container */) {
  5813. return 'an <ng-template>';
  5814. }
  5815. else if (tNode.type & 128 /* TNodeType.LetDeclaration */) {
  5816. return 'an @let declaration';
  5817. }
  5818. else {
  5819. return 'a node';
  5820. }
  5821. }
  5822. const SCHEDULE_IN_ROOT_ZONE_DEFAULT = false;
  5823. /**
  5824. * `DestroyRef` lets you set callbacks to run for any cleanup or destruction behavior.
  5825. * The scope of this destruction depends on where `DestroyRef` is injected. If `DestroyRef`
  5826. * is injected in a component or directive, the callbacks run when that component or
  5827. * directive is destroyed. Otherwise the callbacks run when a corresponding injector is destroyed.
  5828. *
  5829. * @publicApi
  5830. */
  5831. class DestroyRef {
  5832. /**
  5833. * @internal
  5834. * @nocollapse
  5835. */
  5836. static __NG_ELEMENT_ID__ = injectDestroyRef;
  5837. /**
  5838. * @internal
  5839. * @nocollapse
  5840. */
  5841. static __NG_ENV_ID__ = (injector) => injector;
  5842. }
  5843. class NodeInjectorDestroyRef extends DestroyRef {
  5844. _lView;
  5845. constructor(_lView) {
  5846. super();
  5847. this._lView = _lView;
  5848. }
  5849. onDestroy(callback) {
  5850. const lView = this._lView;
  5851. // Checking if `lView` is already destroyed before storing the `callback` enhances
  5852. // safety and integrity for applications.
  5853. // If `lView` is destroyed, we call the `callback` immediately to ensure that
  5854. // any necessary cleanup is handled gracefully.
  5855. // With this approach, we're providing better reliability in managing resources.
  5856. // One of the use cases is `takeUntilDestroyed`, which aims to replace `takeUntil`
  5857. // in existing applications. While `takeUntil` can be safely called once the view
  5858. // is destroyed — resulting in no errors and finalizing the subscription depending
  5859. // on whether a subject or replay subject is used, replacing it with
  5860. // `takeUntilDestroyed` introduces a breaking change, as it throws an error if
  5861. // the `lView` is destroyed (https://github.com/angular/angular/issues/54527).
  5862. if (isDestroyed(lView)) {
  5863. callback();
  5864. // We return a "noop" callback, which, when executed, does nothing because
  5865. // we haven't stored anything on the `lView`, and thus there's nothing to remove.
  5866. return () => { };
  5867. }
  5868. storeLViewOnDestroy(lView, callback);
  5869. return () => removeLViewOnDestroy(lView, callback);
  5870. }
  5871. }
  5872. function injectDestroyRef() {
  5873. return new NodeInjectorDestroyRef(getLView());
  5874. }
  5875. /**
  5876. * Injectable that is notified when an `LView` is made aware of changes to application state.
  5877. */
  5878. class ChangeDetectionScheduler {
  5879. }
  5880. /** Token used to indicate if zoneless was enabled via provideZonelessChangeDetection(). */
  5881. const ZONELESS_ENABLED = new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'Zoneless enabled' : '', { providedIn: 'root', factory: () => false });
  5882. /** Token used to indicate `provideExperimentalZonelessChangeDetection` was used. */
  5883. const PROVIDED_ZONELESS = new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'Zoneless provided' : '', { providedIn: 'root', factory: () => false });
  5884. const ZONELESS_SCHEDULER_DISABLED = new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'scheduler disabled' : '');
  5885. // TODO(atscott): Remove in v19. Scheduler should be done with runOutsideAngular.
  5886. const SCHEDULE_IN_ROOT_ZONE = new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'run changes outside zone in root' : '');
  5887. /**
  5888. * Internal implementation of the pending tasks service.
  5889. */
  5890. class PendingTasksInternal {
  5891. taskId = 0;
  5892. pendingTasks = new Set();
  5893. get _hasPendingTasks() {
  5894. return this.hasPendingTasks.value;
  5895. }
  5896. hasPendingTasks = new BehaviorSubject(false);
  5897. add() {
  5898. if (!this._hasPendingTasks) {
  5899. this.hasPendingTasks.next(true);
  5900. }
  5901. const taskId = this.taskId++;
  5902. this.pendingTasks.add(taskId);
  5903. return taskId;
  5904. }
  5905. has(taskId) {
  5906. return this.pendingTasks.has(taskId);
  5907. }
  5908. remove(taskId) {
  5909. this.pendingTasks.delete(taskId);
  5910. if (this.pendingTasks.size === 0 && this._hasPendingTasks) {
  5911. this.hasPendingTasks.next(false);
  5912. }
  5913. }
  5914. ngOnDestroy() {
  5915. this.pendingTasks.clear();
  5916. if (this._hasPendingTasks) {
  5917. this.hasPendingTasks.next(false);
  5918. }
  5919. }
  5920. /** @nocollapse */
  5921. static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
  5922. token: PendingTasksInternal,
  5923. providedIn: 'root',
  5924. factory: () => new PendingTasksInternal(),
  5925. });
  5926. }
  5927. /**
  5928. * Service that keeps track of pending tasks contributing to the stableness of Angular
  5929. * application. While several existing Angular services (ex.: `HttpClient`) will internally manage
  5930. * tasks influencing stability, this API gives control over stability to library and application
  5931. * developers for specific cases not covered by Angular internals.
  5932. *
  5933. * The concept of stability comes into play in several important scenarios:
  5934. * - SSR process needs to wait for the application stability before serializing and sending rendered
  5935. * HTML;
  5936. * - tests might want to delay assertions until the application becomes stable;
  5937. *
  5938. * @usageNotes
  5939. * ```ts
  5940. * const pendingTasks = inject(PendingTasks);
  5941. * const taskCleanup = pendingTasks.add();
  5942. * // do work that should block application's stability and then:
  5943. * taskCleanup();
  5944. * ```
  5945. *
  5946. * @publicApi
  5947. * @developerPreview
  5948. */
  5949. class PendingTasks {
  5950. internalPendingTasks = inject(PendingTasksInternal);
  5951. scheduler = inject(ChangeDetectionScheduler);
  5952. /**
  5953. * Adds a new task that should block application's stability.
  5954. * @returns A cleanup function that removes a task when called.
  5955. */
  5956. add() {
  5957. const taskId = this.internalPendingTasks.add();
  5958. return () => {
  5959. if (!this.internalPendingTasks.has(taskId)) {
  5960. // This pending task has already been cleared.
  5961. return;
  5962. }
  5963. // Notifying the scheduler will hold application stability open until the next tick.
  5964. this.scheduler.notify(11 /* NotificationSource.PendingTaskRemoved */);
  5965. this.internalPendingTasks.remove(taskId);
  5966. };
  5967. }
  5968. /**
  5969. * Runs an asynchronous function and blocks the application's stability until the function completes.
  5970. *
  5971. * ```ts
  5972. * pendingTasks.run(async () => {
  5973. * const userData = await fetch('/api/user');
  5974. * this.userData.set(userData);
  5975. * });
  5976. * ```
  5977. *
  5978. * Application stability is at least delayed until the next tick after the `run` method resolves
  5979. * so it is safe to make additional updates to application state that would require UI synchronization:
  5980. *
  5981. * ```ts
  5982. * const userData = await pendingTasks.run(() => fetch('/api/user'));
  5983. * this.userData.set(userData);
  5984. * ```
  5985. *
  5986. * @param fn The asynchronous function to execute
  5987. */
  5988. async run(fn) {
  5989. const removeTask = this.add();
  5990. try {
  5991. return await fn();
  5992. }
  5993. finally {
  5994. removeTask();
  5995. }
  5996. }
  5997. /** @nocollapse */
  5998. static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
  5999. token: PendingTasks,
  6000. providedIn: 'root',
  6001. factory: () => new PendingTasks(),
  6002. });
  6003. }
  6004. class EventEmitter_ extends Subject {
  6005. // tslint:disable-next-line:require-internal-with-underscore
  6006. __isAsync;
  6007. destroyRef = undefined;
  6008. pendingTasks = undefined;
  6009. constructor(isAsync = false) {
  6010. super();
  6011. this.__isAsync = isAsync;
  6012. // Attempt to retrieve a `DestroyRef` and `PendingTasks` optionally.
  6013. // For backwards compatibility reasons, this cannot be required.
  6014. if (isInInjectionContext()) {
  6015. // `DestroyRef` is optional because it is not available in all contexts.
  6016. // But it is useful to properly complete the `EventEmitter` if used with `outputToObservable`
  6017. // when the component/directive is destroyed. (See `outputToObservable` for more details.)
  6018. this.destroyRef = inject(DestroyRef, { optional: true }) ?? undefined;
  6019. this.pendingTasks = inject(PendingTasksInternal, { optional: true }) ?? undefined;
  6020. }
  6021. }
  6022. emit(value) {
  6023. const prevConsumer = setActiveConsumer$1(null);
  6024. try {
  6025. super.next(value);
  6026. }
  6027. finally {
  6028. setActiveConsumer$1(prevConsumer);
  6029. }
  6030. }
  6031. subscribe(observerOrNext, error, complete) {
  6032. let nextFn = observerOrNext;
  6033. let errorFn = error || (() => null);
  6034. let completeFn = complete;
  6035. if (observerOrNext && typeof observerOrNext === 'object') {
  6036. const observer = observerOrNext;
  6037. nextFn = observer.next?.bind(observer);
  6038. errorFn = observer.error?.bind(observer);
  6039. completeFn = observer.complete?.bind(observer);
  6040. }
  6041. if (this.__isAsync) {
  6042. errorFn = this.wrapInTimeout(errorFn);
  6043. if (nextFn) {
  6044. nextFn = this.wrapInTimeout(nextFn);
  6045. }
  6046. if (completeFn) {
  6047. completeFn = this.wrapInTimeout(completeFn);
  6048. }
  6049. }
  6050. const sink = super.subscribe({ next: nextFn, error: errorFn, complete: completeFn });
  6051. if (observerOrNext instanceof Subscription) {
  6052. observerOrNext.add(sink);
  6053. }
  6054. return sink;
  6055. }
  6056. wrapInTimeout(fn) {
  6057. return (value) => {
  6058. const taskId = this.pendingTasks?.add();
  6059. setTimeout(() => {
  6060. try {
  6061. fn(value);
  6062. }
  6063. finally {
  6064. if (taskId !== undefined) {
  6065. this.pendingTasks?.remove(taskId);
  6066. }
  6067. }
  6068. });
  6069. };
  6070. }
  6071. }
  6072. /**
  6073. * @publicApi
  6074. */
  6075. const EventEmitter = EventEmitter_;
  6076. function noop(...args) {
  6077. // Do nothing.
  6078. }
  6079. /**
  6080. * Gets a scheduling function that runs the callback after the first of setTimeout and
  6081. * requestAnimationFrame resolves.
  6082. *
  6083. * - `requestAnimationFrame` ensures that change detection runs ahead of a browser repaint.
  6084. * This ensures that the create and update passes of a change detection always happen
  6085. * in the same frame.
  6086. * - When the browser is resource-starved, `rAF` can execute _before_ a `setTimeout` because
  6087. * rendering is a very high priority process. This means that `setTimeout` cannot guarantee
  6088. * same-frame create and update pass, when `setTimeout` is used to schedule the update phase.
  6089. * - While `rAF` gives us the desirable same-frame updates, it has two limitations that
  6090. * prevent it from being used alone. First, it does not run in background tabs, which would
  6091. * prevent Angular from initializing an application when opened in a new tab (for example).
  6092. * Second, repeated calls to requestAnimationFrame will execute at the refresh rate of the
  6093. * hardware (~16ms for a 60Hz display). This would cause significant slowdown of tests that
  6094. * are written with several updates and asserts in the form of "update; await stable; assert;".
  6095. * - Both `setTimeout` and `rAF` are able to "coalesce" several events from a single user
  6096. * interaction into a single change detection. Importantly, this reduces view tree traversals when
  6097. * compared to an alternative timing mechanism like `queueMicrotask`, where change detection would
  6098. * then be interleaves between each event.
  6099. *
  6100. * By running change detection after the first of `setTimeout` and `rAF` to execute, we get the
  6101. * best of both worlds.
  6102. *
  6103. * @returns a function to cancel the scheduled callback
  6104. */
  6105. function scheduleCallbackWithRafRace(callback) {
  6106. let timeoutId;
  6107. let animationFrameId;
  6108. function cleanup() {
  6109. callback = noop;
  6110. try {
  6111. if (animationFrameId !== undefined && typeof cancelAnimationFrame === 'function') {
  6112. cancelAnimationFrame(animationFrameId);
  6113. }
  6114. if (timeoutId !== undefined) {
  6115. clearTimeout(timeoutId);
  6116. }
  6117. }
  6118. catch {
  6119. // Clearing/canceling can fail in tests due to the timing of functions being patched and unpatched
  6120. // Just ignore the errors - we protect ourselves from this issue by also making the callback a no-op.
  6121. }
  6122. }
  6123. timeoutId = setTimeout(() => {
  6124. callback();
  6125. cleanup();
  6126. });
  6127. if (typeof requestAnimationFrame === 'function') {
  6128. animationFrameId = requestAnimationFrame(() => {
  6129. callback();
  6130. cleanup();
  6131. });
  6132. }
  6133. return () => cleanup();
  6134. }
  6135. function scheduleCallbackWithMicrotask(callback) {
  6136. queueMicrotask(() => callback());
  6137. return () => {
  6138. callback = noop;
  6139. };
  6140. }
  6141. class AsyncStackTaggingZoneSpec {
  6142. createTask;
  6143. constructor(namePrefix, consoleAsyncStackTaggingImpl = console) {
  6144. this.name = 'asyncStackTagging for ' + namePrefix;
  6145. this.createTask = consoleAsyncStackTaggingImpl?.createTask ?? (() => null);
  6146. }
  6147. // ZoneSpec implementation below.
  6148. name;
  6149. onScheduleTask(delegate, _current, target, task) {
  6150. task.consoleTask = this.createTask(`Zone - ${task.source || task.type}`);
  6151. return delegate.scheduleTask(target, task);
  6152. }
  6153. onInvokeTask(delegate, _currentZone, targetZone, task, applyThis, applyArgs) {
  6154. let ret;
  6155. if (task.consoleTask) {
  6156. ret = task.consoleTask.run(() => delegate.invokeTask(targetZone, task, applyThis, applyArgs));
  6157. }
  6158. else {
  6159. ret = delegate.invokeTask(targetZone, task, applyThis, applyArgs);
  6160. }
  6161. return ret;
  6162. }
  6163. }
  6164. const isAngularZoneProperty = 'isAngularZone';
  6165. const angularZoneInstanceIdProperty = isAngularZoneProperty + '_ID';
  6166. let ngZoneInstanceId = 0;
  6167. /**
  6168. * An injectable service for executing work inside or outside of the Angular zone.
  6169. *
  6170. * The most common use of this service is to optimize performance when starting a work consisting of
  6171. * one or more asynchronous tasks that don't require UI updates or error handling to be handled by
  6172. * Angular. Such tasks can be kicked off via {@link #runOutsideAngular} and if needed, these tasks
  6173. * can reenter the Angular zone via {@link #run}.
  6174. *
  6175. * <!-- TODO: add/fix links to:
  6176. * - docs explaining zones and the use of zones in Angular and change-detection
  6177. * - link to runOutsideAngular/run (throughout this file!)
  6178. * -->
  6179. *
  6180. * @usageNotes
  6181. * ### Example
  6182. *
  6183. * ```ts
  6184. * import {Component, NgZone} from '@angular/core';
  6185. * import {NgIf} from '@angular/common';
  6186. *
  6187. * @Component({
  6188. * selector: 'ng-zone-demo',
  6189. * template: `
  6190. * <h2>Demo: NgZone</h2>
  6191. *
  6192. * <p>Progress: {{progress}}%</p>
  6193. * <p *ngIf="progress >= 100">Done processing {{label}} of Angular zone!</p>
  6194. *
  6195. * <button (click)="processWithinAngularZone()">Process within Angular zone</button>
  6196. * <button (click)="processOutsideOfAngularZone()">Process outside of Angular zone</button>
  6197. * `,
  6198. * })
  6199. * export class NgZoneDemo {
  6200. * progress: number = 0;
  6201. * label: string;
  6202. *
  6203. * constructor(private _ngZone: NgZone) {}
  6204. *
  6205. * // Loop inside the Angular zone
  6206. * // so the UI DOES refresh after each setTimeout cycle
  6207. * processWithinAngularZone() {
  6208. * this.label = 'inside';
  6209. * this.progress = 0;
  6210. * this._increaseProgress(() => console.log('Inside Done!'));
  6211. * }
  6212. *
  6213. * // Loop outside of the Angular zone
  6214. * // so the UI DOES NOT refresh after each setTimeout cycle
  6215. * processOutsideOfAngularZone() {
  6216. * this.label = 'outside';
  6217. * this.progress = 0;
  6218. * this._ngZone.runOutsideAngular(() => {
  6219. * this._increaseProgress(() => {
  6220. * // reenter the Angular zone and display done
  6221. * this._ngZone.run(() => { console.log('Outside Done!'); });
  6222. * });
  6223. * });
  6224. * }
  6225. *
  6226. * _increaseProgress(doneCallback: () => void) {
  6227. * this.progress += 1;
  6228. * console.log(`Current progress: ${this.progress}%`);
  6229. *
  6230. * if (this.progress < 100) {
  6231. * window.setTimeout(() => this._increaseProgress(doneCallback), 10);
  6232. * } else {
  6233. * doneCallback();
  6234. * }
  6235. * }
  6236. * }
  6237. * ```
  6238. *
  6239. * @publicApi
  6240. */
  6241. class NgZone {
  6242. hasPendingMacrotasks = false;
  6243. hasPendingMicrotasks = false;
  6244. /**
  6245. * Whether there are no outstanding microtasks or macrotasks.
  6246. */
  6247. isStable = true;
  6248. /**
  6249. * Notifies when code enters Angular Zone. This gets fired first on VM Turn.
  6250. */
  6251. onUnstable = new EventEmitter(false);
  6252. /**
  6253. * Notifies when there is no more microtasks enqueued in the current VM Turn.
  6254. * This is a hint for Angular to do change detection, which may enqueue more microtasks.
  6255. * For this reason this event can fire multiple times per VM Turn.
  6256. */
  6257. onMicrotaskEmpty = new EventEmitter(false);
  6258. /**
  6259. * Notifies when the last `onMicrotaskEmpty` has run and there are no more microtasks, which
  6260. * implies we are about to relinquish VM turn.
  6261. * This event gets called just once.
  6262. */
  6263. onStable = new EventEmitter(false);
  6264. /**
  6265. * Notifies that an error has been delivered.
  6266. */
  6267. onError = new EventEmitter(false);
  6268. constructor(options) {
  6269. const { enableLongStackTrace = false, shouldCoalesceEventChangeDetection = false, shouldCoalesceRunChangeDetection = false, scheduleInRootZone = SCHEDULE_IN_ROOT_ZONE_DEFAULT, } = options;
  6270. if (typeof Zone == 'undefined') {
  6271. throw new RuntimeError(908 /* RuntimeErrorCode.MISSING_ZONEJS */, ngDevMode && `In this configuration Angular requires Zone.js`);
  6272. }
  6273. Zone.assertZonePatched();
  6274. const self = this;
  6275. self._nesting = 0;
  6276. self._outer = self._inner = Zone.current;
  6277. // AsyncStackTaggingZoneSpec provides `linked stack traces` to show
  6278. // where the async operation is scheduled. For more details, refer
  6279. // to this article, https://developer.chrome.com/blog/devtools-better-angular-debugging/
  6280. // And we only import this AsyncStackTaggingZoneSpec in development mode,
  6281. // in the production mode, the AsyncStackTaggingZoneSpec will be tree shaken away.
  6282. if (ngDevMode) {
  6283. self._inner = self._inner.fork(new AsyncStackTaggingZoneSpec('Angular'));
  6284. }
  6285. if (Zone['TaskTrackingZoneSpec']) {
  6286. self._inner = self._inner.fork(new Zone['TaskTrackingZoneSpec']());
  6287. }
  6288. if (enableLongStackTrace && Zone['longStackTraceZoneSpec']) {
  6289. self._inner = self._inner.fork(Zone['longStackTraceZoneSpec']);
  6290. }
  6291. // if shouldCoalesceRunChangeDetection is true, all tasks including event tasks will be
  6292. // coalesced, so shouldCoalesceEventChangeDetection option is not necessary and can be skipped.
  6293. self.shouldCoalesceEventChangeDetection =
  6294. !shouldCoalesceRunChangeDetection && shouldCoalesceEventChangeDetection;
  6295. self.shouldCoalesceRunChangeDetection = shouldCoalesceRunChangeDetection;
  6296. self.callbackScheduled = false;
  6297. self.scheduleInRootZone = scheduleInRootZone;
  6298. forkInnerZoneWithAngularBehavior(self);
  6299. }
  6300. /**
  6301. This method checks whether the method call happens within an Angular Zone instance.
  6302. */
  6303. static isInAngularZone() {
  6304. // Zone needs to be checked, because this method might be called even when NoopNgZone is used.
  6305. return typeof Zone !== 'undefined' && Zone.current.get(isAngularZoneProperty) === true;
  6306. }
  6307. /**
  6308. Assures that the method is called within the Angular Zone, otherwise throws an error.
  6309. */
  6310. static assertInAngularZone() {
  6311. if (!NgZone.isInAngularZone()) {
  6312. throw new RuntimeError(909 /* RuntimeErrorCode.UNEXPECTED_ZONE_STATE */, ngDevMode && 'Expected to be in Angular Zone, but it is not!');
  6313. }
  6314. }
  6315. /**
  6316. Assures that the method is called outside of the Angular Zone, otherwise throws an error.
  6317. */
  6318. static assertNotInAngularZone() {
  6319. if (NgZone.isInAngularZone()) {
  6320. throw new RuntimeError(909 /* RuntimeErrorCode.UNEXPECTED_ZONE_STATE */, ngDevMode && 'Expected to not be in Angular Zone, but it is!');
  6321. }
  6322. }
  6323. /**
  6324. * Executes the `fn` function synchronously within the Angular zone and returns value returned by
  6325. * the function.
  6326. *
  6327. * Running functions via `run` allows you to reenter Angular zone from a task that was executed
  6328. * outside of the Angular zone (typically started via {@link #runOutsideAngular}).
  6329. *
  6330. * Any future tasks or microtasks scheduled from within this function will continue executing from
  6331. * within the Angular zone.
  6332. *
  6333. * If a synchronous error happens it will be rethrown and not reported via `onError`.
  6334. */
  6335. run(fn, applyThis, applyArgs) {
  6336. return this._inner.run(fn, applyThis, applyArgs);
  6337. }
  6338. /**
  6339. * Executes the `fn` function synchronously within the Angular zone as a task and returns value
  6340. * returned by the function.
  6341. *
  6342. * Running functions via `runTask` allows you to reenter Angular zone from a task that was executed
  6343. * outside of the Angular zone (typically started via {@link #runOutsideAngular}).
  6344. *
  6345. * Any future tasks or microtasks scheduled from within this function will continue executing from
  6346. * within the Angular zone.
  6347. *
  6348. * If a synchronous error happens it will be rethrown and not reported via `onError`.
  6349. */
  6350. runTask(fn, applyThis, applyArgs, name) {
  6351. const zone = this._inner;
  6352. const task = zone.scheduleEventTask('NgZoneEvent: ' + name, fn, EMPTY_PAYLOAD, noop, noop);
  6353. try {
  6354. return zone.runTask(task, applyThis, applyArgs);
  6355. }
  6356. finally {
  6357. zone.cancelTask(task);
  6358. }
  6359. }
  6360. /**
  6361. * Same as `run`, except that synchronous errors are caught and forwarded via `onError` and not
  6362. * rethrown.
  6363. */
  6364. runGuarded(fn, applyThis, applyArgs) {
  6365. return this._inner.runGuarded(fn, applyThis, applyArgs);
  6366. }
  6367. /**
  6368. * Executes the `fn` function synchronously in Angular's parent zone and returns value returned by
  6369. * the function.
  6370. *
  6371. * Running functions via {@link #runOutsideAngular} allows you to escape Angular's zone and do
  6372. * work that
  6373. * doesn't trigger Angular change-detection or is subject to Angular's error handling.
  6374. *
  6375. * Any future tasks or microtasks scheduled from within this function will continue executing from
  6376. * outside of the Angular zone.
  6377. *
  6378. * Use {@link #run} to reenter the Angular zone and do work that updates the application model.
  6379. */
  6380. runOutsideAngular(fn) {
  6381. return this._outer.run(fn);
  6382. }
  6383. }
  6384. const EMPTY_PAYLOAD = {};
  6385. function checkStable(zone) {
  6386. // TODO: @JiaLiPassion, should check zone.isCheckStableRunning to prevent
  6387. // re-entry. The case is:
  6388. //
  6389. // @Component({...})
  6390. // export class AppComponent {
  6391. // constructor(private ngZone: NgZone) {
  6392. // this.ngZone.onStable.subscribe(() => {
  6393. // this.ngZone.run(() => console.log('stable'););
  6394. // });
  6395. // }
  6396. //
  6397. // The onStable subscriber run another function inside ngZone
  6398. // which causes `checkStable()` re-entry.
  6399. // But this fix causes some issues in g3, so this fix will be
  6400. // launched in another PR.
  6401. if (zone._nesting == 0 && !zone.hasPendingMicrotasks && !zone.isStable) {
  6402. try {
  6403. zone._nesting++;
  6404. zone.onMicrotaskEmpty.emit(null);
  6405. }
  6406. finally {
  6407. zone._nesting--;
  6408. if (!zone.hasPendingMicrotasks) {
  6409. try {
  6410. zone.runOutsideAngular(() => zone.onStable.emit(null));
  6411. }
  6412. finally {
  6413. zone.isStable = true;
  6414. }
  6415. }
  6416. }
  6417. }
  6418. }
  6419. function delayChangeDetectionForEvents(zone) {
  6420. /**
  6421. * We also need to check _nesting here
  6422. * Consider the following case with shouldCoalesceRunChangeDetection = true
  6423. *
  6424. * ngZone.run(() => {});
  6425. * ngZone.run(() => {});
  6426. *
  6427. * We want the two `ngZone.run()` only trigger one change detection
  6428. * when shouldCoalesceRunChangeDetection is true.
  6429. * And because in this case, change detection run in async way(requestAnimationFrame),
  6430. * so we also need to check the _nesting here to prevent multiple
  6431. * change detections.
  6432. */
  6433. if (zone.isCheckStableRunning || zone.callbackScheduled) {
  6434. return;
  6435. }
  6436. zone.callbackScheduled = true;
  6437. function scheduleCheckStable() {
  6438. scheduleCallbackWithRafRace(() => {
  6439. zone.callbackScheduled = false;
  6440. updateMicroTaskStatus(zone);
  6441. zone.isCheckStableRunning = true;
  6442. checkStable(zone);
  6443. zone.isCheckStableRunning = false;
  6444. });
  6445. }
  6446. if (zone.scheduleInRootZone) {
  6447. Zone.root.run(() => {
  6448. scheduleCheckStable();
  6449. });
  6450. }
  6451. else {
  6452. zone._outer.run(() => {
  6453. scheduleCheckStable();
  6454. });
  6455. }
  6456. updateMicroTaskStatus(zone);
  6457. }
  6458. function forkInnerZoneWithAngularBehavior(zone) {
  6459. const delayChangeDetectionForEventsDelegate = () => {
  6460. delayChangeDetectionForEvents(zone);
  6461. };
  6462. const instanceId = ngZoneInstanceId++;
  6463. zone._inner = zone._inner.fork({
  6464. name: 'angular',
  6465. properties: {
  6466. [isAngularZoneProperty]: true,
  6467. [angularZoneInstanceIdProperty]: instanceId,
  6468. [angularZoneInstanceIdProperty + instanceId]: true,
  6469. },
  6470. onInvokeTask: (delegate, current, target, task, applyThis, applyArgs) => {
  6471. // Prevent triggering change detection when the flag is detected.
  6472. if (shouldBeIgnoredByZone(applyArgs)) {
  6473. return delegate.invokeTask(target, task, applyThis, applyArgs);
  6474. }
  6475. try {
  6476. onEnter(zone);
  6477. return delegate.invokeTask(target, task, applyThis, applyArgs);
  6478. }
  6479. finally {
  6480. if ((zone.shouldCoalesceEventChangeDetection && task.type === 'eventTask') ||
  6481. zone.shouldCoalesceRunChangeDetection) {
  6482. delayChangeDetectionForEventsDelegate();
  6483. }
  6484. onLeave(zone);
  6485. }
  6486. },
  6487. onInvoke: (delegate, current, target, callback, applyThis, applyArgs, source) => {
  6488. try {
  6489. onEnter(zone);
  6490. return delegate.invoke(target, callback, applyThis, applyArgs, source);
  6491. }
  6492. finally {
  6493. if (zone.shouldCoalesceRunChangeDetection &&
  6494. // Do not delay change detection when the task is the scheduler's tick.
  6495. // We need to synchronously trigger the stability logic so that the
  6496. // zone-based scheduler can prevent a duplicate ApplicationRef.tick
  6497. // by first checking if the scheduler tick is running. This does seem a bit roundabout,
  6498. // but we _do_ still want to trigger all the correct events when we exit the zone.run
  6499. // (`onMicrotaskEmpty` and `onStable` _should_ emit; developers can have code which
  6500. // relies on these events happening after change detection runs).
  6501. // Note: `zone.callbackScheduled` is already in delayChangeDetectionForEventsDelegate
  6502. // but is added here as well to prevent reads of applyArgs when not necessary
  6503. !zone.callbackScheduled &&
  6504. !isSchedulerTick(applyArgs)) {
  6505. delayChangeDetectionForEventsDelegate();
  6506. }
  6507. onLeave(zone);
  6508. }
  6509. },
  6510. onHasTask: (delegate, current, target, hasTaskState) => {
  6511. delegate.hasTask(target, hasTaskState);
  6512. if (current === target) {
  6513. // We are only interested in hasTask events which originate from our zone
  6514. // (A child hasTask event is not interesting to us)
  6515. if (hasTaskState.change == 'microTask') {
  6516. zone._hasPendingMicrotasks = hasTaskState.microTask;
  6517. updateMicroTaskStatus(zone);
  6518. checkStable(zone);
  6519. }
  6520. else if (hasTaskState.change == 'macroTask') {
  6521. zone.hasPendingMacrotasks = hasTaskState.macroTask;
  6522. }
  6523. }
  6524. },
  6525. onHandleError: (delegate, current, target, error) => {
  6526. delegate.handleError(target, error);
  6527. zone.runOutsideAngular(() => zone.onError.emit(error));
  6528. return false;
  6529. },
  6530. });
  6531. }
  6532. function updateMicroTaskStatus(zone) {
  6533. if (zone._hasPendingMicrotasks ||
  6534. ((zone.shouldCoalesceEventChangeDetection || zone.shouldCoalesceRunChangeDetection) &&
  6535. zone.callbackScheduled === true)) {
  6536. zone.hasPendingMicrotasks = true;
  6537. }
  6538. else {
  6539. zone.hasPendingMicrotasks = false;
  6540. }
  6541. }
  6542. function onEnter(zone) {
  6543. zone._nesting++;
  6544. if (zone.isStable) {
  6545. zone.isStable = false;
  6546. zone.onUnstable.emit(null);
  6547. }
  6548. }
  6549. function onLeave(zone) {
  6550. zone._nesting--;
  6551. checkStable(zone);
  6552. }
  6553. /**
  6554. * Provides a noop implementation of `NgZone` which does nothing. This zone requires explicit calls
  6555. * to framework to perform rendering.
  6556. */
  6557. class NoopNgZone {
  6558. hasPendingMicrotasks = false;
  6559. hasPendingMacrotasks = false;
  6560. isStable = true;
  6561. onUnstable = new EventEmitter();
  6562. onMicrotaskEmpty = new EventEmitter();
  6563. onStable = new EventEmitter();
  6564. onError = new EventEmitter();
  6565. run(fn, applyThis, applyArgs) {
  6566. return fn.apply(applyThis, applyArgs);
  6567. }
  6568. runGuarded(fn, applyThis, applyArgs) {
  6569. return fn.apply(applyThis, applyArgs);
  6570. }
  6571. runOutsideAngular(fn) {
  6572. return fn();
  6573. }
  6574. runTask(fn, applyThis, applyArgs, name) {
  6575. return fn.apply(applyThis, applyArgs);
  6576. }
  6577. }
  6578. function shouldBeIgnoredByZone(applyArgs) {
  6579. return hasApplyArgsData(applyArgs, '__ignore_ng_zone__');
  6580. }
  6581. function isSchedulerTick(applyArgs) {
  6582. return hasApplyArgsData(applyArgs, '__scheduler_tick__');
  6583. }
  6584. function hasApplyArgsData(applyArgs, key) {
  6585. if (!Array.isArray(applyArgs)) {
  6586. return false;
  6587. }
  6588. // We should only ever get 1 arg passed through to invokeTask.
  6589. // Short circuit here incase that behavior changes.
  6590. if (applyArgs.length !== 1) {
  6591. return false;
  6592. }
  6593. return applyArgs[0]?.data?.[key] === true;
  6594. }
  6595. function getNgZone(ngZoneToUse = 'zone.js', options) {
  6596. if (ngZoneToUse === 'noop') {
  6597. return new NoopNgZone();
  6598. }
  6599. if (ngZoneToUse === 'zone.js') {
  6600. return new NgZone(options);
  6601. }
  6602. return ngZoneToUse;
  6603. }
  6604. /**
  6605. * Provides a hook for centralized exception handling.
  6606. *
  6607. * The default implementation of `ErrorHandler` prints error messages to the `console`. To
  6608. * intercept error handling, write a custom exception handler that replaces this default as
  6609. * appropriate for your app.
  6610. *
  6611. * @usageNotes
  6612. * ### Example
  6613. *
  6614. * ```ts
  6615. * class MyErrorHandler implements ErrorHandler {
  6616. * handleError(error) {
  6617. * // do something with the exception
  6618. * }
  6619. * }
  6620. *
  6621. * // Provide in standalone apps
  6622. * bootstrapApplication(AppComponent, {
  6623. * providers: [{provide: ErrorHandler, useClass: MyErrorHandler}]
  6624. * })
  6625. *
  6626. * // Provide in module-based apps
  6627. * @NgModule({
  6628. * providers: [{provide: ErrorHandler, useClass: MyErrorHandler}]
  6629. * })
  6630. * class MyModule {}
  6631. * ```
  6632. *
  6633. * @publicApi
  6634. */
  6635. class ErrorHandler {
  6636. /**
  6637. * @internal
  6638. */
  6639. _console = console;
  6640. handleError(error) {
  6641. this._console.error('ERROR', error);
  6642. }
  6643. }
  6644. /**
  6645. * `InjectionToken` used to configure how to call the `ErrorHandler`.
  6646. *
  6647. * `NgZone` is provided by default today so the default (and only) implementation for this
  6648. * is calling `ErrorHandler.handleError` outside of the Angular zone.
  6649. */
  6650. const INTERNAL_APPLICATION_ERROR_HANDLER = new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'internal error handler' : '', {
  6651. providedIn: 'root',
  6652. factory: () => {
  6653. const zone = inject(NgZone);
  6654. const userErrorHandler = inject(ErrorHandler);
  6655. return (e) => zone.runOutsideAngular(() => userErrorHandler.handleError(e));
  6656. },
  6657. });
  6658. /**
  6659. * An `OutputEmitterRef` is created by the `output()` function and can be
  6660. * used to emit values to consumers of your directive or component.
  6661. *
  6662. * Consumers of your directive/component can bind to the output and
  6663. * subscribe to changes via the bound event syntax. For example:
  6664. *
  6665. * ```html
  6666. * <my-comp (valueChange)="processNewValue($event)" />
  6667. * ```
  6668. *
  6669. * @publicAPI
  6670. */
  6671. class OutputEmitterRef {
  6672. destroyed = false;
  6673. listeners = null;
  6674. errorHandler = inject(ErrorHandler, { optional: true });
  6675. /** @internal */
  6676. destroyRef = inject(DestroyRef);
  6677. constructor() {
  6678. // Clean-up all listeners and mark as destroyed upon destroy.
  6679. this.destroyRef.onDestroy(() => {
  6680. this.destroyed = true;
  6681. this.listeners = null;
  6682. });
  6683. }
  6684. subscribe(callback) {
  6685. if (this.destroyed) {
  6686. throw new RuntimeError(953 /* RuntimeErrorCode.OUTPUT_REF_DESTROYED */, ngDevMode &&
  6687. 'Unexpected subscription to destroyed `OutputRef`. ' +
  6688. 'The owning directive/component is destroyed.');
  6689. }
  6690. (this.listeners ??= []).push(callback);
  6691. return {
  6692. unsubscribe: () => {
  6693. const idx = this.listeners?.indexOf(callback);
  6694. if (idx !== undefined && idx !== -1) {
  6695. this.listeners?.splice(idx, 1);
  6696. }
  6697. },
  6698. };
  6699. }
  6700. /** Emits a new value to the output. */
  6701. emit(value) {
  6702. if (this.destroyed) {
  6703. console.warn(formatRuntimeError(953 /* RuntimeErrorCode.OUTPUT_REF_DESTROYED */, ngDevMode &&
  6704. 'Unexpected emit for destroyed `OutputRef`. ' +
  6705. 'The owning directive/component is destroyed.'));
  6706. return;
  6707. }
  6708. if (this.listeners === null) {
  6709. return;
  6710. }
  6711. const previousConsumer = setActiveConsumer$1(null);
  6712. try {
  6713. for (const listenerFn of this.listeners) {
  6714. try {
  6715. listenerFn(value);
  6716. }
  6717. catch (err) {
  6718. this.errorHandler?.handleError(err);
  6719. }
  6720. }
  6721. }
  6722. finally {
  6723. setActiveConsumer$1(previousConsumer);
  6724. }
  6725. }
  6726. }
  6727. /** Gets the owning `DestroyRef` for the given output. */
  6728. function getOutputDestroyRef(ref) {
  6729. return ref.destroyRef;
  6730. }
  6731. /**
  6732. * The `output` function allows declaration of Angular outputs in
  6733. * directives and components.
  6734. *
  6735. * You can use outputs to emit values to parent directives and component.
  6736. * Parents can subscribe to changes via:
  6737. *
  6738. * - template event bindings. For example, `(myOutput)="doSomething($event)"`
  6739. * - programmatic subscription by using `OutputRef#subscribe`.
  6740. *
  6741. * @usageNotes
  6742. *
  6743. * To use `output()`, import the function from `@angular/core`.
  6744. *
  6745. * ```ts
  6746. * import {output} from '@angular/core';
  6747. * ```
  6748. *
  6749. * Inside your component, introduce a new class member and initialize
  6750. * it with a call to `output`.
  6751. *
  6752. * ```ts
  6753. * @Directive({
  6754. * ...
  6755. * })
  6756. * export class MyDir {
  6757. * nameChange = output<string>(); // OutputEmitterRef<string>
  6758. * onClick = output(); // OutputEmitterRef<void>
  6759. * }
  6760. * ```
  6761. *
  6762. * You can emit values to consumers of your directive, by using
  6763. * the `emit` method from `OutputEmitterRef`.
  6764. *
  6765. * ```ts
  6766. * updateName(newName: string): void {
  6767. * this.nameChange.emit(newName);
  6768. * }
  6769. * ```
  6770. * @initializerApiFunction {"showTypesInSignaturePreview": true}
  6771. * @publicAPI
  6772. */
  6773. function output(opts) {
  6774. ngDevMode && assertInInjectionContext(output);
  6775. return new OutputEmitterRef();
  6776. }
  6777. function inputFunction(initialValue, opts) {
  6778. ngDevMode && assertInInjectionContext(input);
  6779. return createInputSignal(initialValue, opts);
  6780. }
  6781. function inputRequiredFunction(opts) {
  6782. ngDevMode && assertInInjectionContext(input);
  6783. return createInputSignal(REQUIRED_UNSET_VALUE, opts);
  6784. }
  6785. /**
  6786. * The `input` function allows declaration of Angular inputs in directives
  6787. * and components.
  6788. *
  6789. * There are two variants of inputs that can be declared:
  6790. *
  6791. * 1. **Optional inputs** with an initial value.
  6792. * 2. **Required inputs** that consumers need to set.
  6793. *
  6794. * By default, the `input` function will declare optional inputs that
  6795. * always have an initial value. Required inputs can be declared
  6796. * using the `input.required()` function.
  6797. *
  6798. * Inputs are signals. The values of an input are exposed as a `Signal`.
  6799. * The signal always holds the latest value of the input that is bound
  6800. * from the parent.
  6801. *
  6802. * @usageNotes
  6803. * To use signal-based inputs, import `input` from `@angular/core`.
  6804. *
  6805. * ```ts
  6806. * import {input} from '@angular/core`;
  6807. * ```
  6808. *
  6809. * Inside your component, introduce a new class member and initialize
  6810. * it with a call to `input` or `input.required`.
  6811. *
  6812. * ```ts
  6813. * @Component({
  6814. * ...
  6815. * })
  6816. * export class UserProfileComponent {
  6817. * firstName = input<string>(); // Signal<string|undefined>
  6818. * lastName = input.required<string>(); // Signal<string>
  6819. * age = input(0) // Signal<number>
  6820. * }
  6821. * ```
  6822. *
  6823. * Inside your component template, you can display values of the inputs
  6824. * by calling the signal.
  6825. *
  6826. * ```html
  6827. * <span>{{firstName()}}</span>
  6828. * ```
  6829. *
  6830. * @publicAPI
  6831. * @initializerApiFunction
  6832. */
  6833. const input = (() => {
  6834. // Note: This may be considered a side-effect, but nothing will depend on
  6835. // this assignment, unless this `input` constant export is accessed. It's a
  6836. // self-contained side effect that is local to the user facing`input` export.
  6837. inputFunction.required = inputRequiredFunction;
  6838. return inputFunction;
  6839. })();
  6840. /**
  6841. * Creates an ElementRef from the most recent node.
  6842. *
  6843. * @returns The ElementRef instance to use
  6844. */
  6845. function injectElementRef() {
  6846. return createElementRef(getCurrentTNode(), getLView());
  6847. }
  6848. /**
  6849. * Creates an ElementRef given a node.
  6850. *
  6851. * @param tNode The node for which you'd like an ElementRef
  6852. * @param lView The view to which the node belongs
  6853. * @returns The ElementRef instance to use
  6854. */
  6855. function createElementRef(tNode, lView) {
  6856. return new ElementRef(getNativeByTNode(tNode, lView));
  6857. }
  6858. /**
  6859. * A wrapper around a native element inside of a View.
  6860. *
  6861. * An `ElementRef` is backed by a render-specific element. In the browser, this is usually a DOM
  6862. * element.
  6863. *
  6864. * @security Permitting direct access to the DOM can make your application more vulnerable to
  6865. * XSS attacks. Carefully review any use of `ElementRef` in your code. For more detail, see the
  6866. * [Security Guide](https://g.co/ng/security).
  6867. *
  6868. * @publicApi
  6869. */
  6870. // Note: We don't expose things like `Injector`, `ViewContainer`, ... here,
  6871. // i.e. users have to ask for what they need. With that, we can build better analysis tools
  6872. // and could do better codegen in the future.
  6873. class ElementRef {
  6874. /**
  6875. * <div class="docs-alert docs-alert-important">
  6876. * <header>Use with caution</header>
  6877. * <p>
  6878. * Use this API as the last resort when direct access to DOM is needed. Use templating and
  6879. * data-binding provided by Angular instead. If used, it is recommended in combination with
  6880. * {@link /best-practices/security#direct-use-of-the-dom-apis-and-explicit-sanitization-calls DomSanitizer}
  6881. * for maxiumum security;
  6882. * </p>
  6883. * </div>
  6884. */
  6885. nativeElement;
  6886. constructor(nativeElement) {
  6887. this.nativeElement = nativeElement;
  6888. }
  6889. /**
  6890. * @internal
  6891. * @nocollapse
  6892. */
  6893. static __NG_ELEMENT_ID__ = injectElementRef;
  6894. }
  6895. /**
  6896. * Unwraps `ElementRef` and return the `nativeElement`.
  6897. *
  6898. * @param value value to unwrap
  6899. * @returns `nativeElement` if `ElementRef` otherwise returns value as is.
  6900. */
  6901. function unwrapElementRef(value) {
  6902. return value instanceof ElementRef ? value.nativeElement : value;
  6903. }
  6904. /**
  6905. * Checks if the given `value` is a reactive `Signal`.
  6906. */
  6907. function isSignal(value) {
  6908. return typeof value === 'function' && value[SIGNAL] !== undefined;
  6909. }
  6910. /**
  6911. * Utility function used during template type checking to extract the value from a `WritableSignal`.
  6912. * @codeGenApi
  6913. */
  6914. function ɵunwrapWritableSignal(value) {
  6915. // Note: the function uses `WRITABLE_SIGNAL` as a brand instead of `WritableSignal<T>`,
  6916. // because the latter incorrectly unwraps non-signal getter functions.
  6917. return null;
  6918. }
  6919. /**
  6920. * Create a `Signal` that can be set or updated directly.
  6921. */
  6922. function signal(initialValue, options) {
  6923. const signalFn = createSignal(initialValue, options?.equal);
  6924. const node = signalFn[SIGNAL];
  6925. signalFn.set = (newValue) => signalSetFn(node, newValue);
  6926. signalFn.update = (updateFn) => signalUpdateFn(node, updateFn);
  6927. signalFn.asReadonly = signalAsReadonlyFn.bind(signalFn);
  6928. if (ngDevMode) {
  6929. signalFn.toString = () => `[Signal: ${signalFn()}]`;
  6930. node.debugName = options?.debugName;
  6931. }
  6932. return signalFn;
  6933. }
  6934. function signalAsReadonlyFn() {
  6935. const node = this[SIGNAL];
  6936. if (node.readonlyFn === undefined) {
  6937. const readonlyFn = () => this();
  6938. readonlyFn[SIGNAL] = node;
  6939. node.readonlyFn = readonlyFn;
  6940. }
  6941. return node.readonlyFn;
  6942. }
  6943. /**
  6944. * Checks if the given `value` is a writeable signal.
  6945. */
  6946. function isWritableSignal(value) {
  6947. return isSignal(value) && typeof value.set === 'function';
  6948. }
  6949. function symbolIterator() {
  6950. // @ts-expect-error accessing a private member
  6951. return this._results[Symbol.iterator]();
  6952. }
  6953. /**
  6954. * An unmodifiable list of items that Angular keeps up to date when the state
  6955. * of the application changes.
  6956. *
  6957. * The type of object that {@link ViewChildren}, {@link ContentChildren}, and {@link QueryList}
  6958. * provide.
  6959. *
  6960. * Implements an iterable interface, therefore it can be used in both ES6
  6961. * javascript `for (var i of items)` loops as well as in Angular templates with
  6962. * `*ngFor="let i of myList"`.
  6963. *
  6964. * Changes can be observed by subscribing to the changes `Observable`.
  6965. *
  6966. * NOTE: In the future this class will implement an `Observable` interface.
  6967. *
  6968. * @usageNotes
  6969. * ### Example
  6970. * ```ts
  6971. * @Component({...})
  6972. * class Container {
  6973. * @ViewChildren(Item) items:QueryList<Item>;
  6974. * }
  6975. * ```
  6976. *
  6977. * @publicApi
  6978. */
  6979. class QueryList {
  6980. _emitDistinctChangesOnly;
  6981. dirty = true;
  6982. _onDirty = undefined;
  6983. _results = [];
  6984. _changesDetected = false;
  6985. _changes = undefined;
  6986. length = 0;
  6987. first = undefined;
  6988. last = undefined;
  6989. /**
  6990. * Returns `Observable` of `QueryList` notifying the subscriber of changes.
  6991. */
  6992. get changes() {
  6993. return (this._changes ??= new Subject());
  6994. }
  6995. /**
  6996. * @param emitDistinctChangesOnly Whether `QueryList.changes` should fire only when actual change
  6997. * has occurred. Or if it should fire when query is recomputed. (recomputing could resolve in
  6998. * the same result)
  6999. */
  7000. constructor(_emitDistinctChangesOnly = false) {
  7001. this._emitDistinctChangesOnly = _emitDistinctChangesOnly;
  7002. }
  7003. /**
  7004. * Returns the QueryList entry at `index`.
  7005. */
  7006. get(index) {
  7007. return this._results[index];
  7008. }
  7009. /**
  7010. * See
  7011. * [Array.map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
  7012. */
  7013. map(fn) {
  7014. return this._results.map(fn);
  7015. }
  7016. filter(fn) {
  7017. return this._results.filter(fn);
  7018. }
  7019. /**
  7020. * See
  7021. * [Array.find](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find)
  7022. */
  7023. find(fn) {
  7024. return this._results.find(fn);
  7025. }
  7026. /**
  7027. * See
  7028. * [Array.reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)
  7029. */
  7030. reduce(fn, init) {
  7031. return this._results.reduce(fn, init);
  7032. }
  7033. /**
  7034. * See
  7035. * [Array.forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)
  7036. */
  7037. forEach(fn) {
  7038. this._results.forEach(fn);
  7039. }
  7040. /**
  7041. * See
  7042. * [Array.some](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some)
  7043. */
  7044. some(fn) {
  7045. return this._results.some(fn);
  7046. }
  7047. /**
  7048. * Returns a copy of the internal results list as an Array.
  7049. */
  7050. toArray() {
  7051. return this._results.slice();
  7052. }
  7053. toString() {
  7054. return this._results.toString();
  7055. }
  7056. /**
  7057. * Updates the stored data of the query list, and resets the `dirty` flag to `false`, so that
  7058. * on change detection, it will not notify of changes to the queries, unless a new change
  7059. * occurs.
  7060. *
  7061. * @param resultsTree The query results to store
  7062. * @param identityAccessor Optional function for extracting stable object identity from a value
  7063. * in the array. This function is executed for each element of the query result list while
  7064. * comparing current query list with the new one (provided as a first argument of the `reset`
  7065. * function) to detect if the lists are different. If the function is not provided, elements
  7066. * are compared as is (without any pre-processing).
  7067. */
  7068. reset(resultsTree, identityAccessor) {
  7069. this.dirty = false;
  7070. const newResultFlat = flatten(resultsTree);
  7071. if ((this._changesDetected = !arrayEquals(this._results, newResultFlat, identityAccessor))) {
  7072. this._results = newResultFlat;
  7073. this.length = newResultFlat.length;
  7074. this.last = newResultFlat[this.length - 1];
  7075. this.first = newResultFlat[0];
  7076. }
  7077. }
  7078. /**
  7079. * Triggers a change event by emitting on the `changes` {@link EventEmitter}.
  7080. */
  7081. notifyOnChanges() {
  7082. if (this._changes !== undefined && (this._changesDetected || !this._emitDistinctChangesOnly))
  7083. this._changes.next(this);
  7084. }
  7085. /** @internal */
  7086. onDirty(cb) {
  7087. this._onDirty = cb;
  7088. }
  7089. /** internal */
  7090. setDirty() {
  7091. this.dirty = true;
  7092. this._onDirty?.();
  7093. }
  7094. /** internal */
  7095. destroy() {
  7096. if (this._changes !== undefined) {
  7097. this._changes.complete();
  7098. this._changes.unsubscribe();
  7099. }
  7100. }
  7101. [Symbol.iterator] = (() => symbolIterator)();
  7102. }
  7103. /**
  7104. * The name of an attribute that can be added to the hydration boundary node
  7105. * (component host node) to disable hydration for the content within that boundary.
  7106. */
  7107. const SKIP_HYDRATION_ATTR_NAME = 'ngSkipHydration';
  7108. /** Lowercase name of the `ngSkipHydration` attribute used for case-insensitive comparisons. */
  7109. const SKIP_HYDRATION_ATTR_NAME_LOWER_CASE = 'ngskiphydration';
  7110. /**
  7111. * Helper function to check if a given TNode has the 'ngSkipHydration' attribute.
  7112. */
  7113. function hasSkipHydrationAttrOnTNode(tNode) {
  7114. const attrs = tNode.mergedAttrs;
  7115. if (attrs === null)
  7116. return false;
  7117. // only ever look at the attribute name and skip the values
  7118. for (let i = 0; i < attrs.length; i += 2) {
  7119. const value = attrs[i];
  7120. // This is a marker, which means that the static attributes section is over,
  7121. // so we can exit early.
  7122. if (typeof value === 'number')
  7123. return false;
  7124. if (typeof value === 'string' && value.toLowerCase() === SKIP_HYDRATION_ATTR_NAME_LOWER_CASE) {
  7125. return true;
  7126. }
  7127. }
  7128. return false;
  7129. }
  7130. /**
  7131. * Helper function to check if a given RElement has the 'ngSkipHydration' attribute.
  7132. */
  7133. function hasSkipHydrationAttrOnRElement(rNode) {
  7134. return rNode.hasAttribute(SKIP_HYDRATION_ATTR_NAME);
  7135. }
  7136. /**
  7137. * Checks whether a TNode has a flag to indicate that it's a part of
  7138. * a skip hydration block.
  7139. */
  7140. function hasInSkipHydrationBlockFlag(tNode) {
  7141. return (tNode.flags & 128 /* TNodeFlags.inSkipHydrationBlock */) === 128 /* TNodeFlags.inSkipHydrationBlock */;
  7142. }
  7143. /**
  7144. * Helper function that determines if a given node is within a skip hydration block
  7145. * by navigating up the TNode tree to see if any parent nodes have skip hydration
  7146. * attribute.
  7147. */
  7148. function isInSkipHydrationBlock(tNode) {
  7149. if (hasInSkipHydrationBlockFlag(tNode)) {
  7150. return true;
  7151. }
  7152. let currentTNode = tNode.parent;
  7153. while (currentTNode) {
  7154. if (hasInSkipHydrationBlockFlag(tNode) || hasSkipHydrationAttrOnTNode(currentTNode)) {
  7155. return true;
  7156. }
  7157. currentTNode = currentTNode.parent;
  7158. }
  7159. return false;
  7160. }
  7161. /**
  7162. * Check if an i18n block is in a skip hydration section by looking at a parent TNode
  7163. * to determine if this TNode is in a skip hydration section or the TNode has
  7164. * the `ngSkipHydration` attribute.
  7165. */
  7166. function isI18nInSkipHydrationBlock(parentTNode) {
  7167. return (hasInSkipHydrationBlockFlag(parentTNode) ||
  7168. hasSkipHydrationAttrOnTNode(parentTNode) ||
  7169. isInSkipHydrationBlock(parentTNode));
  7170. }
  7171. /**
  7172. * The strategy that the default change detector uses to detect changes.
  7173. * When set, takes effect the next time change detection is triggered.
  7174. *
  7175. * @see {@link /api/core/ChangeDetectorRef?tab=usage-notes Change detection usage}
  7176. * @see {@link /best-practices/skipping-subtrees Skipping component subtrees}
  7177. *
  7178. * @publicApi
  7179. */
  7180. var ChangeDetectionStrategy;
  7181. (function (ChangeDetectionStrategy) {
  7182. /**
  7183. * Use the `CheckOnce` strategy, meaning that automatic change detection is deactivated
  7184. * until reactivated by setting the strategy to `Default` (`CheckAlways`).
  7185. * Change detection can still be explicitly invoked.
  7186. * This strategy applies to all child directives and cannot be overridden.
  7187. */
  7188. ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush";
  7189. /**
  7190. * Use the default `CheckAlways` strategy, in which change detection is automatic until
  7191. * explicitly deactivated.
  7192. */
  7193. ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default";
  7194. })(ChangeDetectionStrategy || (ChangeDetectionStrategy = {}));
  7195. // Keeps track of the currently-active LViews.
  7196. const TRACKED_LVIEWS = new Map();
  7197. // Used for generating unique IDs for LViews.
  7198. let uniqueIdCounter = 0;
  7199. /** Gets a unique ID that can be assigned to an LView. */
  7200. function getUniqueLViewId() {
  7201. return uniqueIdCounter++;
  7202. }
  7203. /** Starts tracking an LView. */
  7204. function registerLView(lView) {
  7205. ngDevMode && assertNumber(lView[ID], 'LView must have an ID in order to be registered');
  7206. TRACKED_LVIEWS.set(lView[ID], lView);
  7207. }
  7208. /** Gets an LView by its unique ID. */
  7209. function getLViewById(id) {
  7210. ngDevMode && assertNumber(id, 'ID used for LView lookup must be a number');
  7211. return TRACKED_LVIEWS.get(id) || null;
  7212. }
  7213. /** Stops tracking an LView. */
  7214. function unregisterLView(lView) {
  7215. ngDevMode && assertNumber(lView[ID], 'Cannot stop tracking an LView that does not have an ID');
  7216. TRACKED_LVIEWS.delete(lView[ID]);
  7217. }
  7218. /** Gets the currently-tracked views. */
  7219. function getTrackedLViews() {
  7220. return TRACKED_LVIEWS;
  7221. }
  7222. /**
  7223. * The internal view context which is specific to a given DOM element, directive or
  7224. * component instance. Each value in here (besides the LView and element node details)
  7225. * can be present, null or undefined. If undefined then it implies the value has not been
  7226. * looked up yet, otherwise, if null, then a lookup was executed and nothing was found.
  7227. *
  7228. * Each value will get filled when the respective value is examined within the getContext
  7229. * function. The component, element and each directive instance will share the same instance
  7230. * of the context.
  7231. */
  7232. class LContext {
  7233. lViewId;
  7234. nodeIndex;
  7235. native;
  7236. /**
  7237. * The instance of the Component node.
  7238. */
  7239. component;
  7240. /**
  7241. * The list of active directives that exist on this element.
  7242. */
  7243. directives;
  7244. /**
  7245. * The map of local references (local reference name => element or directive instance) that
  7246. * exist on this element.
  7247. */
  7248. localRefs;
  7249. /** Component's parent view data. */
  7250. get lView() {
  7251. return getLViewById(this.lViewId);
  7252. }
  7253. constructor(
  7254. /**
  7255. * ID of the component's parent view data.
  7256. */
  7257. lViewId,
  7258. /**
  7259. * The index instance of the node.
  7260. */
  7261. nodeIndex,
  7262. /**
  7263. * The instance of the DOM node that is attached to the lNode.
  7264. */
  7265. native) {
  7266. this.lViewId = lViewId;
  7267. this.nodeIndex = nodeIndex;
  7268. this.native = native;
  7269. }
  7270. }
  7271. /**
  7272. * Returns the matching `LContext` data for a given DOM node, directive or component instance.
  7273. *
  7274. * This function will examine the provided DOM element, component, or directive instance\'s
  7275. * monkey-patched property to derive the `LContext` data. Once called then the monkey-patched
  7276. * value will be that of the newly created `LContext`.
  7277. *
  7278. * If the monkey-patched value is the `LView` instance then the context value for that
  7279. * target will be created and the monkey-patch reference will be updated. Therefore when this
  7280. * function is called it may mutate the provided element\'s, component\'s or any of the associated
  7281. * directive\'s monkey-patch values.
  7282. *
  7283. * If the monkey-patch value is not detected then the code will walk up the DOM until an element
  7284. * is found which contains a monkey-patch reference. When that occurs then the provided element
  7285. * will be updated with a new context (which is then returned). If the monkey-patch value is not
  7286. * detected for a component/directive instance then it will throw an error (all components and
  7287. * directives should be automatically monkey-patched by ivy).
  7288. *
  7289. * @param target Component, Directive or DOM Node.
  7290. */
  7291. function getLContext(target) {
  7292. let mpValue = readPatchedData(target);
  7293. if (mpValue) {
  7294. // only when it's an array is it considered an LView instance
  7295. // ... otherwise it's an already constructed LContext instance
  7296. if (isLView(mpValue)) {
  7297. const lView = mpValue;
  7298. let nodeIndex;
  7299. let component = undefined;
  7300. let directives = undefined;
  7301. if (isComponentInstance(target)) {
  7302. nodeIndex = findViaComponent(lView, target);
  7303. if (nodeIndex == -1) {
  7304. throw new Error('The provided component was not found in the application');
  7305. }
  7306. component = target;
  7307. }
  7308. else if (isDirectiveInstance(target)) {
  7309. nodeIndex = findViaDirective(lView, target);
  7310. if (nodeIndex == -1) {
  7311. throw new Error('The provided directive was not found in the application');
  7312. }
  7313. directives = getDirectivesAtNodeIndex(nodeIndex, lView);
  7314. }
  7315. else {
  7316. nodeIndex = findViaNativeElement(lView, target);
  7317. if (nodeIndex == -1) {
  7318. return null;
  7319. }
  7320. }
  7321. // the goal is not to fill the entire context full of data because the lookups
  7322. // are expensive. Instead, only the target data (the element, component, container, ICU
  7323. // expression or directive details) are filled into the context. If called multiple times
  7324. // with different target values then the missing target data will be filled in.
  7325. const native = unwrapRNode(lView[nodeIndex]);
  7326. const existingCtx = readPatchedData(native);
  7327. const context = existingCtx && !Array.isArray(existingCtx)
  7328. ? existingCtx
  7329. : createLContext(lView, nodeIndex, native);
  7330. // only when the component has been discovered then update the monkey-patch
  7331. if (component && context.component === undefined) {
  7332. context.component = component;
  7333. attachPatchData(context.component, context);
  7334. }
  7335. // only when the directives have been discovered then update the monkey-patch
  7336. if (directives && context.directives === undefined) {
  7337. context.directives = directives;
  7338. for (let i = 0; i < directives.length; i++) {
  7339. attachPatchData(directives[i], context);
  7340. }
  7341. }
  7342. attachPatchData(context.native, context);
  7343. mpValue = context;
  7344. }
  7345. }
  7346. else {
  7347. const rElement = target;
  7348. ngDevMode && assertDomNode(rElement);
  7349. // if the context is not found then we need to traverse upwards up the DOM
  7350. // to find the nearest element that has already been monkey patched with data
  7351. let parent = rElement;
  7352. while ((parent = parent.parentNode)) {
  7353. const parentContext = readPatchedData(parent);
  7354. if (parentContext) {
  7355. const lView = Array.isArray(parentContext) ? parentContext : parentContext.lView;
  7356. // the edge of the app was also reached here through another means
  7357. // (maybe because the DOM was changed manually).
  7358. if (!lView) {
  7359. return null;
  7360. }
  7361. const index = findViaNativeElement(lView, rElement);
  7362. if (index >= 0) {
  7363. const native = unwrapRNode(lView[index]);
  7364. const context = createLContext(lView, index, native);
  7365. attachPatchData(native, context);
  7366. mpValue = context;
  7367. break;
  7368. }
  7369. }
  7370. }
  7371. }
  7372. return mpValue || null;
  7373. }
  7374. /**
  7375. * Creates an empty instance of a `LContext` context
  7376. */
  7377. function createLContext(lView, nodeIndex, native) {
  7378. return new LContext(lView[ID], nodeIndex, native);
  7379. }
  7380. /**
  7381. * Takes a component instance and returns the view for that component.
  7382. *
  7383. * @param componentInstance
  7384. * @returns The component's view
  7385. */
  7386. function getComponentViewByInstance(componentInstance) {
  7387. let patchedData = readPatchedData(componentInstance);
  7388. let lView;
  7389. if (isLView(patchedData)) {
  7390. const contextLView = patchedData;
  7391. const nodeIndex = findViaComponent(contextLView, componentInstance);
  7392. lView = getComponentLViewByIndex(nodeIndex, contextLView);
  7393. const context = createLContext(contextLView, nodeIndex, lView[HOST]);
  7394. context.component = componentInstance;
  7395. attachPatchData(componentInstance, context);
  7396. attachPatchData(context.native, context);
  7397. }
  7398. else {
  7399. const context = patchedData;
  7400. const contextLView = context.lView;
  7401. ngDevMode && assertLView(contextLView);
  7402. lView = getComponentLViewByIndex(context.nodeIndex, contextLView);
  7403. }
  7404. return lView;
  7405. }
  7406. /**
  7407. * This property will be monkey-patched on elements, components and directives.
  7408. */
  7409. const MONKEY_PATCH_KEY_NAME = '__ngContext__';
  7410. /**
  7411. * Assigns the given data to the given target (which could be a component,
  7412. * directive or DOM node instance) using monkey-patching.
  7413. */
  7414. function attachPatchData(target, data) {
  7415. ngDevMode && assertDefined(target, 'Target expected');
  7416. // Only attach the ID of the view in order to avoid memory leaks (see #41047). We only do this
  7417. // for `LView`, because we have control over when an `LView` is created and destroyed, whereas
  7418. // we can't know when to remove an `LContext`.
  7419. if (isLView(data)) {
  7420. target[MONKEY_PATCH_KEY_NAME] = data[ID];
  7421. registerLView(data);
  7422. }
  7423. else {
  7424. target[MONKEY_PATCH_KEY_NAME] = data;
  7425. }
  7426. }
  7427. /**
  7428. * Returns the monkey-patch value data present on the target (which could be
  7429. * a component, directive or a DOM node).
  7430. */
  7431. function readPatchedData(target) {
  7432. ngDevMode && assertDefined(target, 'Target expected');
  7433. const data = target[MONKEY_PATCH_KEY_NAME];
  7434. return typeof data === 'number' ? getLViewById(data) : data || null;
  7435. }
  7436. function readPatchedLView(target) {
  7437. const value = readPatchedData(target);
  7438. if (value) {
  7439. return (isLView(value) ? value : value.lView);
  7440. }
  7441. return null;
  7442. }
  7443. function isComponentInstance(instance) {
  7444. return instance && instance.constructor && instance.constructor.ɵcmp;
  7445. }
  7446. function isDirectiveInstance(instance) {
  7447. return instance && instance.constructor && instance.constructor.ɵdir;
  7448. }
  7449. /**
  7450. * Locates the element within the given LView and returns the matching index
  7451. */
  7452. function findViaNativeElement(lView, target) {
  7453. const tView = lView[TVIEW];
  7454. for (let i = HEADER_OFFSET; i < tView.bindingStartIndex; i++) {
  7455. if (unwrapRNode(lView[i]) === target) {
  7456. return i;
  7457. }
  7458. }
  7459. return -1;
  7460. }
  7461. /**
  7462. * Locates the next tNode (child, sibling or parent).
  7463. */
  7464. function traverseNextElement(tNode) {
  7465. if (tNode.child) {
  7466. return tNode.child;
  7467. }
  7468. else if (tNode.next) {
  7469. return tNode.next;
  7470. }
  7471. else {
  7472. // Let's take the following template: <div><span>text</span></div><component/>
  7473. // After checking the text node, we need to find the next parent that has a "next" TNode,
  7474. // in this case the parent `div`, so that we can find the component.
  7475. while (tNode.parent && !tNode.parent.next) {
  7476. tNode = tNode.parent;
  7477. }
  7478. return tNode.parent && tNode.parent.next;
  7479. }
  7480. }
  7481. /**
  7482. * Locates the component within the given LView and returns the matching index
  7483. */
  7484. function findViaComponent(lView, componentInstance) {
  7485. const componentIndices = lView[TVIEW].components;
  7486. if (componentIndices) {
  7487. for (let i = 0; i < componentIndices.length; i++) {
  7488. const elementComponentIndex = componentIndices[i];
  7489. const componentView = getComponentLViewByIndex(elementComponentIndex, lView);
  7490. if (componentView[CONTEXT] === componentInstance) {
  7491. return elementComponentIndex;
  7492. }
  7493. }
  7494. }
  7495. else {
  7496. const rootComponentView = getComponentLViewByIndex(HEADER_OFFSET, lView);
  7497. const rootComponent = rootComponentView[CONTEXT];
  7498. if (rootComponent === componentInstance) {
  7499. // we are dealing with the root element here therefore we know that the
  7500. // element is the very first element after the HEADER data in the lView
  7501. return HEADER_OFFSET;
  7502. }
  7503. }
  7504. return -1;
  7505. }
  7506. /**
  7507. * Locates the directive within the given LView and returns the matching index
  7508. */
  7509. function findViaDirective(lView, directiveInstance) {
  7510. // if a directive is monkey patched then it will (by default)
  7511. // have a reference to the LView of the current view. The
  7512. // element bound to the directive being search lives somewhere
  7513. // in the view data. We loop through the nodes and check their
  7514. // list of directives for the instance.
  7515. let tNode = lView[TVIEW].firstChild;
  7516. while (tNode) {
  7517. const directiveIndexStart = tNode.directiveStart;
  7518. const directiveIndexEnd = tNode.directiveEnd;
  7519. for (let i = directiveIndexStart; i < directiveIndexEnd; i++) {
  7520. if (lView[i] === directiveInstance) {
  7521. return tNode.index;
  7522. }
  7523. }
  7524. tNode = traverseNextElement(tNode);
  7525. }
  7526. return -1;
  7527. }
  7528. /**
  7529. * Returns a list of directives applied to a node at a specific index. The list includes
  7530. * directives matched by selector and any host directives, but it excludes components.
  7531. * Use `getComponentAtNodeIndex` to find the component applied to a node.
  7532. *
  7533. * @param nodeIndex The node index
  7534. * @param lView The target view data
  7535. */
  7536. function getDirectivesAtNodeIndex(nodeIndex, lView) {
  7537. const tNode = lView[TVIEW].data[nodeIndex];
  7538. if (tNode.directiveStart === 0)
  7539. return EMPTY_ARRAY;
  7540. const results = [];
  7541. for (let i = tNode.directiveStart; i < tNode.directiveEnd; i++) {
  7542. const directiveInstance = lView[i];
  7543. if (!isComponentInstance(directiveInstance)) {
  7544. results.push(directiveInstance);
  7545. }
  7546. }
  7547. return results;
  7548. }
  7549. function getComponentAtNodeIndex(nodeIndex, lView) {
  7550. const tNode = lView[TVIEW].data[nodeIndex];
  7551. return isComponentHost(tNode) ? lView[tNode.directiveStart + tNode.componentOffset] : null;
  7552. }
  7553. /**
  7554. * Returns a map of local references (local reference name => element or directive instance) that
  7555. * exist on a given element.
  7556. */
  7557. function discoverLocalRefs(lView, nodeIndex) {
  7558. const tNode = lView[TVIEW].data[nodeIndex];
  7559. if (tNode && tNode.localNames) {
  7560. const result = {};
  7561. let localIndex = tNode.index + 1;
  7562. for (let i = 0; i < tNode.localNames.length; i += 2) {
  7563. result[tNode.localNames[i]] = lView[localIndex];
  7564. localIndex++;
  7565. }
  7566. return result;
  7567. }
  7568. return null;
  7569. }
  7570. /**
  7571. * Retrieve the root view from any component or `LView` by walking the parent `LView` until
  7572. * reaching the root `LView`.
  7573. *
  7574. * @param componentOrLView any component or `LView`
  7575. */
  7576. function getRootView(componentOrLView) {
  7577. ngDevMode && assertDefined(componentOrLView, 'component');
  7578. let lView = isLView(componentOrLView) ? componentOrLView : readPatchedLView(componentOrLView);
  7579. while (lView && !isRootView(lView)) {
  7580. lView = getLViewParent(lView);
  7581. }
  7582. ngDevMode && assertLView(lView);
  7583. return lView;
  7584. }
  7585. /**
  7586. * Returns the context information associated with the application where the target is situated. It
  7587. * does this by walking the parent views until it gets to the root view, then getting the context
  7588. * off of that.
  7589. *
  7590. * @param viewOrComponent the `LView` or component to get the root context for.
  7591. */
  7592. function getRootContext(viewOrComponent) {
  7593. const rootView = getRootView(viewOrComponent);
  7594. ngDevMode &&
  7595. assertDefined(rootView[CONTEXT], 'Root view has no context. Perhaps it is disconnected?');
  7596. return rootView[CONTEXT];
  7597. }
  7598. /**
  7599. * Gets the first `LContainer` in the LView or `null` if none exists.
  7600. */
  7601. function getFirstLContainer(lView) {
  7602. return getNearestLContainer(lView[CHILD_HEAD]);
  7603. }
  7604. /**
  7605. * Gets the next `LContainer` that is a sibling of the given container.
  7606. */
  7607. function getNextLContainer(container) {
  7608. return getNearestLContainer(container[NEXT]);
  7609. }
  7610. function getNearestLContainer(viewOrContainer) {
  7611. while (viewOrContainer !== null && !isLContainer(viewOrContainer)) {
  7612. viewOrContainer = viewOrContainer[NEXT];
  7613. }
  7614. return viewOrContainer;
  7615. }
  7616. /**
  7617. * Retrieves the component instance associated with a given DOM element.
  7618. *
  7619. * @usageNotes
  7620. * Given the following DOM structure:
  7621. *
  7622. * ```html
  7623. * <app-root>
  7624. * <div>
  7625. * <child-comp></child-comp>
  7626. * </div>
  7627. * </app-root>
  7628. * ```
  7629. *
  7630. * Calling `getComponent` on `<child-comp>` will return the instance of `ChildComponent`
  7631. * associated with this DOM element.
  7632. *
  7633. * Calling the function on `<app-root>` will return the `MyApp` instance.
  7634. *
  7635. *
  7636. * @param element DOM element from which the component should be retrieved.
  7637. * @returns Component instance associated with the element or `null` if there
  7638. * is no component associated with it.
  7639. *
  7640. * @publicApi
  7641. */
  7642. function getComponent(element) {
  7643. ngDevMode && assertDomElement(element);
  7644. const context = getLContext(element);
  7645. if (context === null)
  7646. return null;
  7647. if (context.component === undefined) {
  7648. const lView = context.lView;
  7649. if (lView === null) {
  7650. return null;
  7651. }
  7652. context.component = getComponentAtNodeIndex(context.nodeIndex, lView);
  7653. }
  7654. return context.component;
  7655. }
  7656. /**
  7657. * If inside an embedded view (e.g. `*ngIf` or `*ngFor`), retrieves the context of the embedded
  7658. * view that the element is part of. Otherwise retrieves the instance of the component whose view
  7659. * owns the element (in this case, the result is the same as calling `getOwningComponent`).
  7660. *
  7661. * @param element Element for which to get the surrounding component instance.
  7662. * @returns Instance of the component that is around the element or null if the element isn't
  7663. * inside any component.
  7664. *
  7665. * @publicApi
  7666. */
  7667. function getContext(element) {
  7668. assertDomElement(element);
  7669. const context = getLContext(element);
  7670. const lView = context ? context.lView : null;
  7671. return lView === null ? null : lView[CONTEXT];
  7672. }
  7673. /**
  7674. * Retrieves the component instance whose view contains the DOM element.
  7675. *
  7676. * For example, if `<child-comp>` is used in the template of `<app-comp>`
  7677. * (i.e. a `ViewChild` of `<app-comp>`), calling `getOwningComponent` on `<child-comp>`
  7678. * would return `<app-comp>`.
  7679. *
  7680. * @param elementOrDir DOM element, component or directive instance
  7681. * for which to retrieve the root components.
  7682. * @returns Component instance whose view owns the DOM element or null if the element is not
  7683. * part of a component view.
  7684. *
  7685. * @publicApi
  7686. */
  7687. function getOwningComponent(elementOrDir) {
  7688. const context = getLContext(elementOrDir);
  7689. let lView = context ? context.lView : null;
  7690. if (lView === null)
  7691. return null;
  7692. let parent;
  7693. while (lView[TVIEW].type === 2 /* TViewType.Embedded */ && (parent = getLViewParent(lView))) {
  7694. lView = parent;
  7695. }
  7696. return isRootView(lView) ? null : lView[CONTEXT];
  7697. }
  7698. /**
  7699. * Retrieves all root components associated with a DOM element, directive or component instance.
  7700. * Root components are those which have been bootstrapped by Angular.
  7701. *
  7702. * @param elementOrDir DOM element, component or directive instance
  7703. * for which to retrieve the root components.
  7704. * @returns Root components associated with the target object.
  7705. *
  7706. * @publicApi
  7707. */
  7708. function getRootComponents(elementOrDir) {
  7709. const lView = readPatchedLView(elementOrDir);
  7710. return lView !== null ? [getRootContext(lView)] : [];
  7711. }
  7712. /**
  7713. * Retrieves an `Injector` associated with an element, component or directive instance.
  7714. *
  7715. * @param elementOrDir DOM element, component or directive instance for which to
  7716. * retrieve the injector.
  7717. * @returns Injector associated with the element, component or directive instance.
  7718. *
  7719. * @publicApi
  7720. */
  7721. function getInjector(elementOrDir) {
  7722. const context = getLContext(elementOrDir);
  7723. const lView = context ? context.lView : null;
  7724. if (lView === null)
  7725. return Injector.NULL;
  7726. const tNode = lView[TVIEW].data[context.nodeIndex];
  7727. return new NodeInjector(tNode, lView);
  7728. }
  7729. /**
  7730. * Retrieve a set of injection tokens at a given DOM node.
  7731. *
  7732. * @param element Element for which the injection tokens should be retrieved.
  7733. */
  7734. function getInjectionTokens(element) {
  7735. const context = getLContext(element);
  7736. const lView = context ? context.lView : null;
  7737. if (lView === null)
  7738. return [];
  7739. const tView = lView[TVIEW];
  7740. const tNode = tView.data[context.nodeIndex];
  7741. const providerTokens = [];
  7742. const startIndex = tNode.providerIndexes & 1048575 /* TNodeProviderIndexes.ProvidersStartIndexMask */;
  7743. const endIndex = tNode.directiveEnd;
  7744. for (let i = startIndex; i < endIndex; i++) {
  7745. let value = tView.data[i];
  7746. if (isDirectiveDefHack(value)) {
  7747. // The fact that we sometimes store Type and sometimes DirectiveDef in this location is a
  7748. // design flaw. We should always store same type so that we can be monomorphic. The issue
  7749. // is that for Components/Directives we store the def instead the type. The correct behavior
  7750. // is that we should always be storing injectable type in this location.
  7751. value = value.type;
  7752. }
  7753. providerTokens.push(value);
  7754. }
  7755. return providerTokens;
  7756. }
  7757. /**
  7758. * Retrieves directive instances associated with a given DOM node. Does not include
  7759. * component instances.
  7760. *
  7761. * @usageNotes
  7762. * Given the following DOM structure:
  7763. *
  7764. * ```html
  7765. * <app-root>
  7766. * <button my-button></button>
  7767. * <my-comp></my-comp>
  7768. * </app-root>
  7769. * ```
  7770. *
  7771. * Calling `getDirectives` on `<button>` will return an array with an instance of the `MyButton`
  7772. * directive that is associated with the DOM node.
  7773. *
  7774. * Calling `getDirectives` on `<my-comp>` will return an empty array.
  7775. *
  7776. * @param node DOM node for which to get the directives.
  7777. * @returns Array of directives associated with the node.
  7778. *
  7779. * @publicApi
  7780. */
  7781. function getDirectives(node) {
  7782. // Skip text nodes because we can't have directives associated with them.
  7783. if (node instanceof Text) {
  7784. return [];
  7785. }
  7786. const context = getLContext(node);
  7787. const lView = context ? context.lView : null;
  7788. if (lView === null) {
  7789. return [];
  7790. }
  7791. const tView = lView[TVIEW];
  7792. const nodeIndex = context.nodeIndex;
  7793. if (!tView?.data[nodeIndex]) {
  7794. return [];
  7795. }
  7796. if (context.directives === undefined) {
  7797. context.directives = getDirectivesAtNodeIndex(nodeIndex, lView);
  7798. }
  7799. // The `directives` in this case are a named array called `LComponentView`. Clone the
  7800. // result so we don't expose an internal data structure in the user's console.
  7801. return context.directives === null ? [] : [...context.directives];
  7802. }
  7803. /**
  7804. * Returns the debug (partial) metadata for a particular directive or component instance.
  7805. * The function accepts an instance of a directive or component and returns the corresponding
  7806. * metadata.
  7807. *
  7808. * @param directiveOrComponentInstance Instance of a directive or component
  7809. * @returns metadata of the passed directive or component
  7810. *
  7811. * @publicApi
  7812. */
  7813. function getDirectiveMetadata$1(directiveOrComponentInstance) {
  7814. const { constructor } = directiveOrComponentInstance;
  7815. if (!constructor) {
  7816. throw new Error('Unable to find the instance constructor');
  7817. }
  7818. // In case a component inherits from a directive, we may have component and directive metadata
  7819. // To ensure we don't get the metadata of the directive, we want to call `getComponentDef` first.
  7820. const componentDef = getComponentDef(constructor);
  7821. if (componentDef) {
  7822. const inputs = extractInputDebugMetadata(componentDef.inputs);
  7823. return {
  7824. inputs,
  7825. outputs: componentDef.outputs,
  7826. encapsulation: componentDef.encapsulation,
  7827. changeDetection: componentDef.onPush
  7828. ? ChangeDetectionStrategy.OnPush
  7829. : ChangeDetectionStrategy.Default,
  7830. };
  7831. }
  7832. const directiveDef = getDirectiveDef(constructor);
  7833. if (directiveDef) {
  7834. const inputs = extractInputDebugMetadata(directiveDef.inputs);
  7835. return { inputs, outputs: directiveDef.outputs };
  7836. }
  7837. return null;
  7838. }
  7839. /**
  7840. * Retrieve map of local references.
  7841. *
  7842. * The references are retrieved as a map of local reference name to element or directive instance.
  7843. *
  7844. * @param target DOM element, component or directive instance for which to retrieve
  7845. * the local references.
  7846. */
  7847. function getLocalRefs(target) {
  7848. const context = getLContext(target);
  7849. if (context === null)
  7850. return {};
  7851. if (context.localRefs === undefined) {
  7852. const lView = context.lView;
  7853. if (lView === null) {
  7854. return {};
  7855. }
  7856. context.localRefs = discoverLocalRefs(lView, context.nodeIndex);
  7857. }
  7858. return context.localRefs || {};
  7859. }
  7860. /**
  7861. * Retrieves the host element of a component or directive instance.
  7862. * The host element is the DOM element that matched the selector of the directive.
  7863. *
  7864. * @param componentOrDirective Component or directive instance for which the host
  7865. * element should be retrieved.
  7866. * @returns Host element of the target.
  7867. *
  7868. * @publicApi
  7869. */
  7870. function getHostElement(componentOrDirective) {
  7871. return getLContext(componentOrDirective).native;
  7872. }
  7873. /**
  7874. * Retrieves a list of event listeners associated with a DOM element. The list does include host
  7875. * listeners, but it does not include event listeners defined outside of the Angular context
  7876. * (e.g. through `addEventListener`).
  7877. *
  7878. * @usageNotes
  7879. * Given the following DOM structure:
  7880. *
  7881. * ```html
  7882. * <app-root>
  7883. * <div (click)="doSomething()"></div>
  7884. * </app-root>
  7885. * ```
  7886. *
  7887. * Calling `getListeners` on `<div>` will return an object that looks as follows:
  7888. *
  7889. * ```ts
  7890. * {
  7891. * name: 'click',
  7892. * element: <div>,
  7893. * callback: () => doSomething(),
  7894. * useCapture: false
  7895. * }
  7896. * ```
  7897. *
  7898. * @param element Element for which the DOM listeners should be retrieved.
  7899. * @returns Array of event listeners on the DOM element.
  7900. *
  7901. * @publicApi
  7902. */
  7903. function getListeners(element) {
  7904. ngDevMode && assertDomElement(element);
  7905. const lContext = getLContext(element);
  7906. const lView = lContext === null ? null : lContext.lView;
  7907. if (lView === null)
  7908. return [];
  7909. const tView = lView[TVIEW];
  7910. const lCleanup = lView[CLEANUP];
  7911. const tCleanup = tView.cleanup;
  7912. const listeners = [];
  7913. if (tCleanup && lCleanup) {
  7914. for (let i = 0; i < tCleanup.length;) {
  7915. const firstParam = tCleanup[i++];
  7916. const secondParam = tCleanup[i++];
  7917. if (typeof firstParam === 'string') {
  7918. const name = firstParam;
  7919. const listenerElement = unwrapRNode(lView[secondParam]);
  7920. const callback = lCleanup[tCleanup[i++]];
  7921. const useCaptureOrIndx = tCleanup[i++];
  7922. // if useCaptureOrIndx is boolean then report it as is.
  7923. // if useCaptureOrIndx is positive number then it in unsubscribe method
  7924. // if useCaptureOrIndx is negative number then it is a Subscription
  7925. const type = typeof useCaptureOrIndx === 'boolean' || useCaptureOrIndx >= 0 ? 'dom' : 'output';
  7926. const useCapture = typeof useCaptureOrIndx === 'boolean' ? useCaptureOrIndx : false;
  7927. if (element == listenerElement) {
  7928. listeners.push({ element, name, callback, useCapture, type });
  7929. }
  7930. }
  7931. }
  7932. }
  7933. listeners.sort(sortListeners);
  7934. return listeners;
  7935. }
  7936. function sortListeners(a, b) {
  7937. if (a.name == b.name)
  7938. return 0;
  7939. return a.name < b.name ? -1 : 1;
  7940. }
  7941. /**
  7942. * This function should not exist because it is megamorphic and only mostly correct.
  7943. *
  7944. * See call site for more info.
  7945. */
  7946. function isDirectiveDefHack(obj) {
  7947. return (obj.type !== undefined &&
  7948. obj.declaredInputs !== undefined &&
  7949. obj.findHostDirectiveDefs !== undefined);
  7950. }
  7951. /** Asserts that a value is a DOM Element. */
  7952. function assertDomElement(value) {
  7953. if (typeof Element !== 'undefined' && !(value instanceof Element)) {
  7954. throw new Error('Expecting instance of DOM Element');
  7955. }
  7956. }
  7957. /**
  7958. * A directive definition holds additional metadata using bitwise flags to indicate
  7959. * for example whether it is signal based.
  7960. *
  7961. * This information needs to be separate from the `publicName -> minifiedName`
  7962. * mappings for backwards compatibility.
  7963. */
  7964. function extractInputDebugMetadata(inputs) {
  7965. const res = {};
  7966. for (const key in inputs) {
  7967. if (inputs.hasOwnProperty(key)) {
  7968. const value = inputs[key];
  7969. if (value !== undefined) {
  7970. res[key] = value[0];
  7971. }
  7972. }
  7973. }
  7974. return res;
  7975. }
  7976. /**
  7977. * Most of the use of `document` in Angular is from within the DI system so it is possible to simply
  7978. * inject the `DOCUMENT` token and are done.
  7979. *
  7980. * Ivy is special because it does not rely upon the DI and must get hold of the document some other
  7981. * way.
  7982. *
  7983. * The solution is to define `getDocument()` and `setDocument()` top-level functions for ivy.
  7984. * Wherever ivy needs the global document, it calls `getDocument()` instead.
  7985. *
  7986. * When running ivy outside of a browser environment, it is necessary to call `setDocument()` to
  7987. * tell ivy what the global `document` is.
  7988. *
  7989. * Angular does this for us in each of the standard platforms (`Browser` and `Server`)
  7990. * by calling `setDocument()` when providing the `DOCUMENT` token.
  7991. */
  7992. let DOCUMENT = undefined;
  7993. /**
  7994. * Tell ivy what the `document` is for this platform.
  7995. *
  7996. * It is only necessary to call this if the current platform is not a browser.
  7997. *
  7998. * @param document The object representing the global `document` in this environment.
  7999. */
  8000. function setDocument(document) {
  8001. DOCUMENT = document;
  8002. }
  8003. /**
  8004. * Access the object that represents the `document` for this platform.
  8005. *
  8006. * Ivy calls this whenever it needs to access the `document` object.
  8007. * For example to create the renderer or to do sanitization.
  8008. */
  8009. function getDocument() {
  8010. if (DOCUMENT !== undefined) {
  8011. return DOCUMENT;
  8012. }
  8013. else if (typeof document !== 'undefined') {
  8014. return document;
  8015. }
  8016. throw new RuntimeError(210 /* RuntimeErrorCode.MISSING_DOCUMENT */, (typeof ngDevMode === 'undefined' || ngDevMode) &&
  8017. `The document object is not available in this context. Make sure the DOCUMENT injection token is provided.`);
  8018. // No "document" can be found. This should only happen if we are running ivy outside Angular and
  8019. // the current platform is not a browser. Since this is not a supported scenario at the moment
  8020. // this should not happen in Angular apps.
  8021. // Once we support running ivy outside of Angular we will need to publish `setDocument()` as a
  8022. // public API.
  8023. }
  8024. /**
  8025. * A DI token representing a string ID, used
  8026. * primarily for prefixing application attributes and CSS styles when
  8027. * {@link ViewEncapsulation#Emulated} is being used.
  8028. *
  8029. * The token is needed in cases when multiple applications are bootstrapped on a page
  8030. * (for example, using `bootstrapApplication` calls). In this case, ensure that those applications
  8031. * have different `APP_ID` value setup. For example:
  8032. *
  8033. * ```ts
  8034. * bootstrapApplication(ComponentA, {
  8035. * providers: [
  8036. * { provide: APP_ID, useValue: 'app-a' },
  8037. * // ... other providers ...
  8038. * ]
  8039. * });
  8040. *
  8041. * bootstrapApplication(ComponentB, {
  8042. * providers: [
  8043. * { provide: APP_ID, useValue: 'app-b' },
  8044. * // ... other providers ...
  8045. * ]
  8046. * });
  8047. * ```
  8048. *
  8049. * By default, when there is only one application bootstrapped, you don't need to provide the
  8050. * `APP_ID` token (the `ng` will be used as an app ID).
  8051. *
  8052. * @publicApi
  8053. */
  8054. const APP_ID = new InjectionToken(ngDevMode ? 'AppId' : '', {
  8055. providedIn: 'root',
  8056. factory: () => DEFAULT_APP_ID,
  8057. });
  8058. /** Default value of the `APP_ID` token. */
  8059. const DEFAULT_APP_ID = 'ng';
  8060. /**
  8061. * A function that is executed when a platform is initialized.
  8062. *
  8063. * @deprecated from v19.0.0, use providePlatformInitializer instead
  8064. *
  8065. * @see {@link providePlatformInitializer}
  8066. *
  8067. * @publicApi
  8068. */
  8069. const PLATFORM_INITIALIZER = new InjectionToken(ngDevMode ? 'Platform Initializer' : '');
  8070. /**
  8071. * A token that indicates an opaque platform ID.
  8072. * @publicApi
  8073. */
  8074. const PLATFORM_ID = new InjectionToken(ngDevMode ? 'Platform ID' : '', {
  8075. providedIn: 'platform',
  8076. factory: () => 'unknown', // set a default platform name, when none set explicitly
  8077. });
  8078. /**
  8079. * A DI token that indicates the root directory of
  8080. * the application
  8081. * @publicApi
  8082. * @deprecated
  8083. */
  8084. const PACKAGE_ROOT_URL = new InjectionToken(ngDevMode ? 'Application Packages Root URL' : '');
  8085. // We keep this token here, rather than the animations package, so that modules that only care
  8086. // about which animations module is loaded (e.g. the CDK) can retrieve it without having to
  8087. // include extra dependencies. See #44970 for more context.
  8088. /**
  8089. * A [DI token](api/core/InjectionToken) that indicates which animations
  8090. * module has been loaded.
  8091. * @publicApi
  8092. */
  8093. const ANIMATION_MODULE_TYPE = new InjectionToken(ngDevMode ? 'AnimationModuleType' : '');
  8094. // TODO(crisbeto): link to CSP guide here.
  8095. /**
  8096. * Token used to configure the [Content Security Policy](https://web.dev/strict-csp/) nonce that
  8097. * Angular will apply when inserting inline styles. If not provided, Angular will look up its value
  8098. * from the `ngCspNonce` attribute of the application root node.
  8099. *
  8100. * @publicApi
  8101. */
  8102. const CSP_NONCE = new InjectionToken(ngDevMode ? 'CSP nonce' : '', {
  8103. providedIn: 'root',
  8104. factory: () => {
  8105. // Ideally we wouldn't have to use `querySelector` here since we know that the nonce will be on
  8106. // the root node, but because the token value is used in renderers, it has to be available
  8107. // *very* early in the bootstrapping process. This should be a fairly shallow search, because
  8108. // the app won't have been added to the DOM yet. Some approaches that were considered:
  8109. // 1. Find the root node through `ApplicationRef.components[i].location` - normally this would
  8110. // be enough for our purposes, but the token is injected very early so the `components` array
  8111. // isn't populated yet.
  8112. // 2. Find the root `LView` through the current `LView` - renderers are a prerequisite to
  8113. // creating the `LView`. This means that no `LView` will have been entered when this factory is
  8114. // invoked for the root component.
  8115. // 3. Have the token factory return `() => string` which is invoked when a nonce is requested -
  8116. // the slightly later execution does allow us to get an `LView` reference, but the fact that
  8117. // it is a function means that it could be executed at *any* time (including immediately) which
  8118. // may lead to weird bugs.
  8119. // 4. Have the `ComponentFactory` read the attribute and provide it to the injector under the
  8120. // hood - has the same problem as #1 and #2 in that the renderer is used to query for the root
  8121. // node and the nonce value needs to be available when the renderer is created.
  8122. return getDocument().body?.querySelector('[ngCspNonce]')?.getAttribute('ngCspNonce') || null;
  8123. },
  8124. });
  8125. const IMAGE_CONFIG_DEFAULTS = {
  8126. breakpoints: [16, 32, 48, 64, 96, 128, 256, 384, 640, 750, 828, 1080, 1200, 1920, 2048, 3840],
  8127. placeholderResolution: 30,
  8128. disableImageSizeWarning: false,
  8129. disableImageLazyLoadWarning: false,
  8130. };
  8131. /**
  8132. * Injection token that configures the image optimized image functionality.
  8133. * See {@link ImageConfig} for additional information about parameters that
  8134. * can be used.
  8135. *
  8136. * @see {@link NgOptimizedImage}
  8137. * @see {@link ImageConfig}
  8138. * @publicApi
  8139. */
  8140. const IMAGE_CONFIG = new InjectionToken(ngDevMode ? 'ImageConfig' : '', {
  8141. providedIn: 'root',
  8142. factory: () => IMAGE_CONFIG_DEFAULTS,
  8143. });
  8144. /**
  8145. * Create a `StateKey<T>` that can be used to store value of type T with `TransferState`.
  8146. *
  8147. * Example:
  8148. *
  8149. * ```ts
  8150. * const COUNTER_KEY = makeStateKey<number>('counter');
  8151. * let value = 10;
  8152. *
  8153. * transferState.set(COUNTER_KEY, value);
  8154. * ```
  8155. *
  8156. * @publicApi
  8157. */
  8158. function makeStateKey(key) {
  8159. return key;
  8160. }
  8161. function initTransferState() {
  8162. const transferState = new TransferState();
  8163. if (typeof ngServerMode === 'undefined' || !ngServerMode) {
  8164. transferState.store = retrieveTransferredState(getDocument(), inject(APP_ID));
  8165. }
  8166. return transferState;
  8167. }
  8168. /**
  8169. * A key value store that is transferred from the application on the server side to the application
  8170. * on the client side.
  8171. *
  8172. * The `TransferState` is available as an injectable token.
  8173. * On the client, just inject this token using DI and use it, it will be lazily initialized.
  8174. * On the server it's already included if `renderApplication` function is used. Otherwise, import
  8175. * the `ServerTransferStateModule` module to make the `TransferState` available.
  8176. *
  8177. * The values in the store are serialized/deserialized using JSON.stringify/JSON.parse. So only
  8178. * boolean, number, string, null and non-class objects will be serialized and deserialized in a
  8179. * non-lossy manner.
  8180. *
  8181. * @publicApi
  8182. */
  8183. class TransferState {
  8184. /** @nocollapse */
  8185. static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
  8186. token: TransferState,
  8187. providedIn: 'root',
  8188. factory: initTransferState,
  8189. });
  8190. /** @internal */
  8191. store = {};
  8192. onSerializeCallbacks = {};
  8193. /**
  8194. * Get the value corresponding to a key. Return `defaultValue` if key is not found.
  8195. */
  8196. get(key, defaultValue) {
  8197. return this.store[key] !== undefined ? this.store[key] : defaultValue;
  8198. }
  8199. /**
  8200. * Set the value corresponding to a key.
  8201. */
  8202. set(key, value) {
  8203. this.store[key] = value;
  8204. }
  8205. /**
  8206. * Remove a key from the store.
  8207. */
  8208. remove(key) {
  8209. delete this.store[key];
  8210. }
  8211. /**
  8212. * Test whether a key exists in the store.
  8213. */
  8214. hasKey(key) {
  8215. return this.store.hasOwnProperty(key);
  8216. }
  8217. /**
  8218. * Indicates whether the state is empty.
  8219. */
  8220. get isEmpty() {
  8221. return Object.keys(this.store).length === 0;
  8222. }
  8223. /**
  8224. * Register a callback to provide the value for a key when `toJson` is called.
  8225. */
  8226. onSerialize(key, callback) {
  8227. this.onSerializeCallbacks[key] = callback;
  8228. }
  8229. /**
  8230. * Serialize the current state of the store to JSON.
  8231. */
  8232. toJson() {
  8233. // Call the onSerialize callbacks and put those values into the store.
  8234. for (const key in this.onSerializeCallbacks) {
  8235. if (this.onSerializeCallbacks.hasOwnProperty(key)) {
  8236. try {
  8237. this.store[key] = this.onSerializeCallbacks[key]();
  8238. }
  8239. catch (e) {
  8240. console.warn('Exception in onSerialize callback: ', e);
  8241. }
  8242. }
  8243. }
  8244. // Escape script tag to avoid break out of <script> tag in serialized output.
  8245. // Encoding of `<` is the same behaviour as G3 script_builders.
  8246. return JSON.stringify(this.store).replace(/</g, '\\u003C');
  8247. }
  8248. }
  8249. function retrieveTransferredState(doc, appId) {
  8250. // Locate the script tag with the JSON data transferred from the server.
  8251. // The id of the script tag is set to the Angular appId + 'state'.
  8252. const script = doc.getElementById(appId + '-state');
  8253. if (script?.textContent) {
  8254. try {
  8255. // Avoid using any here as it triggers lint errors in google3 (any is not allowed).
  8256. // Decoding of `<` is done of the box by browsers and node.js, same behaviour as G3
  8257. // script_builders.
  8258. return JSON.parse(script.textContent);
  8259. }
  8260. catch (e) {
  8261. console.warn('Exception while restoring TransferState for app ' + appId, e);
  8262. }
  8263. }
  8264. return {};
  8265. }
  8266. /** Encodes that the node lookup should start from the host node of this component. */
  8267. const REFERENCE_NODE_HOST = 'h';
  8268. /** Encodes that the node lookup should start from the document body node. */
  8269. const REFERENCE_NODE_BODY = 'b';
  8270. const NODE_NAVIGATION_STEP_FIRST_CHILD = 'f';
  8271. const NODE_NAVIGATION_STEP_NEXT_SIBLING = 'n';
  8272. /**
  8273. * Keys within serialized view data structure to represent various
  8274. * parts. See the `SerializedView` interface below for additional information.
  8275. */
  8276. const ELEMENT_CONTAINERS = 'e';
  8277. const TEMPLATES = 't';
  8278. const CONTAINERS = 'c';
  8279. const MULTIPLIER = 'x';
  8280. const NUM_ROOT_NODES = 'r';
  8281. const TEMPLATE_ID = 'i'; // as it's also an "id"
  8282. const NODES = 'n';
  8283. const DISCONNECTED_NODES = 'd';
  8284. const I18N_DATA = 'l';
  8285. const DEFER_BLOCK_ID = 'di';
  8286. const DEFER_BLOCK_STATE$1 = 's';
  8287. const DEFER_PARENT_BLOCK_ID = 'p';
  8288. const DEFER_HYDRATE_TRIGGERS = 't';
  8289. /**
  8290. * Internal token that specifies whether DOM reuse logic
  8291. * during hydration is enabled.
  8292. */
  8293. const IS_HYDRATION_DOM_REUSE_ENABLED = new InjectionToken(typeof ngDevMode === 'undefined' || !!ngDevMode ? 'IS_HYDRATION_DOM_REUSE_ENABLED' : '');
  8294. // By default (in client rendering mode), we remove all the contents
  8295. // of the host element and render an application after that.
  8296. const PRESERVE_HOST_CONTENT_DEFAULT = false;
  8297. /**
  8298. * Internal token that indicates whether host element content should be
  8299. * retained during the bootstrap.
  8300. */
  8301. const PRESERVE_HOST_CONTENT = new InjectionToken(typeof ngDevMode === 'undefined' || !!ngDevMode ? 'PRESERVE_HOST_CONTENT' : '', {
  8302. providedIn: 'root',
  8303. factory: () => PRESERVE_HOST_CONTENT_DEFAULT,
  8304. });
  8305. /**
  8306. * Internal token that indicates whether hydration support for i18n
  8307. * is enabled.
  8308. */
  8309. const IS_I18N_HYDRATION_ENABLED = new InjectionToken(typeof ngDevMode === 'undefined' || !!ngDevMode ? 'IS_I18N_HYDRATION_ENABLED' : '');
  8310. /**
  8311. * Internal token that indicates whether event replay support for SSR
  8312. * is enabled.
  8313. */
  8314. const IS_EVENT_REPLAY_ENABLED = new InjectionToken(typeof ngDevMode === 'undefined' || !!ngDevMode ? 'IS_EVENT_REPLAY_ENABLED' : '');
  8315. const EVENT_REPLAY_ENABLED_DEFAULT = false;
  8316. /**
  8317. * Internal token that indicates whether incremental hydration support
  8318. * is enabled.
  8319. */
  8320. const IS_INCREMENTAL_HYDRATION_ENABLED = new InjectionToken(typeof ngDevMode === 'undefined' || !!ngDevMode ? 'IS_INCREMENTAL_HYDRATION_ENABLED' : '');
  8321. /**
  8322. * A map of DOM elements with `jsaction` attributes grouped by action names.
  8323. */
  8324. const JSACTION_BLOCK_ELEMENT_MAP = new InjectionToken(ngDevMode ? 'JSACTION_BLOCK_ELEMENT_MAP' : '', {
  8325. providedIn: 'root',
  8326. factory: () => new Map(),
  8327. });
  8328. /** Actions that are supported by the tracing framework. */
  8329. var TracingAction;
  8330. (function (TracingAction) {
  8331. TracingAction[TracingAction["CHANGE_DETECTION"] = 0] = "CHANGE_DETECTION";
  8332. TracingAction[TracingAction["AFTER_NEXT_RENDER"] = 1] = "AFTER_NEXT_RENDER";
  8333. })(TracingAction || (TracingAction = {}));
  8334. /**
  8335. * Injection token for a `TracingService`, optionally provided.
  8336. */
  8337. const TracingService = new InjectionToken(ngDevMode ? 'TracingService' : '');
  8338. const markedFeatures = new Set();
  8339. // tslint:disable:ban
  8340. /**
  8341. * A guarded `performance.mark` for feature marking.
  8342. *
  8343. * This method exists because while all supported browser and node.js version supported by Angular
  8344. * support performance.mark API. This is not the case for other environments such as JSDOM and
  8345. * Cloudflare workers.
  8346. */
  8347. function performanceMarkFeature(feature) {
  8348. if (markedFeatures.has(feature)) {
  8349. return;
  8350. }
  8351. markedFeatures.add(feature);
  8352. performance?.mark?.('mark_feature_usage', { detail: { feature } });
  8353. }
  8354. /**
  8355. * Asserts that the current stack frame is not within a reactive context. Useful
  8356. * to disallow certain code from running inside a reactive context (see {@link /api/core/rxjs/toSignal toSignal})
  8357. *
  8358. * @param debugFn a reference to the function making the assertion (used for the error message).
  8359. *
  8360. * @publicApi
  8361. */
  8362. function assertNotInReactiveContext(debugFn, extraContext) {
  8363. // Taking a `Function` instead of a string name here prevents the un-minified name of the function
  8364. // from being retained in the bundle regardless of minification.
  8365. if (getActiveConsumer() !== null) {
  8366. throw new RuntimeError(-602 /* RuntimeErrorCode.ASSERTION_NOT_INSIDE_REACTIVE_CONTEXT */, ngDevMode &&
  8367. `${debugFn.name}() cannot be called from within a reactive context.${extraContext ? ` ${extraContext}` : ''}`);
  8368. }
  8369. }
  8370. class ViewContext {
  8371. view;
  8372. node;
  8373. constructor(view, node) {
  8374. this.view = view;
  8375. this.node = node;
  8376. }
  8377. /**
  8378. * @internal
  8379. * @nocollapse
  8380. */
  8381. static __NG_ELEMENT_ID__ = injectViewContext;
  8382. }
  8383. function injectViewContext() {
  8384. return new ViewContext(getLView(), getCurrentTNode());
  8385. }
  8386. /**
  8387. * The phase to run an `afterRender` or `afterNextRender` callback in.
  8388. *
  8389. * Callbacks in the same phase run in the order they are registered. Phases run in the
  8390. * following order after each render:
  8391. *
  8392. * 1. `AfterRenderPhase.EarlyRead`
  8393. * 2. `AfterRenderPhase.Write`
  8394. * 3. `AfterRenderPhase.MixedReadWrite`
  8395. * 4. `AfterRenderPhase.Read`
  8396. *
  8397. * Angular is unable to verify or enforce that phases are used correctly, and instead
  8398. * relies on each developer to follow the guidelines documented for each value and
  8399. * carefully choose the appropriate one, refactoring their code if necessary. By doing
  8400. * so, Angular is better able to minimize the performance degradation associated with
  8401. * manual DOM access, ensuring the best experience for the end users of your application
  8402. * or library.
  8403. *
  8404. * @deprecated Specify the phase for your callback to run in by passing a spec-object as the first
  8405. * parameter to `afterRender` or `afterNextRender` instead of a function.
  8406. */
  8407. var AfterRenderPhase;
  8408. (function (AfterRenderPhase) {
  8409. /**
  8410. * Use `AfterRenderPhase.EarlyRead` for callbacks that only need to **read** from the
  8411. * DOM before a subsequent `AfterRenderPhase.Write` callback, for example to perform
  8412. * custom layout that the browser doesn't natively support. Prefer the
  8413. * `AfterRenderPhase.Read` phase if reading can wait until after the write phase.
  8414. * **Never** write to the DOM in this phase.
  8415. *
  8416. * <div class="docs-alert docs-alert-important">
  8417. *
  8418. * Using this value can degrade performance.
  8419. * Instead, prefer using built-in browser functionality when possible.
  8420. *
  8421. * </div>
  8422. */
  8423. AfterRenderPhase[AfterRenderPhase["EarlyRead"] = 0] = "EarlyRead";
  8424. /**
  8425. * Use `AfterRenderPhase.Write` for callbacks that only **write** to the DOM. **Never**
  8426. * read from the DOM in this phase.
  8427. */
  8428. AfterRenderPhase[AfterRenderPhase["Write"] = 1] = "Write";
  8429. /**
  8430. * Use `AfterRenderPhase.MixedReadWrite` for callbacks that read from or write to the
  8431. * DOM, that haven't been refactored to use a different phase. **Never** use this phase if
  8432. * it is possible to divide the work among the other phases instead.
  8433. *
  8434. * <div class="docs-alert docs-alert-critical">
  8435. *
  8436. * Using this value can **significantly** degrade performance.
  8437. * Instead, prefer dividing work into the appropriate phase callbacks.
  8438. *
  8439. * </div>
  8440. */
  8441. AfterRenderPhase[AfterRenderPhase["MixedReadWrite"] = 2] = "MixedReadWrite";
  8442. /**
  8443. * Use `AfterRenderPhase.Read` for callbacks that only **read** from the DOM. **Never**
  8444. * write to the DOM in this phase.
  8445. */
  8446. AfterRenderPhase[AfterRenderPhase["Read"] = 3] = "Read";
  8447. })(AfterRenderPhase || (AfterRenderPhase = {}));
  8448. class AfterRenderManager {
  8449. impl = null;
  8450. execute() {
  8451. this.impl?.execute();
  8452. }
  8453. /** @nocollapse */
  8454. static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
  8455. token: AfterRenderManager,
  8456. providedIn: 'root',
  8457. factory: () => new AfterRenderManager(),
  8458. });
  8459. }
  8460. const AFTER_RENDER_PHASES = /* @__PURE__ **/ (() => [
  8461. AfterRenderPhase.EarlyRead,
  8462. AfterRenderPhase.Write,
  8463. AfterRenderPhase.MixedReadWrite,
  8464. AfterRenderPhase.Read,
  8465. ])();
  8466. class AfterRenderImpl {
  8467. ngZone = inject(NgZone);
  8468. scheduler = inject(ChangeDetectionScheduler);
  8469. errorHandler = inject(ErrorHandler, { optional: true });
  8470. /** Current set of active sequences. */
  8471. sequences = new Set();
  8472. /** Tracks registrations made during the current set of executions. */
  8473. deferredRegistrations = new Set();
  8474. /** Whether the `AfterRenderManager` is currently executing hooks. */
  8475. executing = false;
  8476. constructor() {
  8477. // Inject the tracing service to make sure it's initialized.
  8478. inject(TracingService, { optional: true });
  8479. }
  8480. /**
  8481. * Run the sequence of phases of hooks, once through. As a result of executing some hooks, more
  8482. * might be scheduled.
  8483. */
  8484. execute() {
  8485. const hasSequencesToExecute = this.sequences.size > 0;
  8486. if (hasSequencesToExecute) {
  8487. profiler(16 /* ProfilerEvent.AfterRenderHooksStart */);
  8488. }
  8489. this.executing = true;
  8490. for (const phase of AFTER_RENDER_PHASES) {
  8491. for (const sequence of this.sequences) {
  8492. if (sequence.erroredOrDestroyed || !sequence.hooks[phase]) {
  8493. continue;
  8494. }
  8495. try {
  8496. sequence.pipelinedValue = this.ngZone.runOutsideAngular(() => this.maybeTrace(() => {
  8497. const hookFn = sequence.hooks[phase];
  8498. const value = hookFn(sequence.pipelinedValue);
  8499. return value;
  8500. }, sequence.snapshot));
  8501. }
  8502. catch (err) {
  8503. sequence.erroredOrDestroyed = true;
  8504. this.errorHandler?.handleError(err);
  8505. }
  8506. }
  8507. }
  8508. this.executing = false;
  8509. // Cleanup step to reset sequence state and also collect one-shot sequences for removal.
  8510. for (const sequence of this.sequences) {
  8511. sequence.afterRun();
  8512. if (sequence.once) {
  8513. this.sequences.delete(sequence);
  8514. // Destroy the sequence so its on destroy callbacks can be cleaned up
  8515. // immediately, instead of waiting until the injector is destroyed.
  8516. sequence.destroy();
  8517. }
  8518. }
  8519. for (const sequence of this.deferredRegistrations) {
  8520. this.sequences.add(sequence);
  8521. }
  8522. if (this.deferredRegistrations.size > 0) {
  8523. this.scheduler.notify(7 /* NotificationSource.RenderHook */);
  8524. }
  8525. this.deferredRegistrations.clear();
  8526. if (hasSequencesToExecute) {
  8527. profiler(17 /* ProfilerEvent.AfterRenderHooksEnd */);
  8528. }
  8529. }
  8530. register(sequence) {
  8531. const { view } = sequence;
  8532. if (view !== undefined) {
  8533. // Delay adding it to the manager, add it to the view instead.
  8534. (view[AFTER_RENDER_SEQUENCES_TO_ADD] ??= []).push(sequence);
  8535. // Mark the view for traversal to ensure we eventually schedule the afterNextRender.
  8536. markAncestorsForTraversal(view);
  8537. view[FLAGS] |= 8192 /* LViewFlags.HasChildViewsToRefresh */;
  8538. }
  8539. else if (!this.executing) {
  8540. this.addSequence(sequence);
  8541. }
  8542. else {
  8543. this.deferredRegistrations.add(sequence);
  8544. }
  8545. }
  8546. addSequence(sequence) {
  8547. this.sequences.add(sequence);
  8548. // Trigger an `ApplicationRef.tick()` if one is not already pending/running, because we have a
  8549. // new render hook that needs to run.
  8550. this.scheduler.notify(7 /* NotificationSource.RenderHook */);
  8551. }
  8552. unregister(sequence) {
  8553. if (this.executing && this.sequences.has(sequence)) {
  8554. // We can't remove an `AfterRenderSequence` in the middle of iteration.
  8555. // Instead, mark it as destroyed so it doesn't run any more, and mark it as one-shot so it'll
  8556. // be removed at the end of the current execution.
  8557. sequence.erroredOrDestroyed = true;
  8558. sequence.pipelinedValue = undefined;
  8559. sequence.once = true;
  8560. }
  8561. else {
  8562. // It's safe to directly remove this sequence.
  8563. this.sequences.delete(sequence);
  8564. this.deferredRegistrations.delete(sequence);
  8565. }
  8566. }
  8567. maybeTrace(fn, snapshot) {
  8568. // Only trace the execution if the snapshot is defined.
  8569. return snapshot ? snapshot.run(TracingAction.AFTER_NEXT_RENDER, fn) : fn();
  8570. }
  8571. /** @nocollapse */
  8572. static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
  8573. token: AfterRenderImpl,
  8574. providedIn: 'root',
  8575. factory: () => new AfterRenderImpl(),
  8576. });
  8577. }
  8578. class AfterRenderSequence {
  8579. impl;
  8580. hooks;
  8581. view;
  8582. once;
  8583. snapshot;
  8584. /**
  8585. * Whether this sequence errored or was destroyed during this execution, and hooks should no
  8586. * longer run for it.
  8587. */
  8588. erroredOrDestroyed = false;
  8589. /**
  8590. * The value returned by the last hook execution (if any), ready to be pipelined into the next
  8591. * one.
  8592. */
  8593. pipelinedValue = undefined;
  8594. unregisterOnDestroy;
  8595. constructor(impl, hooks, view, once, destroyRef, snapshot = null) {
  8596. this.impl = impl;
  8597. this.hooks = hooks;
  8598. this.view = view;
  8599. this.once = once;
  8600. this.snapshot = snapshot;
  8601. this.unregisterOnDestroy = destroyRef?.onDestroy(() => this.destroy());
  8602. }
  8603. afterRun() {
  8604. this.erroredOrDestroyed = false;
  8605. this.pipelinedValue = undefined;
  8606. // Clear the tracing snapshot after the initial run. This snapshot only
  8607. // associates the initial run of the hook with the context that created it.
  8608. // Follow-up runs are independent of that initial context and have different
  8609. // triggers.
  8610. this.snapshot?.dispose();
  8611. this.snapshot = null;
  8612. }
  8613. destroy() {
  8614. this.impl.unregister(this);
  8615. this.unregisterOnDestroy?.();
  8616. const scheduled = this.view?.[AFTER_RENDER_SEQUENCES_TO_ADD];
  8617. if (scheduled) {
  8618. this.view[AFTER_RENDER_SEQUENCES_TO_ADD] = scheduled.filter((s) => s !== this);
  8619. }
  8620. }
  8621. }
  8622. function afterRender(callbackOrSpec, options) {
  8623. ngDevMode &&
  8624. assertNotInReactiveContext(afterRender, 'Call `afterRender` outside of a reactive context. For example, schedule the render ' +
  8625. 'callback inside the component constructor`.');
  8626. !options?.injector && assertInInjectionContext(afterRender);
  8627. const injector = options?.injector ?? inject(Injector);
  8628. if (typeof ngServerMode !== 'undefined' && ngServerMode) {
  8629. return NOOP_AFTER_RENDER_REF;
  8630. }
  8631. performanceMarkFeature('NgAfterRender');
  8632. return afterRenderImpl(callbackOrSpec, injector, options, /* once */ false);
  8633. }
  8634. function afterNextRender(callbackOrSpec, options) {
  8635. !options?.injector && assertInInjectionContext(afterNextRender);
  8636. const injector = options?.injector ?? inject(Injector);
  8637. if (typeof ngServerMode !== 'undefined' && ngServerMode) {
  8638. return NOOP_AFTER_RENDER_REF;
  8639. }
  8640. performanceMarkFeature('NgAfterNextRender');
  8641. return afterRenderImpl(callbackOrSpec, injector, options, /* once */ true);
  8642. }
  8643. function getHooks(callbackOrSpec, phase) {
  8644. if (callbackOrSpec instanceof Function) {
  8645. const hooks = [undefined, undefined, undefined, undefined];
  8646. hooks[phase] = callbackOrSpec;
  8647. return hooks;
  8648. }
  8649. else {
  8650. return [
  8651. callbackOrSpec.earlyRead,
  8652. callbackOrSpec.write,
  8653. callbackOrSpec.mixedReadWrite,
  8654. callbackOrSpec.read,
  8655. ];
  8656. }
  8657. }
  8658. /**
  8659. * Shared implementation for `afterRender` and `afterNextRender`.
  8660. */
  8661. function afterRenderImpl(callbackOrSpec, injector, options, once) {
  8662. const manager = injector.get(AfterRenderManager);
  8663. // Lazily initialize the handler implementation, if necessary. This is so that it can be
  8664. // tree-shaken if `afterRender` and `afterNextRender` aren't used.
  8665. manager.impl ??= injector.get(AfterRenderImpl);
  8666. const tracing = injector.get(TracingService, null, { optional: true });
  8667. const hooks = options?.phase ?? AfterRenderPhase.MixedReadWrite;
  8668. const destroyRef = options?.manualCleanup !== true ? injector.get(DestroyRef) : null;
  8669. const viewContext = injector.get(ViewContext, null, { optional: true });
  8670. const sequence = new AfterRenderSequence(manager.impl, getHooks(callbackOrSpec, hooks), viewContext?.view, once, destroyRef, tracing?.snapshot(null));
  8671. manager.impl.register(sequence);
  8672. return sequence;
  8673. }
  8674. /** `AfterRenderRef` that does nothing. */
  8675. const NOOP_AFTER_RENDER_REF = {
  8676. destroy() { },
  8677. };
  8678. /**
  8679. * Describes the state of defer block dependency loading.
  8680. */
  8681. var DeferDependenciesLoadingState;
  8682. (function (DeferDependenciesLoadingState) {
  8683. /** Initial state, dependency loading is not yet triggered */
  8684. DeferDependenciesLoadingState[DeferDependenciesLoadingState["NOT_STARTED"] = 0] = "NOT_STARTED";
  8685. /** Dependency loading is in progress */
  8686. DeferDependenciesLoadingState[DeferDependenciesLoadingState["IN_PROGRESS"] = 1] = "IN_PROGRESS";
  8687. /** Dependency loading has completed successfully */
  8688. DeferDependenciesLoadingState[DeferDependenciesLoadingState["COMPLETE"] = 2] = "COMPLETE";
  8689. /** Dependency loading has failed */
  8690. DeferDependenciesLoadingState[DeferDependenciesLoadingState["FAILED"] = 3] = "FAILED";
  8691. })(DeferDependenciesLoadingState || (DeferDependenciesLoadingState = {}));
  8692. /** Slot index where `minimum` parameter value is stored. */
  8693. const MINIMUM_SLOT = 0;
  8694. /** Slot index where `after` parameter value is stored. */
  8695. const LOADING_AFTER_SLOT = 1;
  8696. /**
  8697. * Describes the current state of this defer block instance.
  8698. *
  8699. * @publicApi
  8700. */
  8701. var DeferBlockState;
  8702. (function (DeferBlockState) {
  8703. /** The placeholder block content is rendered */
  8704. DeferBlockState[DeferBlockState["Placeholder"] = 0] = "Placeholder";
  8705. /** The loading block content is rendered */
  8706. DeferBlockState[DeferBlockState["Loading"] = 1] = "Loading";
  8707. /** The main content block content is rendered */
  8708. DeferBlockState[DeferBlockState["Complete"] = 2] = "Complete";
  8709. /** The error block content is rendered */
  8710. DeferBlockState[DeferBlockState["Error"] = 3] = "Error";
  8711. })(DeferBlockState || (DeferBlockState = {}));
  8712. /**
  8713. * Describes the initial state of this defer block instance.
  8714. *
  8715. * Note: this state is internal only and *must* be represented
  8716. * with a number lower than any value in the `DeferBlockState` enum.
  8717. */
  8718. var DeferBlockInternalState;
  8719. (function (DeferBlockInternalState) {
  8720. /** Initial state. Nothing is rendered yet. */
  8721. DeferBlockInternalState[DeferBlockInternalState["Initial"] = -1] = "Initial";
  8722. })(DeferBlockInternalState || (DeferBlockInternalState = {}));
  8723. const NEXT_DEFER_BLOCK_STATE = 0;
  8724. // Note: it's *important* to keep the state in this slot, because this slot
  8725. // is used by runtime logic to differentiate between LViews, LContainers and
  8726. // other types (see `isLView` and `isLContainer` functions). In case of defer
  8727. // blocks, this slot would always be a number.
  8728. const DEFER_BLOCK_STATE = 1;
  8729. const STATE_IS_FROZEN_UNTIL = 2;
  8730. const LOADING_AFTER_CLEANUP_FN = 3;
  8731. const TRIGGER_CLEANUP_FNS = 4;
  8732. const PREFETCH_TRIGGER_CLEANUP_FNS = 5;
  8733. const SSR_UNIQUE_ID = 6;
  8734. const SSR_BLOCK_STATE = 7;
  8735. const ON_COMPLETE_FNS = 8;
  8736. const HYDRATE_TRIGGER_CLEANUP_FNS = 9;
  8737. /**
  8738. * Options for configuring defer blocks behavior.
  8739. * @publicApi
  8740. */
  8741. var DeferBlockBehavior;
  8742. (function (DeferBlockBehavior) {
  8743. /**
  8744. * Manual triggering mode for defer blocks. Provides control over when defer blocks render
  8745. * and which state they render.
  8746. */
  8747. DeferBlockBehavior[DeferBlockBehavior["Manual"] = 0] = "Manual";
  8748. /**
  8749. * Playthrough mode for defer blocks. This mode behaves like defer blocks would in a browser.
  8750. * This is the default behavior in test environments.
  8751. */
  8752. DeferBlockBehavior[DeferBlockBehavior["Playthrough"] = 1] = "Playthrough";
  8753. })(DeferBlockBehavior || (DeferBlockBehavior = {}));
  8754. /*!
  8755. * @license
  8756. * Copyright Google LLC All Rights Reserved.
  8757. *
  8758. * Use of this source code is governed by an MIT-style license that can be
  8759. * found in the LICENSE file at https://angular.dev/license
  8760. */
  8761. /**
  8762. * Registers a cleanup function associated with a prefetching trigger
  8763. * or a regular trigger of a defer block.
  8764. */
  8765. function storeTriggerCleanupFn(type, lDetails, cleanupFn) {
  8766. const key = getCleanupFnKeyByType(type);
  8767. if (lDetails[key] === null) {
  8768. lDetails[key] = [];
  8769. }
  8770. lDetails[key].push(cleanupFn);
  8771. }
  8772. /**
  8773. * Invokes registered cleanup functions either for prefetch or for regular triggers.
  8774. */
  8775. function invokeTriggerCleanupFns(type, lDetails) {
  8776. const key = getCleanupFnKeyByType(type);
  8777. const cleanupFns = lDetails[key];
  8778. if (cleanupFns !== null) {
  8779. for (const cleanupFn of cleanupFns) {
  8780. cleanupFn();
  8781. }
  8782. lDetails[key] = null;
  8783. }
  8784. }
  8785. /**
  8786. * Invokes registered cleanup functions for prefetch, hydrate, and regular triggers.
  8787. */
  8788. function invokeAllTriggerCleanupFns(lDetails) {
  8789. invokeTriggerCleanupFns(1 /* TriggerType.Prefetch */, lDetails);
  8790. invokeTriggerCleanupFns(0 /* TriggerType.Regular */, lDetails);
  8791. invokeTriggerCleanupFns(2 /* TriggerType.Hydrate */, lDetails);
  8792. }
  8793. function getCleanupFnKeyByType(type) {
  8794. let key = TRIGGER_CLEANUP_FNS;
  8795. if (type === 1 /* TriggerType.Prefetch */) {
  8796. key = PREFETCH_TRIGGER_CLEANUP_FNS;
  8797. }
  8798. else if (type === 2 /* TriggerType.Hydrate */) {
  8799. key = HYDRATE_TRIGGER_CLEANUP_FNS;
  8800. }
  8801. return key;
  8802. }
  8803. /**
  8804. * Calculates a data slot index for defer block info (either static or
  8805. * instance-specific), given an index of a defer instruction.
  8806. */
  8807. function getDeferBlockDataIndex(deferBlockIndex) {
  8808. // Instance state is located at the *next* position
  8809. // after the defer block slot in an LView or TView.data.
  8810. return deferBlockIndex + 1;
  8811. }
  8812. /** Retrieves a defer block state from an LView, given a TNode that represents a block. */
  8813. function getLDeferBlockDetails(lView, tNode) {
  8814. const tView = lView[TVIEW];
  8815. const slotIndex = getDeferBlockDataIndex(tNode.index);
  8816. ngDevMode && assertIndexInDeclRange(tView, slotIndex);
  8817. return lView[slotIndex];
  8818. }
  8819. /** Stores a defer block instance state in LView. */
  8820. function setLDeferBlockDetails(lView, deferBlockIndex, lDetails) {
  8821. const tView = lView[TVIEW];
  8822. const slotIndex = getDeferBlockDataIndex(deferBlockIndex);
  8823. ngDevMode && assertIndexInDeclRange(tView, slotIndex);
  8824. lView[slotIndex] = lDetails;
  8825. }
  8826. /** Retrieves static info about a defer block, given a TView and a TNode that represents a block. */
  8827. function getTDeferBlockDetails(tView, tNode) {
  8828. const slotIndex = getDeferBlockDataIndex(tNode.index);
  8829. ngDevMode && assertIndexInDeclRange(tView, slotIndex);
  8830. return tView.data[slotIndex];
  8831. }
  8832. /** Stores a defer block static info in `TView.data`. */
  8833. function setTDeferBlockDetails(tView, deferBlockIndex, deferBlockConfig) {
  8834. const slotIndex = getDeferBlockDataIndex(deferBlockIndex);
  8835. ngDevMode && assertIndexInDeclRange(tView, slotIndex);
  8836. tView.data[slotIndex] = deferBlockConfig;
  8837. }
  8838. function getTemplateIndexForState(newState, hostLView, tNode) {
  8839. const tView = hostLView[TVIEW];
  8840. const tDetails = getTDeferBlockDetails(tView, tNode);
  8841. switch (newState) {
  8842. case DeferBlockState.Complete:
  8843. return tDetails.primaryTmplIndex;
  8844. case DeferBlockState.Loading:
  8845. return tDetails.loadingTmplIndex;
  8846. case DeferBlockState.Error:
  8847. return tDetails.errorTmplIndex;
  8848. case DeferBlockState.Placeholder:
  8849. return tDetails.placeholderTmplIndex;
  8850. default:
  8851. ngDevMode && throwError(`Unexpected defer block state: ${newState}`);
  8852. return null;
  8853. }
  8854. }
  8855. /**
  8856. * Returns a minimum amount of time that a given state should be rendered for,
  8857. * taking into account `minimum` parameter value. If the `minimum` value is
  8858. * not specified - returns `null`.
  8859. */
  8860. function getMinimumDurationForState(tDetails, currentState) {
  8861. if (currentState === DeferBlockState.Placeholder) {
  8862. return tDetails.placeholderBlockConfig?.[MINIMUM_SLOT] ?? null;
  8863. }
  8864. else if (currentState === DeferBlockState.Loading) {
  8865. return tDetails.loadingBlockConfig?.[MINIMUM_SLOT] ?? null;
  8866. }
  8867. return null;
  8868. }
  8869. /** Retrieves the value of the `after` parameter on the @loading block. */
  8870. function getLoadingBlockAfter(tDetails) {
  8871. return tDetails.loadingBlockConfig?.[LOADING_AFTER_SLOT] ?? null;
  8872. }
  8873. /**
  8874. * Adds downloaded dependencies into a directive or a pipe registry,
  8875. * making sure that a dependency doesn't yet exist in the registry.
  8876. */
  8877. function addDepsToRegistry(currentDeps, newDeps) {
  8878. if (!currentDeps || currentDeps.length === 0) {
  8879. return newDeps;
  8880. }
  8881. const currentDepSet = new Set(currentDeps);
  8882. for (const dep of newDeps) {
  8883. currentDepSet.add(dep);
  8884. }
  8885. // If `currentDeps` is the same length, there were no new deps and can
  8886. // return the original array.
  8887. return currentDeps.length === currentDepSet.size ? currentDeps : Array.from(currentDepSet);
  8888. }
  8889. /** Retrieves a TNode that represents main content of a defer block. */
  8890. function getPrimaryBlockTNode(tView, tDetails) {
  8891. const adjustedIndex = tDetails.primaryTmplIndex + HEADER_OFFSET;
  8892. return getTNode(tView, adjustedIndex);
  8893. }
  8894. /**
  8895. * Asserts whether all dependencies for a defer block are loaded.
  8896. * Always run this function (in dev mode) before rendering a defer
  8897. * block in completed state.
  8898. */
  8899. function assertDeferredDependenciesLoaded(tDetails) {
  8900. assertEqual(tDetails.loadingState, DeferDependenciesLoadingState.COMPLETE, 'Expecting all deferred dependencies to be loaded.');
  8901. }
  8902. /**
  8903. * Determines if a given value matches the expected structure of a defer block
  8904. *
  8905. * We can safely rely on the primaryTmplIndex because every defer block requires
  8906. * that a primary template exists. All the other template options are optional.
  8907. */
  8908. function isTDeferBlockDetails(value) {
  8909. return (value !== null &&
  8910. typeof value === 'object' &&
  8911. typeof value.primaryTmplIndex === 'number');
  8912. }
  8913. /**
  8914. * Whether a given TNode represents a defer block.
  8915. */
  8916. function isDeferBlock(tView, tNode) {
  8917. let tDetails = null;
  8918. const slotIndex = getDeferBlockDataIndex(tNode.index);
  8919. // Check if a slot index is in the reasonable range.
  8920. // Note: we do `-1` on the right border, since defer block details are stored
  8921. // in the `n+1` slot, see `getDeferBlockDataIndex` for more info.
  8922. if (HEADER_OFFSET < slotIndex && slotIndex < tView.bindingStartIndex) {
  8923. tDetails = getTDeferBlockDetails(tView, tNode);
  8924. }
  8925. return !!tDetails && isTDeferBlockDetails(tDetails);
  8926. }
  8927. /**
  8928. * Tracks debugging information about a trigger.
  8929. * @param tView TView in which the trigger is declared.
  8930. * @param tNode TNode on which the trigger is declared.
  8931. * @param textRepresentation Text representation of the trigger to be used for debugging purposes.
  8932. */
  8933. function trackTriggerForDebugging(tView, tNode, textRepresentation) {
  8934. const tDetails = getTDeferBlockDetails(tView, tNode);
  8935. tDetails.debug ??= {};
  8936. tDetails.debug.triggers ??= new Set();
  8937. tDetails.debug.triggers.add(textRepresentation);
  8938. }
  8939. /*!
  8940. * @license
  8941. * Copyright Google LLC All Rights Reserved.
  8942. *
  8943. * Use of this source code is governed by an MIT-style license that can be
  8944. * found in the LICENSE file at https://angular.dev/license
  8945. */
  8946. /** Configuration object used to register passive and capturing events. */
  8947. const eventListenerOptions = {
  8948. passive: true,
  8949. capture: true,
  8950. };
  8951. /** Keeps track of the currently-registered `on hover` triggers. */
  8952. const hoverTriggers = new WeakMap();
  8953. /** Keeps track of the currently-registered `on interaction` triggers. */
  8954. const interactionTriggers = new WeakMap();
  8955. /** Currently-registered `viewport` triggers. */
  8956. const viewportTriggers = new WeakMap();
  8957. /** Names of the events considered as interaction events. */
  8958. const interactionEventNames = ['click', 'keydown'];
  8959. /** Names of the events considered as hover events. */
  8960. const hoverEventNames = ['mouseenter', 'mouseover', 'focusin'];
  8961. /** `IntersectionObserver` used to observe `viewport` triggers. */
  8962. let intersectionObserver = null;
  8963. /** Number of elements currently observed with `viewport` triggers. */
  8964. let observedViewportElements = 0;
  8965. /** Object keeping track of registered callbacks for a deferred block trigger. */
  8966. class DeferEventEntry {
  8967. callbacks = new Set();
  8968. listener = () => {
  8969. for (const callback of this.callbacks) {
  8970. callback();
  8971. }
  8972. };
  8973. }
  8974. /**
  8975. * Registers an interaction trigger.
  8976. * @param trigger Element that is the trigger.
  8977. * @param callback Callback to be invoked when the trigger is interacted with.
  8978. */
  8979. function onInteraction(trigger, callback) {
  8980. let entry = interactionTriggers.get(trigger);
  8981. // If this is the first entry for this element, add the listeners.
  8982. if (!entry) {
  8983. // Note that managing events centrally like this lends itself well to using global
  8984. // event delegation. It currently does delegation at the element level, rather than the
  8985. // document level, because:
  8986. // 1. Global delegation is the most effective when there are a lot of events being registered
  8987. // at the same time. Deferred blocks are unlikely to be used in such a way.
  8988. // 2. Matching events to their target isn't free. For each `click` and `keydown` event we
  8989. // would have look through all the triggers and check if the target either is the element
  8990. // itself or it's contained within the element. Given that `click` and `keydown` are some
  8991. // of the most common events, this may end up introducing a lot of runtime overhead.
  8992. // 3. We're still registering only two events per element, no matter how many deferred blocks
  8993. // are referencing it.
  8994. entry = new DeferEventEntry();
  8995. interactionTriggers.set(trigger, entry);
  8996. for (const name of interactionEventNames) {
  8997. trigger.addEventListener(name, entry.listener, eventListenerOptions);
  8998. }
  8999. }
  9000. entry.callbacks.add(callback);
  9001. return () => {
  9002. const { callbacks, listener } = entry;
  9003. callbacks.delete(callback);
  9004. if (callbacks.size === 0) {
  9005. interactionTriggers.delete(trigger);
  9006. for (const name of interactionEventNames) {
  9007. trigger.removeEventListener(name, listener, eventListenerOptions);
  9008. }
  9009. }
  9010. };
  9011. }
  9012. /**
  9013. * Registers a hover trigger.
  9014. * @param trigger Element that is the trigger.
  9015. * @param callback Callback to be invoked when the trigger is hovered over.
  9016. */
  9017. function onHover(trigger, callback) {
  9018. let entry = hoverTriggers.get(trigger);
  9019. // If this is the first entry for this element, add the listener.
  9020. if (!entry) {
  9021. entry = new DeferEventEntry();
  9022. hoverTriggers.set(trigger, entry);
  9023. for (const name of hoverEventNames) {
  9024. trigger.addEventListener(name, entry.listener, eventListenerOptions);
  9025. }
  9026. }
  9027. entry.callbacks.add(callback);
  9028. return () => {
  9029. const { callbacks, listener } = entry;
  9030. callbacks.delete(callback);
  9031. if (callbacks.size === 0) {
  9032. for (const name of hoverEventNames) {
  9033. trigger.removeEventListener(name, listener, eventListenerOptions);
  9034. }
  9035. hoverTriggers.delete(trigger);
  9036. }
  9037. };
  9038. }
  9039. /**
  9040. * Registers a viewport trigger.
  9041. * @param trigger Element that is the trigger.
  9042. * @param callback Callback to be invoked when the trigger comes into the viewport.
  9043. * @param injector Injector that can be used by the trigger to resolve DI tokens.
  9044. */
  9045. function onViewport(trigger, callback, injector) {
  9046. const ngZone = injector.get(NgZone);
  9047. let entry = viewportTriggers.get(trigger);
  9048. intersectionObserver =
  9049. intersectionObserver ||
  9050. ngZone.runOutsideAngular(() => {
  9051. return new IntersectionObserver((entries) => {
  9052. for (const current of entries) {
  9053. // Only invoke the callbacks if the specific element is intersecting.
  9054. if (current.isIntersecting && viewportTriggers.has(current.target)) {
  9055. ngZone.run(viewportTriggers.get(current.target).listener);
  9056. }
  9057. }
  9058. });
  9059. });
  9060. if (!entry) {
  9061. entry = new DeferEventEntry();
  9062. ngZone.runOutsideAngular(() => intersectionObserver.observe(trigger));
  9063. viewportTriggers.set(trigger, entry);
  9064. observedViewportElements++;
  9065. }
  9066. entry.callbacks.add(callback);
  9067. return () => {
  9068. // It's possible that a different cleanup callback fully removed this element already.
  9069. if (!viewportTriggers.has(trigger)) {
  9070. return;
  9071. }
  9072. entry.callbacks.delete(callback);
  9073. if (entry.callbacks.size === 0) {
  9074. intersectionObserver?.unobserve(trigger);
  9075. viewportTriggers.delete(trigger);
  9076. observedViewportElements--;
  9077. }
  9078. if (observedViewportElements === 0) {
  9079. intersectionObserver?.disconnect();
  9080. intersectionObserver = null;
  9081. }
  9082. };
  9083. }
  9084. /**
  9085. * Helper function to get the LView in which a deferred block's trigger is rendered.
  9086. * @param deferredHostLView LView in which the deferred block is defined.
  9087. * @param deferredTNode TNode defining the deferred block.
  9088. * @param walkUpTimes Number of times to go up in the view hierarchy to find the trigger's view.
  9089. * A negative value means that the trigger is inside the block's placeholder, while an undefined
  9090. * value means that the trigger is in the same LView as the deferred block.
  9091. */
  9092. function getTriggerLView(deferredHostLView, deferredTNode, walkUpTimes) {
  9093. // The trigger is in the same view, we don't need to traverse.
  9094. if (walkUpTimes == null) {
  9095. return deferredHostLView;
  9096. }
  9097. // A positive value or zero means that the trigger is in a parent view.
  9098. if (walkUpTimes >= 0) {
  9099. return walkUpViews(walkUpTimes, deferredHostLView);
  9100. }
  9101. // If the value is negative, it means that the trigger is inside the placeholder.
  9102. const deferredContainer = deferredHostLView[deferredTNode.index];
  9103. ngDevMode && assertLContainer(deferredContainer);
  9104. const triggerLView = deferredContainer[CONTAINER_HEADER_OFFSET] ?? null;
  9105. // We need to null check, because the placeholder might not have been rendered yet.
  9106. if (ngDevMode && triggerLView !== null) {
  9107. const lDetails = getLDeferBlockDetails(deferredHostLView, deferredTNode);
  9108. const renderedState = lDetails[DEFER_BLOCK_STATE];
  9109. assertEqual(renderedState, DeferBlockState.Placeholder, 'Expected a placeholder to be rendered in this defer block.');
  9110. assertLView(triggerLView);
  9111. }
  9112. return triggerLView;
  9113. }
  9114. /**
  9115. * Gets the element that a deferred block's trigger is pointing to.
  9116. * @param triggerLView LView in which the trigger is defined.
  9117. * @param triggerIndex Index at which the trigger element should've been rendered.
  9118. */
  9119. function getTriggerElement(triggerLView, triggerIndex) {
  9120. const element = getNativeByIndex(HEADER_OFFSET + triggerIndex, triggerLView);
  9121. ngDevMode && assertElement(element);
  9122. return element;
  9123. }
  9124. /**
  9125. * Registers a DOM-node based trigger.
  9126. * @param initialLView LView in which the defer block is rendered.
  9127. * @param tNode TNode representing the defer block.
  9128. * @param triggerIndex Index at which to find the trigger element.
  9129. * @param walkUpTimes Number of times to go up/down in the view hierarchy to find the trigger.
  9130. * @param registerFn Function that will register the DOM events.
  9131. * @param callback Callback to be invoked when the trigger receives the event that should render
  9132. * the deferred block.
  9133. * @param type Trigger type to distinguish between regular and prefetch triggers.
  9134. */
  9135. function registerDomTrigger(initialLView, tNode, triggerIndex, walkUpTimes, registerFn, callback, type) {
  9136. const injector = initialLView[INJECTOR];
  9137. const zone = injector.get(NgZone);
  9138. let poll;
  9139. function pollDomTrigger() {
  9140. // If the initial view was destroyed, we don't need to do anything.
  9141. if (isDestroyed(initialLView)) {
  9142. poll.destroy();
  9143. return;
  9144. }
  9145. const lDetails = getLDeferBlockDetails(initialLView, tNode);
  9146. const renderedState = lDetails[DEFER_BLOCK_STATE];
  9147. // If the block was loaded before the trigger was resolved, we don't need to do anything.
  9148. if (renderedState !== DeferBlockInternalState.Initial &&
  9149. renderedState !== DeferBlockState.Placeholder) {
  9150. poll.destroy();
  9151. return;
  9152. }
  9153. const triggerLView = getTriggerLView(initialLView, tNode, walkUpTimes);
  9154. // Keep polling until we resolve the trigger's LView.
  9155. if (!triggerLView) {
  9156. // Keep polling.
  9157. return;
  9158. }
  9159. poll.destroy();
  9160. // It's possible that the trigger's view was destroyed before we resolved the trigger element.
  9161. if (isDestroyed(triggerLView)) {
  9162. return;
  9163. }
  9164. const element = getTriggerElement(triggerLView, triggerIndex);
  9165. const cleanup = registerFn(element, () => {
  9166. // `pollDomTrigger` runs outside the zone (because of `afterNextRender`) and registers its
  9167. // listeners outside the zone, so we jump back into the zone prior to running the callback.
  9168. zone.run(() => {
  9169. if (initialLView !== triggerLView) {
  9170. removeLViewOnDestroy(triggerLView, cleanup);
  9171. }
  9172. callback();
  9173. });
  9174. }, injector);
  9175. // The trigger and deferred block might be in different LViews.
  9176. // For the main LView the cleanup would happen as a part of
  9177. // `storeTriggerCleanupFn` logic. For trigger LView we register
  9178. // a cleanup function there to remove event handlers in case an
  9179. // LView gets destroyed before a trigger is invoked.
  9180. if (initialLView !== triggerLView) {
  9181. storeLViewOnDestroy(triggerLView, cleanup);
  9182. }
  9183. storeTriggerCleanupFn(type, lDetails, cleanup);
  9184. }
  9185. // Begin polling for the trigger.
  9186. poll = afterRender({ read: pollDomTrigger }, { injector });
  9187. }
  9188. const DEFER_BLOCK_SSR_ID_ATTRIBUTE = 'ngb';
  9189. function setJSActionAttributes(nativeElement, eventTypes, parentDeferBlockId = null) {
  9190. // jsaction attributes specifically should be applied to elements and not comment nodes.
  9191. // Comment nodes also have no setAttribute function. So this avoids errors.
  9192. if (eventTypes.length === 0 || nativeElement.nodeType !== Node.ELEMENT_NODE) {
  9193. return;
  9194. }
  9195. const existingAttr = nativeElement.getAttribute(Attribute$1.JSACTION);
  9196. // we dedupe cases where hydrate triggers are used as it's possible that
  9197. // someone may have added an event binding to the root node that matches what the
  9198. // hydrate trigger adds.
  9199. const parts = eventTypes.reduce((prev, curr) => {
  9200. // if there is no existing attribute OR it's not in the existing one, we need to add it
  9201. return (existingAttr?.indexOf(curr) ?? -1) === -1 ? prev + curr + ':;' : prev;
  9202. }, '');
  9203. // This is required to be a module accessor to appease security tests on setAttribute.
  9204. nativeElement.setAttribute(Attribute$1.JSACTION, `${existingAttr ?? ''}${parts}`);
  9205. const blockName = parentDeferBlockId ?? '';
  9206. if (blockName !== '' && parts.length > 0) {
  9207. nativeElement.setAttribute(DEFER_BLOCK_SSR_ID_ATTRIBUTE, blockName);
  9208. }
  9209. }
  9210. const sharedStashFunction = (rEl, eventType, listenerFn) => {
  9211. const el = rEl;
  9212. const eventListenerMap = el.__jsaction_fns ?? new Map();
  9213. const eventListeners = eventListenerMap.get(eventType) ?? [];
  9214. eventListeners.push(listenerFn);
  9215. eventListenerMap.set(eventType, eventListeners);
  9216. el.__jsaction_fns = eventListenerMap;
  9217. };
  9218. const sharedMapFunction = (rEl, jsActionMap) => {
  9219. const el = rEl;
  9220. let blockName = el.getAttribute(DEFER_BLOCK_SSR_ID_ATTRIBUTE) ?? '';
  9221. const blockSet = jsActionMap.get(blockName) ?? new Set();
  9222. if (!blockSet.has(el)) {
  9223. blockSet.add(el);
  9224. }
  9225. jsActionMap.set(blockName, blockSet);
  9226. };
  9227. function removeListenersFromBlocks(blockNames, jsActionMap) {
  9228. if (blockNames.length > 0) {
  9229. let blockList = [];
  9230. for (let blockName of blockNames) {
  9231. if (jsActionMap.has(blockName)) {
  9232. blockList = [...blockList, ...jsActionMap.get(blockName)];
  9233. }
  9234. }
  9235. const replayList = new Set(blockList);
  9236. replayList.forEach(removeListeners);
  9237. }
  9238. }
  9239. const removeListeners = (el) => {
  9240. el.removeAttribute(Attribute$1.JSACTION);
  9241. el.removeAttribute(DEFER_BLOCK_SSR_ID_ATTRIBUTE);
  9242. el.__jsaction_fns = undefined;
  9243. };
  9244. const JSACTION_EVENT_CONTRACT = new InjectionToken(ngDevMode ? 'EVENT_CONTRACT_DETAILS' : '', {
  9245. providedIn: 'root',
  9246. factory: () => ({}),
  9247. });
  9248. function invokeListeners(event, currentTarget) {
  9249. const handlerFns = currentTarget?.__jsaction_fns?.get(event.type);
  9250. if (!handlerFns || !currentTarget?.isConnected) {
  9251. return;
  9252. }
  9253. for (const handler of handlerFns) {
  9254. handler(event);
  9255. }
  9256. }
  9257. const stashEventListeners = new Map();
  9258. /**
  9259. * Registers a stashing function for a specific application ID.
  9260. *
  9261. * @param appId The unique identifier for the application instance.
  9262. * @param fn The stashing function to associate with this app ID.
  9263. * @returns A cleanup function that removes the stashing function when called.
  9264. */
  9265. function setStashFn(appId, fn) {
  9266. stashEventListeners.set(appId, fn);
  9267. return () => stashEventListeners.delete(appId);
  9268. }
  9269. /**
  9270. * Indicates whether the stashing code was added, prevents adding it multiple times.
  9271. */
  9272. let isStashEventListenerImplEnabled = false;
  9273. let _stashEventListenerImpl = (lView, target, eventName, listenerFn) => { };
  9274. /**
  9275. * Optionally stashes an event listener for later replay during hydration.
  9276. *
  9277. * This function delegates to an internal `_stashEventListenerImpl`, which may
  9278. * be a no-op unless the event replay feature is enabled. When active, this
  9279. * allows capturing event listener metadata before hydration completes, so that
  9280. * user interactions during SSR can be replayed.
  9281. *
  9282. * @param lView The logical view (LView) where the listener is being registered.
  9283. * @param target The DOM element or event target the listener is attached to.
  9284. * @param eventName The name of the event being listened for (e.g., 'click').
  9285. * @param listenerFn The event handler that was registered.
  9286. */
  9287. function stashEventListenerImpl(lView, target, eventName, listenerFn) {
  9288. _stashEventListenerImpl(lView, target, eventName, listenerFn);
  9289. }
  9290. /**
  9291. * Enables the event listener stashing logic in a tree-shakable way.
  9292. *
  9293. * This function lazily sets the implementation of `_stashEventListenerImpl`
  9294. * so that it becomes active only when `withEventReplay` is invoked. This ensures
  9295. * that the stashing logic is excluded from production builds unless needed.
  9296. */
  9297. function enableStashEventListenerImpl() {
  9298. if (!isStashEventListenerImplEnabled) {
  9299. _stashEventListenerImpl = (lView, target, eventName, listenerFn) => {
  9300. const appId = lView[INJECTOR].get(APP_ID);
  9301. const stashEventListener = stashEventListeners.get(appId);
  9302. stashEventListener?.(target, eventName, listenerFn);
  9303. };
  9304. isStashEventListenerImplEnabled = true;
  9305. }
  9306. }
  9307. /**
  9308. * An internal injection token to reference `DehydratedBlockRegistry` implementation
  9309. * in a tree-shakable way.
  9310. */
  9311. const DEHYDRATED_BLOCK_REGISTRY = new InjectionToken(ngDevMode ? 'DEHYDRATED_BLOCK_REGISTRY' : '');
  9312. /**
  9313. * The DehydratedBlockRegistry is used for incremental hydration purposes. It keeps
  9314. * track of the Defer Blocks that need hydration so we can effectively
  9315. * navigate up to the top dehydrated defer block and fire appropriate cleanup
  9316. * functions post hydration.
  9317. */
  9318. class DehydratedBlockRegistry {
  9319. registry = new Map();
  9320. cleanupFns = new Map();
  9321. jsActionMap = inject(JSACTION_BLOCK_ELEMENT_MAP);
  9322. contract = inject(JSACTION_EVENT_CONTRACT);
  9323. add(blockId, info) {
  9324. this.registry.set(blockId, info);
  9325. // It's possible that hydration is queued that's waiting for the
  9326. // resolution of a lazy loaded route. In this case, we ensure
  9327. // the callback function is called to continue the hydration process
  9328. // for the queued block set.
  9329. if (this.awaitingCallbacks.has(blockId)) {
  9330. const awaitingCallbacks = this.awaitingCallbacks.get(blockId);
  9331. for (const cb of awaitingCallbacks) {
  9332. cb();
  9333. }
  9334. }
  9335. }
  9336. get(blockId) {
  9337. return this.registry.get(blockId) ?? null;
  9338. }
  9339. has(blockId) {
  9340. return this.registry.has(blockId);
  9341. }
  9342. cleanup(hydratedBlocks) {
  9343. removeListenersFromBlocks(hydratedBlocks, this.jsActionMap);
  9344. for (let blockId of hydratedBlocks) {
  9345. this.registry.delete(blockId);
  9346. this.jsActionMap.delete(blockId);
  9347. this.invokeTriggerCleanupFns(blockId);
  9348. this.hydrating.delete(blockId);
  9349. this.awaitingCallbacks.delete(blockId);
  9350. }
  9351. if (this.size === 0) {
  9352. this.contract.instance?.cleanUp();
  9353. }
  9354. }
  9355. get size() {
  9356. return this.registry.size;
  9357. }
  9358. // we have to leave the lowest block Id in the registry
  9359. // unless that block has no children
  9360. addCleanupFn(blockId, fn) {
  9361. let cleanupFunctions = [];
  9362. if (this.cleanupFns.has(blockId)) {
  9363. cleanupFunctions = this.cleanupFns.get(blockId);
  9364. }
  9365. cleanupFunctions.push(fn);
  9366. this.cleanupFns.set(blockId, cleanupFunctions);
  9367. }
  9368. invokeTriggerCleanupFns(blockId) {
  9369. const fns = this.cleanupFns.get(blockId) ?? [];
  9370. for (let fn of fns) {
  9371. fn();
  9372. }
  9373. this.cleanupFns.delete(blockId);
  9374. }
  9375. // Blocks that are being hydrated.
  9376. hydrating = new Map();
  9377. // Blocks that are awaiting a defer instruction finish.
  9378. awaitingCallbacks = new Map();
  9379. awaitParentBlock(topmostParentBlock, callback) {
  9380. const parentBlockAwaitCallbacks = this.awaitingCallbacks.get(topmostParentBlock) ?? [];
  9381. parentBlockAwaitCallbacks.push(callback);
  9382. this.awaitingCallbacks.set(topmostParentBlock, parentBlockAwaitCallbacks);
  9383. }
  9384. /** @nocollapse */
  9385. static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
  9386. token: DehydratedBlockRegistry,
  9387. providedIn: null,
  9388. factory: () => new DehydratedBlockRegistry(),
  9389. });
  9390. }
  9391. /**
  9392. * The name of the key used in the TransferState collection,
  9393. * where hydration information is located.
  9394. */
  9395. const TRANSFER_STATE_TOKEN_ID = '__nghData__';
  9396. /**
  9397. * Lookup key used to reference DOM hydration data (ngh) in `TransferState`.
  9398. */
  9399. const NGH_DATA_KEY = makeStateKey(TRANSFER_STATE_TOKEN_ID);
  9400. /**
  9401. * The name of the key used in the TransferState collection,
  9402. * where serialized defer block information is located.
  9403. */
  9404. const TRANSFER_STATE_DEFER_BLOCKS_INFO = '__nghDeferData__';
  9405. /**
  9406. * Lookup key used to retrieve defer block datain `TransferState`.
  9407. */
  9408. const NGH_DEFER_BLOCKS_KEY = makeStateKey(TRANSFER_STATE_DEFER_BLOCKS_INFO);
  9409. /**
  9410. * The name of the attribute that would be added to host component
  9411. * nodes and contain a reference to a particular slot in transferred
  9412. * state that contains the necessary hydration info for this component.
  9413. */
  9414. const NGH_ATTR_NAME = 'ngh';
  9415. /**
  9416. * Marker used in a comment node to ensure hydration content integrity
  9417. */
  9418. const SSR_CONTENT_INTEGRITY_MARKER = 'nghm';
  9419. /**
  9420. * Reference to a function that reads `ngh` attribute value from a given RNode
  9421. * and retrieves hydration information from the TransferState using that value
  9422. * as an index. Returns `null` by default, when hydration is not enabled.
  9423. *
  9424. * @param rNode Component's host element.
  9425. * @param injector Injector that this component has access to.
  9426. * @param isRootView Specifies whether we trying to read hydration info for the root view.
  9427. */
  9428. let _retrieveHydrationInfoImpl = () => null;
  9429. function retrieveHydrationInfoImpl(rNode, injector, isRootView = false) {
  9430. let nghAttrValue = rNode.getAttribute(NGH_ATTR_NAME);
  9431. if (nghAttrValue == null)
  9432. return null;
  9433. // For cases when a root component also acts as an anchor node for a ViewContainerRef
  9434. // (for example, when ViewContainerRef is injected in a root component), there is a need
  9435. // to serialize information about the component itself, as well as an LContainer that
  9436. // represents this ViewContainerRef. Effectively, we need to serialize 2 pieces of info:
  9437. // (1) hydration info for the root component itself and (2) hydration info for the
  9438. // ViewContainerRef instance (an LContainer). Each piece of information is included into
  9439. // the hydration data (in the TransferState object) separately, thus we end up with 2 ids.
  9440. // Since we only have 1 root element, we encode both bits of info into a single string:
  9441. // ids are separated by the `|` char (e.g. `10|25`, where `10` is the ngh for a component view
  9442. // and 25 is the `ngh` for a root view which holds LContainer).
  9443. const [componentViewNgh, rootViewNgh] = nghAttrValue.split('|');
  9444. nghAttrValue = isRootView ? rootViewNgh : componentViewNgh;
  9445. if (!nghAttrValue)
  9446. return null;
  9447. // We've read one of the ngh ids, keep the remaining one, so that
  9448. // we can set it back on the DOM element.
  9449. const rootNgh = rootViewNgh ? `|${rootViewNgh}` : '';
  9450. const remainingNgh = isRootView ? componentViewNgh : rootNgh;
  9451. let data = {};
  9452. // An element might have an empty `ngh` attribute value (e.g. `<comp ngh="" />`),
  9453. // which means that no special annotations are required. Do not attempt to read
  9454. // from the TransferState in this case.
  9455. if (nghAttrValue !== '') {
  9456. const transferState = injector.get(TransferState, null, { optional: true });
  9457. if (transferState !== null) {
  9458. const nghData = transferState.get(NGH_DATA_KEY, []);
  9459. // The nghAttrValue is always a number referencing an index
  9460. // in the hydration TransferState data.
  9461. data = nghData[Number(nghAttrValue)];
  9462. // If the `ngh` attribute exists and has a non-empty value,
  9463. // the hydration info *must* be present in the TransferState.
  9464. // If there is no data for some reasons, this is an error.
  9465. ngDevMode && assertDefined(data, 'Unable to retrieve hydration info from the TransferState.');
  9466. }
  9467. }
  9468. const dehydratedView = {
  9469. data,
  9470. firstChild: rNode.firstChild ?? null,
  9471. };
  9472. if (isRootView) {
  9473. // If there is hydration info present for the root view, it means that there was
  9474. // a ViewContainerRef injected in the root component. The root component host element
  9475. // acted as an anchor node in this scenario. As a result, the DOM nodes that represent
  9476. // embedded views in this ViewContainerRef are located as siblings to the host node,
  9477. // i.e. `<app-root /><#VIEW1><#VIEW2>...<!--container-->`. In this case, the current
  9478. // node becomes the first child of this root view and the next sibling is the first
  9479. // element in the DOM segment.
  9480. dehydratedView.firstChild = rNode;
  9481. // We use `0` here, since this is the slot (right after the HEADER_OFFSET)
  9482. // where a component LView or an LContainer is located in a root LView.
  9483. setSegmentHead(dehydratedView, 0, rNode.nextSibling);
  9484. }
  9485. if (remainingNgh) {
  9486. // If we have only used one of the ngh ids, store the remaining one
  9487. // back on this RNode.
  9488. rNode.setAttribute(NGH_ATTR_NAME, remainingNgh);
  9489. }
  9490. else {
  9491. // The `ngh` attribute is cleared from the DOM node now
  9492. // that the data has been retrieved for all indices.
  9493. rNode.removeAttribute(NGH_ATTR_NAME);
  9494. }
  9495. // Note: don't check whether this node was claimed for hydration,
  9496. // because this node might've been previously claimed while processing
  9497. // template instructions.
  9498. ngDevMode && markRNodeAsClaimedByHydration(rNode, /* checkIfAlreadyClaimed */ false);
  9499. ngDevMode && ngDevMode.hydratedComponents++;
  9500. return dehydratedView;
  9501. }
  9502. /**
  9503. * Sets the implementation for the `retrieveHydrationInfo` function.
  9504. */
  9505. function enableRetrieveHydrationInfoImpl() {
  9506. _retrieveHydrationInfoImpl = retrieveHydrationInfoImpl;
  9507. }
  9508. /**
  9509. * Retrieves hydration info by reading the value from the `ngh` attribute
  9510. * and accessing a corresponding slot in TransferState storage.
  9511. */
  9512. function retrieveHydrationInfo(rNode, injector, isRootView = false) {
  9513. return _retrieveHydrationInfoImpl(rNode, injector, isRootView);
  9514. }
  9515. /**
  9516. * Retrieves the necessary object from a given ViewRef to serialize:
  9517. * - an LView for component views
  9518. * - an LContainer for cases when component acts as a ViewContainerRef anchor
  9519. * - `null` in case of an embedded view
  9520. */
  9521. function getLNodeForHydration(viewRef) {
  9522. // Reading an internal field from `ViewRef` instance.
  9523. let lView = viewRef._lView;
  9524. const tView = lView[TVIEW];
  9525. // A registered ViewRef might represent an instance of an
  9526. // embedded view, in which case we do not need to annotate it.
  9527. if (tView.type === 2 /* TViewType.Embedded */) {
  9528. return null;
  9529. }
  9530. // Check if it's a root view and if so, retrieve component's
  9531. // LView from the first slot after the header.
  9532. if (isRootView(lView)) {
  9533. lView = lView[HEADER_OFFSET];
  9534. }
  9535. return lView;
  9536. }
  9537. function getTextNodeContent(node) {
  9538. return node.textContent?.replace(/\s/gm, '');
  9539. }
  9540. /**
  9541. * Restores text nodes and separators into the DOM that were lost during SSR
  9542. * serialization. The hydration process replaces empty text nodes and text
  9543. * nodes that are immediately adjacent to other text nodes with comment nodes
  9544. * that this method filters on to restore those missing nodes that the
  9545. * hydration process is expecting to be present.
  9546. *
  9547. * @param node The app's root HTML Element
  9548. */
  9549. function processTextNodeMarkersBeforeHydration(node) {
  9550. const doc = getDocument();
  9551. const commentNodesIterator = doc.createNodeIterator(node, NodeFilter.SHOW_COMMENT, {
  9552. acceptNode(node) {
  9553. const content = getTextNodeContent(node);
  9554. const isTextNodeMarker = content === "ngetn" /* TextNodeMarker.EmptyNode */ || content === "ngtns" /* TextNodeMarker.Separator */;
  9555. return isTextNodeMarker ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
  9556. },
  9557. });
  9558. let currentNode;
  9559. // We cannot modify the DOM while using the commentIterator,
  9560. // because it throws off the iterator state.
  9561. // So we collect all marker nodes first and then follow up with
  9562. // applying the changes to the DOM: either inserting an empty node
  9563. // or just removing the marker if it was used as a separator.
  9564. const nodes = [];
  9565. while ((currentNode = commentNodesIterator.nextNode())) {
  9566. nodes.push(currentNode);
  9567. }
  9568. for (const node of nodes) {
  9569. if (node.textContent === "ngetn" /* TextNodeMarker.EmptyNode */) {
  9570. node.replaceWith(doc.createTextNode(''));
  9571. }
  9572. else {
  9573. node.remove();
  9574. }
  9575. }
  9576. }
  9577. /**
  9578. * Internal type that represents a claimed node.
  9579. * Only used in dev mode.
  9580. */
  9581. var HydrationStatus;
  9582. (function (HydrationStatus) {
  9583. HydrationStatus["Hydrated"] = "hydrated";
  9584. HydrationStatus["Skipped"] = "skipped";
  9585. HydrationStatus["Mismatched"] = "mismatched";
  9586. })(HydrationStatus || (HydrationStatus = {}));
  9587. const HYDRATION_INFO_KEY = '__ngDebugHydrationInfo__';
  9588. function patchHydrationInfo(node, info) {
  9589. node[HYDRATION_INFO_KEY] = info;
  9590. }
  9591. function readHydrationInfo(node) {
  9592. return node[HYDRATION_INFO_KEY] ?? null;
  9593. }
  9594. /**
  9595. * Marks a node as "claimed" by hydration process.
  9596. * This is needed to make assessments in tests whether
  9597. * the hydration process handled all nodes.
  9598. */
  9599. function markRNodeAsClaimedByHydration(node, checkIfAlreadyClaimed = true) {
  9600. if (!ngDevMode) {
  9601. throw new Error('Calling `markRNodeAsClaimedByHydration` in prod mode ' +
  9602. 'is not supported and likely a mistake.');
  9603. }
  9604. if (checkIfAlreadyClaimed && isRNodeClaimedForHydration(node)) {
  9605. throw new Error('Trying to claim a node, which was claimed already.');
  9606. }
  9607. patchHydrationInfo(node, { status: HydrationStatus.Hydrated });
  9608. ngDevMode.hydratedNodes++;
  9609. }
  9610. function markRNodeAsSkippedByHydration(node) {
  9611. if (!ngDevMode) {
  9612. throw new Error('Calling `markRNodeAsSkippedByHydration` in prod mode ' +
  9613. 'is not supported and likely a mistake.');
  9614. }
  9615. patchHydrationInfo(node, { status: HydrationStatus.Skipped });
  9616. ngDevMode.componentsSkippedHydration++;
  9617. }
  9618. function countBlocksSkippedByHydration(injector) {
  9619. const transferState = injector.get(TransferState);
  9620. const nghDeferData = transferState.get(NGH_DEFER_BLOCKS_KEY, {});
  9621. if (ngDevMode) {
  9622. ngDevMode.deferBlocksWithIncrementalHydration = Object.keys(nghDeferData).length;
  9623. }
  9624. }
  9625. function markRNodeAsHavingHydrationMismatch(node, expectedNodeDetails = null, actualNodeDetails = null) {
  9626. if (!ngDevMode) {
  9627. throw new Error('Calling `markRNodeAsMismatchedByHydration` in prod mode ' +
  9628. 'is not supported and likely a mistake.');
  9629. }
  9630. // The RNode can be a standard HTMLElement (not an Angular component or directive)
  9631. // The devtools component tree only displays Angular components & directives
  9632. // Therefore we attach the debug info to the closest component/directive
  9633. while (node && !getComponent(node)) {
  9634. node = node?.parentNode;
  9635. }
  9636. if (node) {
  9637. patchHydrationInfo(node, {
  9638. status: HydrationStatus.Mismatched,
  9639. expectedNodeDetails,
  9640. actualNodeDetails,
  9641. });
  9642. }
  9643. }
  9644. function isRNodeClaimedForHydration(node) {
  9645. return readHydrationInfo(node)?.status === HydrationStatus.Hydrated;
  9646. }
  9647. function setSegmentHead(hydrationInfo, index, node) {
  9648. hydrationInfo.segmentHeads ??= {};
  9649. hydrationInfo.segmentHeads[index] = node;
  9650. }
  9651. function getSegmentHead(hydrationInfo, index) {
  9652. return hydrationInfo.segmentHeads?.[index] ?? null;
  9653. }
  9654. function isIncrementalHydrationEnabled(injector) {
  9655. return injector.get(IS_INCREMENTAL_HYDRATION_ENABLED, false, {
  9656. optional: true,
  9657. });
  9658. }
  9659. /** Throws an error if the incremental hydration is not enabled */
  9660. function assertIncrementalHydrationIsConfigured(injector) {
  9661. if (!isIncrementalHydrationEnabled(injector)) {
  9662. throw new RuntimeError(508 /* RuntimeErrorCode.MISCONFIGURED_INCREMENTAL_HYDRATION */, 'Angular has detected that some `@defer` blocks use `hydrate` triggers, ' +
  9663. 'but incremental hydration was not enabled. Please ensure that the `withIncrementalHydration()` ' +
  9664. 'call is added as an argument for the `provideClientHydration()` function call ' +
  9665. 'in your application config.');
  9666. }
  9667. }
  9668. /** Throws an error if the ssrUniqueId on the LDeferBlockDetails is not present */
  9669. function assertSsrIdDefined(ssrUniqueId) {
  9670. assertDefined(ssrUniqueId, 'Internal error: expecting an SSR id for a defer block that should be hydrated, but the id is not present');
  9671. }
  9672. /**
  9673. * Returns the size of an <ng-container>, using either the information
  9674. * serialized in `ELEMENT_CONTAINERS` (element container size) or by
  9675. * computing the sum of root nodes in all dehydrated views in a given
  9676. * container (in case this `<ng-container>` was also used as a view
  9677. * container host node, e.g. <ng-container *ngIf>).
  9678. */
  9679. function getNgContainerSize(hydrationInfo, index) {
  9680. const data = hydrationInfo.data;
  9681. let size = data[ELEMENT_CONTAINERS]?.[index] ?? null;
  9682. // If there is no serialized information available in the `ELEMENT_CONTAINERS` slot,
  9683. // check if we have info about view containers at this location (e.g.
  9684. // `<ng-container *ngIf>`) and use container size as a number of root nodes in this
  9685. // element container.
  9686. if (size === null && data[CONTAINERS]?.[index]) {
  9687. size = calcSerializedContainerSize(hydrationInfo, index);
  9688. }
  9689. return size;
  9690. }
  9691. function isSerializedElementContainer(hydrationInfo, index) {
  9692. return hydrationInfo.data[ELEMENT_CONTAINERS]?.[index] !== undefined;
  9693. }
  9694. function getSerializedContainerViews(hydrationInfo, index) {
  9695. return hydrationInfo.data[CONTAINERS]?.[index] ?? null;
  9696. }
  9697. /**
  9698. * Computes the size of a serialized container (the number of root nodes)
  9699. * by calculating the sum of root nodes in all dehydrated views in this container.
  9700. */
  9701. function calcSerializedContainerSize(hydrationInfo, index) {
  9702. const views = getSerializedContainerViews(hydrationInfo, index) ?? [];
  9703. let numNodes = 0;
  9704. for (let view of views) {
  9705. numNodes += view[NUM_ROOT_NODES] * (view[MULTIPLIER] ?? 1);
  9706. }
  9707. return numNodes;
  9708. }
  9709. /**
  9710. * Attempt to initialize the `disconnectedNodes` field of the given
  9711. * `DehydratedView`. Returns the initialized value.
  9712. */
  9713. function initDisconnectedNodes(hydrationInfo) {
  9714. // Check if we are processing disconnected info for the first time.
  9715. if (typeof hydrationInfo.disconnectedNodes === 'undefined') {
  9716. const nodeIds = hydrationInfo.data[DISCONNECTED_NODES];
  9717. hydrationInfo.disconnectedNodes = nodeIds ? new Set(nodeIds) : null;
  9718. }
  9719. return hydrationInfo.disconnectedNodes;
  9720. }
  9721. /**
  9722. * Checks whether a node is annotated as "disconnected", i.e. not present
  9723. * in the DOM at serialization time. We should not attempt hydration for
  9724. * such nodes and instead, use a regular "creation mode".
  9725. */
  9726. function isDisconnectedNode$1(hydrationInfo, index) {
  9727. // Check if we are processing disconnected info for the first time.
  9728. if (typeof hydrationInfo.disconnectedNodes === 'undefined') {
  9729. const nodeIds = hydrationInfo.data[DISCONNECTED_NODES];
  9730. hydrationInfo.disconnectedNodes = nodeIds ? new Set(nodeIds) : null;
  9731. }
  9732. return !!initDisconnectedNodes(hydrationInfo)?.has(index);
  9733. }
  9734. /**
  9735. * Helper function to prepare text nodes for serialization by ensuring
  9736. * that seperate logical text blocks in the DOM remain separate after
  9737. * serialization.
  9738. */
  9739. function processTextNodeBeforeSerialization(context, node) {
  9740. // Handle cases where text nodes can be lost after DOM serialization:
  9741. // 1. When there is an *empty text node* in DOM: in this case, this
  9742. // node would not make it into the serialized string and as a result,
  9743. // this node wouldn't be created in a browser. This would result in
  9744. // a mismatch during the hydration, where the runtime logic would expect
  9745. // a text node to be present in live DOM, but no text node would exist.
  9746. // Example: `<span>{{ name }}</span>` when the `name` is an empty string.
  9747. // This would result in `<span></span>` string after serialization and
  9748. // in a browser only the `span` element would be created. To resolve that,
  9749. // an extra comment node is appended in place of an empty text node and
  9750. // that special comment node is replaced with an empty text node *before*
  9751. // hydration.
  9752. // 2. When there are 2 consecutive text nodes present in the DOM.
  9753. // Example: `<div>Hello <ng-container *ngIf="true">world</ng-container></div>`.
  9754. // In this scenario, the live DOM would look like this:
  9755. // <div>#text('Hello ') #text('world') #comment('container')</div>
  9756. // Serialized string would look like this: `<div>Hello world<!--container--></div>`.
  9757. // The live DOM in a browser after that would be:
  9758. // <div>#text('Hello world') #comment('container')</div>
  9759. // Notice how 2 text nodes are now "merged" into one. This would cause hydration
  9760. // logic to fail, since it'd expect 2 text nodes being present, not one.
  9761. // To fix this, we insert a special comment node in between those text nodes, so
  9762. // serialized representation is: `<div>Hello <!--ngtns-->world<!--container--></div>`.
  9763. // This forces browser to create 2 text nodes separated by a comment node.
  9764. // Before running a hydration process, this special comment node is removed, so the
  9765. // live DOM has exactly the same state as it was before serialization.
  9766. // Collect this node as required special annotation only when its
  9767. // contents is empty. Otherwise, such text node would be present on
  9768. // the client after server-side rendering and no special handling needed.
  9769. const el = node;
  9770. const corruptedTextNodes = context.corruptedTextNodes;
  9771. if (el.textContent === '') {
  9772. corruptedTextNodes.set(el, "ngetn" /* TextNodeMarker.EmptyNode */);
  9773. }
  9774. else if (el.nextSibling?.nodeType === Node.TEXT_NODE) {
  9775. corruptedTextNodes.set(el, "ngtns" /* TextNodeMarker.Separator */);
  9776. }
  9777. }
  9778. function convertHydrateTriggersToJsAction(triggers) {
  9779. let actionList = [];
  9780. if (triggers !== null) {
  9781. if (triggers.has(4 /* DeferBlockTrigger.Hover */)) {
  9782. actionList.push(...hoverEventNames);
  9783. }
  9784. if (triggers.has(3 /* DeferBlockTrigger.Interaction */)) {
  9785. actionList.push(...interactionEventNames);
  9786. }
  9787. }
  9788. return actionList;
  9789. }
  9790. /**
  9791. * Builds a queue of blocks that need to be hydrated, looking up the
  9792. * tree to the topmost defer block that exists in the tree that hasn't
  9793. * been hydrated, but exists in the registry. This queue is in top down
  9794. * hierarchical order as a list of defer block ids.
  9795. * Note: This is utilizing serialized information to navigate up the tree
  9796. */
  9797. function getParentBlockHydrationQueue(deferBlockId, injector) {
  9798. const dehydratedBlockRegistry = injector.get(DEHYDRATED_BLOCK_REGISTRY);
  9799. const transferState = injector.get(TransferState);
  9800. const deferBlockParents = transferState.get(NGH_DEFER_BLOCKS_KEY, {});
  9801. let isTopMostDeferBlock = false;
  9802. let currentBlockId = deferBlockId;
  9803. let parentBlockPromise = null;
  9804. const hydrationQueue = [];
  9805. while (!isTopMostDeferBlock && currentBlockId) {
  9806. ngDevMode &&
  9807. assertEqual(hydrationQueue.indexOf(currentBlockId), -1, 'Internal error: defer block hierarchy has a cycle.');
  9808. isTopMostDeferBlock = dehydratedBlockRegistry.has(currentBlockId);
  9809. const hydratingParentBlock = dehydratedBlockRegistry.hydrating.get(currentBlockId);
  9810. if (parentBlockPromise === null && hydratingParentBlock != null) {
  9811. parentBlockPromise = hydratingParentBlock.promise;
  9812. break;
  9813. }
  9814. hydrationQueue.unshift(currentBlockId);
  9815. currentBlockId = deferBlockParents[currentBlockId][DEFER_PARENT_BLOCK_ID];
  9816. }
  9817. return { parentBlockPromise, hydrationQueue };
  9818. }
  9819. function gatherDeferBlocksByJSActionAttribute(doc) {
  9820. const jsactionNodes = doc.body.querySelectorAll('[jsaction]');
  9821. const blockMap = new Set();
  9822. const eventTypes = [hoverEventNames.join(':;'), interactionEventNames.join(':;')].join('|');
  9823. for (let node of jsactionNodes) {
  9824. const attr = node.getAttribute('jsaction');
  9825. const blockId = node.getAttribute('ngb');
  9826. if (attr?.match(eventTypes) && blockId !== null) {
  9827. blockMap.add(node);
  9828. }
  9829. }
  9830. return blockMap;
  9831. }
  9832. function appendDeferBlocksToJSActionMap(doc, injector) {
  9833. const blockMap = gatherDeferBlocksByJSActionAttribute(doc);
  9834. const jsActionMap = injector.get(JSACTION_BLOCK_ELEMENT_MAP);
  9835. for (let rNode of blockMap) {
  9836. sharedMapFunction(rNode, jsActionMap);
  9837. }
  9838. }
  9839. /**
  9840. * Retrieves defer block hydration information from the TransferState.
  9841. *
  9842. * @param injector Injector that this component has access to.
  9843. */
  9844. let _retrieveDeferBlockDataImpl = () => {
  9845. return {};
  9846. };
  9847. function retrieveDeferBlockDataImpl(injector) {
  9848. const transferState = injector.get(TransferState, null, { optional: true });
  9849. if (transferState !== null) {
  9850. const nghDeferData = transferState.get(NGH_DEFER_BLOCKS_KEY, {});
  9851. ngDevMode &&
  9852. assertDefined(nghDeferData, 'Unable to retrieve defer block info from the TransferState.');
  9853. return nghDeferData;
  9854. }
  9855. return {};
  9856. }
  9857. /**
  9858. * Sets the implementation for the `retrieveDeferBlockData` function.
  9859. */
  9860. function enableRetrieveDeferBlockDataImpl() {
  9861. _retrieveDeferBlockDataImpl = retrieveDeferBlockDataImpl;
  9862. }
  9863. /**
  9864. * Retrieves defer block data from TransferState storage
  9865. */
  9866. function retrieveDeferBlockData(injector) {
  9867. return _retrieveDeferBlockDataImpl(injector);
  9868. }
  9869. function isTimerTrigger(triggerInfo) {
  9870. return typeof triggerInfo === 'object' && triggerInfo.trigger === 5 /* DeferBlockTrigger.Timer */;
  9871. }
  9872. function getHydrateTimerTrigger(blockData) {
  9873. const trigger = blockData[DEFER_HYDRATE_TRIGGERS]?.find((t) => isTimerTrigger(t));
  9874. return trigger?.delay ?? null;
  9875. }
  9876. function hasHydrateTrigger(blockData, trigger) {
  9877. return blockData[DEFER_HYDRATE_TRIGGERS]?.includes(trigger) ?? false;
  9878. }
  9879. /**
  9880. * Creates a summary of the given serialized defer block, which is used later to properly initialize
  9881. * specific triggers.
  9882. */
  9883. function createBlockSummary(blockInfo) {
  9884. return {
  9885. data: blockInfo,
  9886. hydrate: {
  9887. idle: hasHydrateTrigger(blockInfo, 0 /* DeferBlockTrigger.Idle */),
  9888. immediate: hasHydrateTrigger(blockInfo, 1 /* DeferBlockTrigger.Immediate */),
  9889. timer: getHydrateTimerTrigger(blockInfo),
  9890. viewport: hasHydrateTrigger(blockInfo, 2 /* DeferBlockTrigger.Viewport */),
  9891. },
  9892. };
  9893. }
  9894. /**
  9895. * Processes all of the defer block data in the transfer state and creates a map of the summaries
  9896. */
  9897. function processBlockData(injector) {
  9898. const blockData = retrieveDeferBlockData(injector);
  9899. let blockDetails = new Map();
  9900. for (let blockId in blockData) {
  9901. blockDetails.set(blockId, createBlockSummary(blockData[blockId]));
  9902. }
  9903. return blockDetails;
  9904. }
  9905. function isSsrContentsIntegrity(node) {
  9906. return (!!node &&
  9907. node.nodeType === Node.COMMENT_NODE &&
  9908. node.textContent?.trim() === SSR_CONTENT_INTEGRITY_MARKER);
  9909. }
  9910. function skipTextNodes(node) {
  9911. // Ignore whitespace. Before the <body>, we shouldn't find text nodes that aren't whitespace.
  9912. while (node && node.nodeType === Node.TEXT_NODE) {
  9913. node = node.previousSibling;
  9914. }
  9915. return node;
  9916. }
  9917. /**
  9918. * Verifies whether the DOM contains a special marker added during SSR time to make sure
  9919. * there is no SSR'ed contents transformations happen after SSR is completed. Typically that
  9920. * happens either by CDN or during the build process as an optimization to remove comment nodes.
  9921. * Hydration process requires comment nodes produced by Angular to locate correct DOM segments.
  9922. * When this special marker is *not* present - throw an error and do not proceed with hydration,
  9923. * since it will not be able to function correctly.
  9924. *
  9925. * Note: this function is invoked only on the client, so it's safe to use DOM APIs.
  9926. */
  9927. function verifySsrContentsIntegrity(doc) {
  9928. for (const node of doc.body.childNodes) {
  9929. if (isSsrContentsIntegrity(node)) {
  9930. return;
  9931. }
  9932. }
  9933. // Check if the HTML parser may have moved the marker to just before the <body> tag,
  9934. // e.g. because the body tag was implicit and not present in the markup. An implicit body
  9935. // tag is unlikely to interfer with whitespace/comments inside of the app's root element.
  9936. // Case 1: Implicit body. Example:
  9937. // <!doctype html><head><title>Hi</title></head><!--nghm--><app-root></app-root>
  9938. const beforeBody = skipTextNodes(doc.body.previousSibling);
  9939. if (isSsrContentsIntegrity(beforeBody)) {
  9940. return;
  9941. }
  9942. // Case 2: Implicit body & head. Example:
  9943. // <!doctype html><head><title>Hi</title><!--nghm--><app-root></app-root>
  9944. let endOfHead = skipTextNodes(doc.head.lastChild);
  9945. if (isSsrContentsIntegrity(endOfHead)) {
  9946. return;
  9947. }
  9948. throw new RuntimeError(-507 /* RuntimeErrorCode.MISSING_SSR_CONTENT_INTEGRITY_MARKER */, typeof ngDevMode !== 'undefined' &&
  9949. ngDevMode &&
  9950. 'Angular hydration logic detected that HTML content of this page was modified after it ' +
  9951. 'was produced during server side rendering. Make sure that there are no optimizations ' +
  9952. 'that remove comment nodes from HTML enabled on your CDN. Angular hydration ' +
  9953. 'relies on HTML produced by the server, including whitespaces and comment nodes.');
  9954. }
  9955. /** Refreshes all content queries declared by directives in a given view */
  9956. function refreshContentQueries(tView, lView) {
  9957. const contentQueries = tView.contentQueries;
  9958. if (contentQueries !== null) {
  9959. const prevConsumer = setActiveConsumer$1(null);
  9960. try {
  9961. for (let i = 0; i < contentQueries.length; i += 2) {
  9962. const queryStartIdx = contentQueries[i];
  9963. const directiveDefIdx = contentQueries[i + 1];
  9964. if (directiveDefIdx !== -1) {
  9965. const directiveDef = tView.data[directiveDefIdx];
  9966. ngDevMode && assertDefined(directiveDef, 'DirectiveDef not found.');
  9967. ngDevMode &&
  9968. assertDefined(directiveDef.contentQueries, 'contentQueries function should be defined');
  9969. setCurrentQueryIndex(queryStartIdx);
  9970. directiveDef.contentQueries(2 /* RenderFlags.Update */, lView[directiveDefIdx], directiveDefIdx);
  9971. }
  9972. }
  9973. }
  9974. finally {
  9975. setActiveConsumer$1(prevConsumer);
  9976. }
  9977. }
  9978. }
  9979. function executeViewQueryFn(flags, viewQueryFn, component) {
  9980. ngDevMode && assertDefined(viewQueryFn, 'View queries function to execute must be defined.');
  9981. setCurrentQueryIndex(0);
  9982. const prevConsumer = setActiveConsumer$1(null);
  9983. try {
  9984. viewQueryFn(flags, component);
  9985. }
  9986. finally {
  9987. setActiveConsumer$1(prevConsumer);
  9988. }
  9989. }
  9990. function executeContentQueries(tView, tNode, lView) {
  9991. if (isContentQueryHost(tNode)) {
  9992. const prevConsumer = setActiveConsumer$1(null);
  9993. try {
  9994. const start = tNode.directiveStart;
  9995. const end = tNode.directiveEnd;
  9996. for (let directiveIndex = start; directiveIndex < end; directiveIndex++) {
  9997. const def = tView.data[directiveIndex];
  9998. if (def.contentQueries) {
  9999. const directiveInstance = lView[directiveIndex];
  10000. ngDevMode &&
  10001. assertDefined(directiveIndex, 'Incorrect reference to a directive defining a content query');
  10002. def.contentQueries(1 /* RenderFlags.Create */, directiveInstance, directiveIndex);
  10003. }
  10004. }
  10005. }
  10006. finally {
  10007. setActiveConsumer$1(prevConsumer);
  10008. }
  10009. }
  10010. }
  10011. /**
  10012. * Defines the CSS styles encapsulation policies for the {@link /api/core/Component Component} decorator's
  10013. * `encapsulation` option.
  10014. *
  10015. * See {@link Component#encapsulation encapsulation}.
  10016. *
  10017. * @usageNotes
  10018. * ### Example
  10019. *
  10020. * {@example core/ts/metadata/encapsulation.ts region='longform'}
  10021. *
  10022. * @publicApi
  10023. */
  10024. var ViewEncapsulation;
  10025. (function (ViewEncapsulation) {
  10026. // TODO: consider making `ViewEncapsulation` a `const enum` instead. See
  10027. // https://github.com/angular/angular/issues/44119 for additional information.
  10028. /**
  10029. * Emulates a native Shadow DOM encapsulation behavior by adding a specific attribute to the
  10030. * component's host element and applying the same attribute to all the CSS selectors provided
  10031. * via {@link Component#styles styles} or {@link Component#styleUrls styleUrls}.
  10032. *
  10033. * This is the default option.
  10034. */
  10035. ViewEncapsulation[ViewEncapsulation["Emulated"] = 0] = "Emulated";
  10036. // Historically the 1 value was for `Native` encapsulation which has been removed as of v11.
  10037. /**
  10038. * Doesn't provide any sort of CSS style encapsulation, meaning that all the styles provided
  10039. * via {@link Component#styles styles} or {@link Component#styleUrls styleUrls} are applicable
  10040. * to any HTML element of the application regardless of their host Component.
  10041. */
  10042. ViewEncapsulation[ViewEncapsulation["None"] = 2] = "None";
  10043. /**
  10044. * Uses the browser's native Shadow DOM API to encapsulate CSS styles, meaning that it creates
  10045. * a ShadowRoot for the component's host element which is then used to encapsulate
  10046. * all the Component's styling.
  10047. */
  10048. ViewEncapsulation[ViewEncapsulation["ShadowDom"] = 3] = "ShadowDom";
  10049. })(ViewEncapsulation || (ViewEncapsulation = {}));
  10050. /**
  10051. * @fileoverview
  10052. * A module to facilitate use of a Trusted Types policy internally within
  10053. * Angular. It lazily constructs the Trusted Types policy, providing helper
  10054. * utilities for promoting strings to Trusted Types. When Trusted Types are not
  10055. * available, strings are used as a fallback.
  10056. * @security All use of this module is security-sensitive and should go through
  10057. * security review.
  10058. */
  10059. /**
  10060. * The Trusted Types policy, or null if Trusted Types are not
  10061. * enabled/supported, or undefined if the policy has not been created yet.
  10062. */
  10063. let policy$1;
  10064. /**
  10065. * Returns the Trusted Types policy, or null if Trusted Types are not
  10066. * enabled/supported. The first call to this function will create the policy.
  10067. */
  10068. function getPolicy$1() {
  10069. if (policy$1 === undefined) {
  10070. policy$1 = null;
  10071. if (_global.trustedTypes) {
  10072. try {
  10073. policy$1 = _global.trustedTypes.createPolicy('angular', {
  10074. createHTML: (s) => s,
  10075. createScript: (s) => s,
  10076. createScriptURL: (s) => s,
  10077. });
  10078. }
  10079. catch {
  10080. // trustedTypes.createPolicy throws if called with a name that is
  10081. // already registered, even in report-only mode. Until the API changes,
  10082. // catch the error not to break the applications functionally. In such
  10083. // cases, the code will fall back to using strings.
  10084. }
  10085. }
  10086. }
  10087. return policy$1;
  10088. }
  10089. /**
  10090. * Unsafely promote a string to a TrustedHTML, falling back to strings when
  10091. * Trusted Types are not available.
  10092. * @security This is a security-sensitive function; any use of this function
  10093. * must go through security review. In particular, it must be assured that the
  10094. * provided string will never cause an XSS vulnerability if used in a context
  10095. * that will be interpreted as HTML by a browser, e.g. when assigning to
  10096. * element.innerHTML.
  10097. */
  10098. function trustedHTMLFromString(html) {
  10099. return getPolicy$1()?.createHTML(html) || html;
  10100. }
  10101. /**
  10102. * Unsafely promote a string to a TrustedScriptURL, falling back to strings
  10103. * when Trusted Types are not available.
  10104. * @security This is a security-sensitive function; any use of this function
  10105. * must go through security review. In particular, it must be assured that the
  10106. * provided string will never cause an XSS vulnerability if used in a context
  10107. * that will cause a browser to load and execute a resource, e.g. when
  10108. * assigning to script.src.
  10109. */
  10110. function trustedScriptURLFromString(url) {
  10111. return getPolicy$1()?.createScriptURL(url) || url;
  10112. }
  10113. /**
  10114. * @fileoverview
  10115. * A module to facilitate use of a Trusted Types policy internally within
  10116. * Angular specifically for bypassSecurityTrust* and custom sanitizers. It
  10117. * lazily constructs the Trusted Types policy, providing helper utilities for
  10118. * promoting strings to Trusted Types. When Trusted Types are not available,
  10119. * strings are used as a fallback.
  10120. * @security All use of this module is security-sensitive and should go through
  10121. * security review.
  10122. */
  10123. /**
  10124. * The Trusted Types policy, or null if Trusted Types are not
  10125. * enabled/supported, or undefined if the policy has not been created yet.
  10126. */
  10127. let policy;
  10128. /**
  10129. * Returns the Trusted Types policy, or null if Trusted Types are not
  10130. * enabled/supported. The first call to this function will create the policy.
  10131. */
  10132. function getPolicy() {
  10133. if (policy === undefined) {
  10134. policy = null;
  10135. if (_global.trustedTypes) {
  10136. try {
  10137. policy = _global.trustedTypes.createPolicy('angular#unsafe-bypass', {
  10138. createHTML: (s) => s,
  10139. createScript: (s) => s,
  10140. createScriptURL: (s) => s,
  10141. });
  10142. }
  10143. catch {
  10144. // trustedTypes.createPolicy throws if called with a name that is
  10145. // already registered, even in report-only mode. Until the API changes,
  10146. // catch the error not to break the applications functionally. In such
  10147. // cases, the code will fall back to using strings.
  10148. }
  10149. }
  10150. }
  10151. return policy;
  10152. }
  10153. /**
  10154. * Unsafely promote a string to a TrustedHTML, falling back to strings when
  10155. * Trusted Types are not available.
  10156. * @security This is a security-sensitive function; any use of this function
  10157. * must go through security review. In particular, it must be assured that it
  10158. * is only passed strings that come directly from custom sanitizers or the
  10159. * bypassSecurityTrust* functions.
  10160. */
  10161. function trustedHTMLFromStringBypass(html) {
  10162. return getPolicy()?.createHTML(html) || html;
  10163. }
  10164. /**
  10165. * Unsafely promote a string to a TrustedScript, falling back to strings when
  10166. * Trusted Types are not available.
  10167. * @security This is a security-sensitive function; any use of this function
  10168. * must go through security review. In particular, it must be assured that it
  10169. * is only passed strings that come directly from custom sanitizers or the
  10170. * bypassSecurityTrust* functions.
  10171. */
  10172. function trustedScriptFromStringBypass(script) {
  10173. return getPolicy()?.createScript(script) || script;
  10174. }
  10175. /**
  10176. * Unsafely promote a string to a TrustedScriptURL, falling back to strings
  10177. * when Trusted Types are not available.
  10178. * @security This is a security-sensitive function; any use of this function
  10179. * must go through security review. In particular, it must be assured that it
  10180. * is only passed strings that come directly from custom sanitizers or the
  10181. * bypassSecurityTrust* functions.
  10182. */
  10183. function trustedScriptURLFromStringBypass(url) {
  10184. return getPolicy()?.createScriptURL(url) || url;
  10185. }
  10186. class SafeValueImpl {
  10187. changingThisBreaksApplicationSecurity;
  10188. constructor(changingThisBreaksApplicationSecurity) {
  10189. this.changingThisBreaksApplicationSecurity = changingThisBreaksApplicationSecurity;
  10190. }
  10191. toString() {
  10192. return (`SafeValue must use [property]=binding: ${this.changingThisBreaksApplicationSecurity}` +
  10193. ` (see ${XSS_SECURITY_URL})`);
  10194. }
  10195. }
  10196. class SafeHtmlImpl extends SafeValueImpl {
  10197. getTypeName() {
  10198. return "HTML" /* BypassType.Html */;
  10199. }
  10200. }
  10201. class SafeStyleImpl extends SafeValueImpl {
  10202. getTypeName() {
  10203. return "Style" /* BypassType.Style */;
  10204. }
  10205. }
  10206. class SafeScriptImpl extends SafeValueImpl {
  10207. getTypeName() {
  10208. return "Script" /* BypassType.Script */;
  10209. }
  10210. }
  10211. class SafeUrlImpl extends SafeValueImpl {
  10212. getTypeName() {
  10213. return "URL" /* BypassType.Url */;
  10214. }
  10215. }
  10216. class SafeResourceUrlImpl extends SafeValueImpl {
  10217. getTypeName() {
  10218. return "ResourceURL" /* BypassType.ResourceUrl */;
  10219. }
  10220. }
  10221. function unwrapSafeValue(value) {
  10222. return value instanceof SafeValueImpl
  10223. ? value.changingThisBreaksApplicationSecurity
  10224. : value;
  10225. }
  10226. function allowSanitizationBypassAndThrow(value, type) {
  10227. const actualType = getSanitizationBypassType(value);
  10228. if (actualType != null && actualType !== type) {
  10229. // Allow ResourceURLs in URL contexts, they are strictly more trusted.
  10230. if (actualType === "ResourceURL" /* BypassType.ResourceUrl */ && type === "URL" /* BypassType.Url */)
  10231. return true;
  10232. throw new Error(`Required a safe ${type}, got a ${actualType} (see ${XSS_SECURITY_URL})`);
  10233. }
  10234. return actualType === type;
  10235. }
  10236. function getSanitizationBypassType(value) {
  10237. return (value instanceof SafeValueImpl && value.getTypeName()) || null;
  10238. }
  10239. /**
  10240. * Mark `html` string as trusted.
  10241. *
  10242. * This function wraps the trusted string in `String` and brands it in a way which makes it
  10243. * recognizable to {@link htmlSanitizer} to be trusted implicitly.
  10244. *
  10245. * @param trustedHtml `html` string which needs to be implicitly trusted.
  10246. * @returns a `html` which has been branded to be implicitly trusted.
  10247. */
  10248. function bypassSanitizationTrustHtml(trustedHtml) {
  10249. return new SafeHtmlImpl(trustedHtml);
  10250. }
  10251. /**
  10252. * Mark `style` string as trusted.
  10253. *
  10254. * This function wraps the trusted string in `String` and brands it in a way which makes it
  10255. * recognizable to {@link styleSanitizer} to be trusted implicitly.
  10256. *
  10257. * @param trustedStyle `style` string which needs to be implicitly trusted.
  10258. * @returns a `style` hich has been branded to be implicitly trusted.
  10259. */
  10260. function bypassSanitizationTrustStyle(trustedStyle) {
  10261. return new SafeStyleImpl(trustedStyle);
  10262. }
  10263. /**
  10264. * Mark `script` string as trusted.
  10265. *
  10266. * This function wraps the trusted string in `String` and brands it in a way which makes it
  10267. * recognizable to {@link scriptSanitizer} to be trusted implicitly.
  10268. *
  10269. * @param trustedScript `script` string which needs to be implicitly trusted.
  10270. * @returns a `script` which has been branded to be implicitly trusted.
  10271. */
  10272. function bypassSanitizationTrustScript(trustedScript) {
  10273. return new SafeScriptImpl(trustedScript);
  10274. }
  10275. /**
  10276. * Mark `url` string as trusted.
  10277. *
  10278. * This function wraps the trusted string in `String` and brands it in a way which makes it
  10279. * recognizable to {@link urlSanitizer} to be trusted implicitly.
  10280. *
  10281. * @param trustedUrl `url` string which needs to be implicitly trusted.
  10282. * @returns a `url` which has been branded to be implicitly trusted.
  10283. */
  10284. function bypassSanitizationTrustUrl(trustedUrl) {
  10285. return new SafeUrlImpl(trustedUrl);
  10286. }
  10287. /**
  10288. * Mark `url` string as trusted.
  10289. *
  10290. * This function wraps the trusted string in `String` and brands it in a way which makes it
  10291. * recognizable to {@link resourceUrlSanitizer} to be trusted implicitly.
  10292. *
  10293. * @param trustedResourceUrl `url` string which needs to be implicitly trusted.
  10294. * @returns a `url` which has been branded to be implicitly trusted.
  10295. */
  10296. function bypassSanitizationTrustResourceUrl(trustedResourceUrl) {
  10297. return new SafeResourceUrlImpl(trustedResourceUrl);
  10298. }
  10299. /**
  10300. * This helper is used to get hold of an inert tree of DOM elements containing dirty HTML
  10301. * that needs sanitizing.
  10302. * Depending upon browser support we use one of two strategies for doing this.
  10303. * Default: DOMParser strategy
  10304. * Fallback: InertDocument strategy
  10305. */
  10306. function getInertBodyHelper(defaultDoc) {
  10307. const inertDocumentHelper = new InertDocumentHelper(defaultDoc);
  10308. return isDOMParserAvailable() ? new DOMParserHelper(inertDocumentHelper) : inertDocumentHelper;
  10309. }
  10310. /**
  10311. * Uses DOMParser to create and fill an inert body element.
  10312. * This is the default strategy used in browsers that support it.
  10313. */
  10314. class DOMParserHelper {
  10315. inertDocumentHelper;
  10316. constructor(inertDocumentHelper) {
  10317. this.inertDocumentHelper = inertDocumentHelper;
  10318. }
  10319. getInertBodyElement(html) {
  10320. // We add these extra elements to ensure that the rest of the content is parsed as expected
  10321. // e.g. leading whitespace is maintained and tags like `<meta>` do not get hoisted to the
  10322. // `<head>` tag. Note that the `<body>` tag is closed implicitly to prevent unclosed tags
  10323. // in `html` from consuming the otherwise explicit `</body>` tag.
  10324. html = '<body><remove></remove>' + html;
  10325. try {
  10326. const body = new window.DOMParser().parseFromString(trustedHTMLFromString(html), 'text/html').body;
  10327. if (body === null) {
  10328. // In some browsers (e.g. Mozilla/5.0 iPad AppleWebKit Mobile) the `body` property only
  10329. // becomes available in the following tick of the JS engine. In that case we fall back to
  10330. // the `inertDocumentHelper` instead.
  10331. return this.inertDocumentHelper.getInertBodyElement(html);
  10332. }
  10333. body.firstChild?.remove();
  10334. return body;
  10335. }
  10336. catch {
  10337. return null;
  10338. }
  10339. }
  10340. }
  10341. /**
  10342. * Use an HTML5 `template` element to create and fill an inert DOM element.
  10343. * This is the fallback strategy if the browser does not support DOMParser.
  10344. */
  10345. class InertDocumentHelper {
  10346. defaultDoc;
  10347. inertDocument;
  10348. constructor(defaultDoc) {
  10349. this.defaultDoc = defaultDoc;
  10350. this.inertDocument = this.defaultDoc.implementation.createHTMLDocument('sanitization-inert');
  10351. }
  10352. getInertBodyElement(html) {
  10353. const templateEl = this.inertDocument.createElement('template');
  10354. templateEl.innerHTML = trustedHTMLFromString(html);
  10355. return templateEl;
  10356. }
  10357. }
  10358. /**
  10359. * We need to determine whether the DOMParser exists in the global context and
  10360. * supports parsing HTML; HTML parsing support is not as wide as other formats, see
  10361. * https://developer.mozilla.org/en-US/docs/Web/API/DOMParser#Browser_compatibility.
  10362. *
  10363. * @suppress {uselessCode}
  10364. */
  10365. function isDOMParserAvailable() {
  10366. try {
  10367. return !!new window.DOMParser().parseFromString(trustedHTMLFromString(''), 'text/html');
  10368. }
  10369. catch {
  10370. return false;
  10371. }
  10372. }
  10373. /**
  10374. * A pattern that recognizes URLs that are safe wrt. XSS in URL navigation
  10375. * contexts.
  10376. *
  10377. * This regular expression matches a subset of URLs that will not cause script
  10378. * execution if used in URL context within a HTML document. Specifically, this
  10379. * regular expression matches if:
  10380. * (1) Either a protocol that is not javascript:, and that has valid characters
  10381. * (alphanumeric or [+-.]).
  10382. * (2) or no protocol. A protocol must be followed by a colon. The below
  10383. * allows that by allowing colons only after one of the characters [/?#].
  10384. * A colon after a hash (#) must be in the fragment.
  10385. * Otherwise, a colon after a (?) must be in a query.
  10386. * Otherwise, a colon after a single solidus (/) must be in a path.
  10387. * Otherwise, a colon after a double solidus (//) must be in the authority
  10388. * (before port).
  10389. *
  10390. * The pattern disallows &, used in HTML entity declarations before
  10391. * one of the characters in [/?#]. This disallows HTML entities used in the
  10392. * protocol name, which should never happen, e.g. "h&#116;tp" for "http".
  10393. * It also disallows HTML entities in the first path part of a relative path,
  10394. * e.g. "foo&lt;bar/baz". Our existing escaping functions should not produce
  10395. * that. More importantly, it disallows masking of a colon,
  10396. * e.g. "javascript&#58;...".
  10397. *
  10398. * This regular expression was taken from the Closure sanitization library.
  10399. */
  10400. const SAFE_URL_PATTERN = /^(?!javascript:)(?:[a-z0-9+.-]+:|[^&:\/?#]*(?:[\/?#]|$))/i;
  10401. function _sanitizeUrl(url) {
  10402. url = String(url);
  10403. if (url.match(SAFE_URL_PATTERN))
  10404. return url;
  10405. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  10406. console.warn(`WARNING: sanitizing unsafe URL value ${url} (see ${XSS_SECURITY_URL})`);
  10407. }
  10408. return 'unsafe:' + url;
  10409. }
  10410. function tagSet(tags) {
  10411. const res = {};
  10412. for (const t of tags.split(','))
  10413. res[t] = true;
  10414. return res;
  10415. }
  10416. function merge(...sets) {
  10417. const res = {};
  10418. for (const s of sets) {
  10419. for (const v in s) {
  10420. if (s.hasOwnProperty(v))
  10421. res[v] = true;
  10422. }
  10423. }
  10424. return res;
  10425. }
  10426. // Good source of info about elements and attributes
  10427. // https://html.spec.whatwg.org/#semantics
  10428. // https://simon.html5.org/html-elements
  10429. // Safe Void Elements - HTML5
  10430. // https://html.spec.whatwg.org/#void-elements
  10431. const VOID_ELEMENTS = tagSet('area,br,col,hr,img,wbr');
  10432. // Elements that you can, intentionally, leave open (and which close themselves)
  10433. // https://html.spec.whatwg.org/#optional-tags
  10434. const OPTIONAL_END_TAG_BLOCK_ELEMENTS = tagSet('colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr');
  10435. const OPTIONAL_END_TAG_INLINE_ELEMENTS = tagSet('rp,rt');
  10436. const OPTIONAL_END_TAG_ELEMENTS = merge(OPTIONAL_END_TAG_INLINE_ELEMENTS, OPTIONAL_END_TAG_BLOCK_ELEMENTS);
  10437. // Safe Block Elements - HTML5
  10438. const BLOCK_ELEMENTS = merge(OPTIONAL_END_TAG_BLOCK_ELEMENTS, tagSet('address,article,' +
  10439. 'aside,blockquote,caption,center,del,details,dialog,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,' +
  10440. 'h6,header,hgroup,hr,ins,main,map,menu,nav,ol,pre,section,summary,table,ul'));
  10441. // Inline Elements - HTML5
  10442. const INLINE_ELEMENTS = merge(OPTIONAL_END_TAG_INLINE_ELEMENTS, tagSet('a,abbr,acronym,audio,b,' +
  10443. 'bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,picture,q,ruby,rp,rt,s,' +
  10444. 'samp,small,source,span,strike,strong,sub,sup,time,track,tt,u,var,video'));
  10445. const VALID_ELEMENTS = merge(VOID_ELEMENTS, BLOCK_ELEMENTS, INLINE_ELEMENTS, OPTIONAL_END_TAG_ELEMENTS);
  10446. // Attributes that have href and hence need to be sanitized
  10447. const URI_ATTRS = tagSet('background,cite,href,itemtype,longdesc,poster,src,xlink:href');
  10448. const HTML_ATTRS = tagSet('abbr,accesskey,align,alt,autoplay,axis,bgcolor,border,cellpadding,cellspacing,class,clear,color,cols,colspan,' +
  10449. 'compact,controls,coords,datetime,default,dir,download,face,headers,height,hidden,hreflang,hspace,' +
  10450. 'ismap,itemscope,itemprop,kind,label,lang,language,loop,media,muted,nohref,nowrap,open,preload,rel,rev,role,rows,rowspan,rules,' +
  10451. 'scope,scrolling,shape,size,sizes,span,srclang,srcset,start,summary,tabindex,target,title,translate,type,usemap,' +
  10452. 'valign,value,vspace,width');
  10453. // Accessibility attributes as per WAI-ARIA 1.1 (W3C Working Draft 14 December 2018)
  10454. const ARIA_ATTRS = tagSet('aria-activedescendant,aria-atomic,aria-autocomplete,aria-busy,aria-checked,aria-colcount,aria-colindex,' +
  10455. 'aria-colspan,aria-controls,aria-current,aria-describedby,aria-details,aria-disabled,aria-dropeffect,' +
  10456. 'aria-errormessage,aria-expanded,aria-flowto,aria-grabbed,aria-haspopup,aria-hidden,aria-invalid,' +
  10457. 'aria-keyshortcuts,aria-label,aria-labelledby,aria-level,aria-live,aria-modal,aria-multiline,' +
  10458. 'aria-multiselectable,aria-orientation,aria-owns,aria-placeholder,aria-posinset,aria-pressed,aria-readonly,' +
  10459. 'aria-relevant,aria-required,aria-roledescription,aria-rowcount,aria-rowindex,aria-rowspan,aria-selected,' +
  10460. 'aria-setsize,aria-sort,aria-valuemax,aria-valuemin,aria-valuenow,aria-valuetext');
  10461. // NB: This currently consciously doesn't support SVG. SVG sanitization has had several security
  10462. // issues in the past, so it seems safer to leave it out if possible. If support for binding SVG via
  10463. // innerHTML is required, SVG attributes should be added here.
  10464. // NB: Sanitization does not allow <form> elements or other active elements (<button> etc). Those
  10465. // can be sanitized, but they increase security surface area without a legitimate use case, so they
  10466. // are left out here.
  10467. const VALID_ATTRS = merge(URI_ATTRS, HTML_ATTRS, ARIA_ATTRS);
  10468. // Elements whose content should not be traversed/preserved, if the elements themselves are invalid.
  10469. //
  10470. // Typically, `<invalid>Some content</invalid>` would traverse (and in this case preserve)
  10471. // `Some content`, but strip `invalid-element` opening/closing tags. For some elements, though, we
  10472. // don't want to preserve the content, if the elements themselves are going to be removed.
  10473. const SKIP_TRAVERSING_CONTENT_IF_INVALID_ELEMENTS = tagSet('script,style,template');
  10474. /**
  10475. * SanitizingHtmlSerializer serializes a DOM fragment, stripping out any unsafe elements and unsafe
  10476. * attributes.
  10477. */
  10478. class SanitizingHtmlSerializer {
  10479. // Explicitly track if something was stripped, to avoid accidentally warning of sanitization just
  10480. // because characters were re-encoded.
  10481. sanitizedSomething = false;
  10482. buf = [];
  10483. sanitizeChildren(el) {
  10484. // This cannot use a TreeWalker, as it has to run on Angular's various DOM adapters.
  10485. // However this code never accesses properties off of `document` before deleting its contents
  10486. // again, so it shouldn't be vulnerable to DOM clobbering.
  10487. let current = el.firstChild;
  10488. let traverseContent = true;
  10489. let parentNodes = [];
  10490. while (current) {
  10491. if (current.nodeType === Node.ELEMENT_NODE) {
  10492. traverseContent = this.startElement(current);
  10493. }
  10494. else if (current.nodeType === Node.TEXT_NODE) {
  10495. this.chars(current.nodeValue);
  10496. }
  10497. else {
  10498. // Strip non-element, non-text nodes.
  10499. this.sanitizedSomething = true;
  10500. }
  10501. if (traverseContent && current.firstChild) {
  10502. // Push current node to the parent stack before entering its content.
  10503. parentNodes.push(current);
  10504. current = getFirstChild(current);
  10505. continue;
  10506. }
  10507. while (current) {
  10508. // Leaving the element.
  10509. // Walk up and to the right, closing tags as we go.
  10510. if (current.nodeType === Node.ELEMENT_NODE) {
  10511. this.endElement(current);
  10512. }
  10513. let next = getNextSibling(current);
  10514. if (next) {
  10515. current = next;
  10516. break;
  10517. }
  10518. // There was no next sibling, walk up to the parent node (extract it from the stack).
  10519. current = parentNodes.pop();
  10520. }
  10521. }
  10522. return this.buf.join('');
  10523. }
  10524. /**
  10525. * Sanitizes an opening element tag (if valid) and returns whether the element's contents should
  10526. * be traversed. Element content must always be traversed (even if the element itself is not
  10527. * valid/safe), unless the element is one of `SKIP_TRAVERSING_CONTENT_IF_INVALID_ELEMENTS`.
  10528. *
  10529. * @param element The element to sanitize.
  10530. * @return True if the element's contents should be traversed.
  10531. */
  10532. startElement(element) {
  10533. const tagName = getNodeName(element).toLowerCase();
  10534. if (!VALID_ELEMENTS.hasOwnProperty(tagName)) {
  10535. this.sanitizedSomething = true;
  10536. return !SKIP_TRAVERSING_CONTENT_IF_INVALID_ELEMENTS.hasOwnProperty(tagName);
  10537. }
  10538. this.buf.push('<');
  10539. this.buf.push(tagName);
  10540. const elAttrs = element.attributes;
  10541. for (let i = 0; i < elAttrs.length; i++) {
  10542. const elAttr = elAttrs.item(i);
  10543. const attrName = elAttr.name;
  10544. const lower = attrName.toLowerCase();
  10545. if (!VALID_ATTRS.hasOwnProperty(lower)) {
  10546. this.sanitizedSomething = true;
  10547. continue;
  10548. }
  10549. let value = elAttr.value;
  10550. // TODO(martinprobst): Special case image URIs for data:image/...
  10551. if (URI_ATTRS[lower])
  10552. value = _sanitizeUrl(value);
  10553. this.buf.push(' ', attrName, '="', encodeEntities(value), '"');
  10554. }
  10555. this.buf.push('>');
  10556. return true;
  10557. }
  10558. endElement(current) {
  10559. const tagName = getNodeName(current).toLowerCase();
  10560. if (VALID_ELEMENTS.hasOwnProperty(tagName) && !VOID_ELEMENTS.hasOwnProperty(tagName)) {
  10561. this.buf.push('</');
  10562. this.buf.push(tagName);
  10563. this.buf.push('>');
  10564. }
  10565. }
  10566. chars(chars) {
  10567. this.buf.push(encodeEntities(chars));
  10568. }
  10569. }
  10570. /**
  10571. * Verifies whether a given child node is a descendant of a given parent node.
  10572. * It may not be the case when properties like `.firstChild` are clobbered and
  10573. * accessing `.firstChild` results in an unexpected node returned.
  10574. */
  10575. function isClobberedElement(parentNode, childNode) {
  10576. return ((parentNode.compareDocumentPosition(childNode) & Node.DOCUMENT_POSITION_CONTAINED_BY) !==
  10577. Node.DOCUMENT_POSITION_CONTAINED_BY);
  10578. }
  10579. /**
  10580. * Retrieves next sibling node and makes sure that there is no
  10581. * clobbering of the `nextSibling` property happening.
  10582. */
  10583. function getNextSibling(node) {
  10584. const nextSibling = node.nextSibling;
  10585. // Make sure there is no `nextSibling` clobbering: navigating to
  10586. // the next sibling and going back to the previous one should result
  10587. // in the original node.
  10588. if (nextSibling && node !== nextSibling.previousSibling) {
  10589. throw clobberedElementError(nextSibling);
  10590. }
  10591. return nextSibling;
  10592. }
  10593. /**
  10594. * Retrieves first child node and makes sure that there is no
  10595. * clobbering of the `firstChild` property happening.
  10596. */
  10597. function getFirstChild(node) {
  10598. const firstChild = node.firstChild;
  10599. if (firstChild && isClobberedElement(node, firstChild)) {
  10600. throw clobberedElementError(firstChild);
  10601. }
  10602. return firstChild;
  10603. }
  10604. /** Gets a reasonable nodeName, even for clobbered nodes. */
  10605. function getNodeName(node) {
  10606. const nodeName = node.nodeName;
  10607. // If the property is clobbered, assume it is an `HTMLFormElement`.
  10608. return typeof nodeName === 'string' ? nodeName : 'FORM';
  10609. }
  10610. function clobberedElementError(node) {
  10611. return new Error(`Failed to sanitize html because the element is clobbered: ${node.outerHTML}`);
  10612. }
  10613. // Regular Expressions for parsing tags and attributes
  10614. const SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
  10615. // ! to ~ is the ASCII range.
  10616. const NON_ALPHANUMERIC_REGEXP = /([^\#-~ |!])/g;
  10617. /**
  10618. * Escapes all potentially dangerous characters, so that the
  10619. * resulting string can be safely inserted into attribute or
  10620. * element text.
  10621. * @param value
  10622. */
  10623. function encodeEntities(value) {
  10624. return value
  10625. .replace(/&/g, '&amp;')
  10626. .replace(SURROGATE_PAIR_REGEXP, function (match) {
  10627. const hi = match.charCodeAt(0);
  10628. const low = match.charCodeAt(1);
  10629. return '&#' + ((hi - 0xd800) * 0x400 + (low - 0xdc00) + 0x10000) + ';';
  10630. })
  10631. .replace(NON_ALPHANUMERIC_REGEXP, function (match) {
  10632. return '&#' + match.charCodeAt(0) + ';';
  10633. })
  10634. .replace(/</g, '&lt;')
  10635. .replace(/>/g, '&gt;');
  10636. }
  10637. let inertBodyHelper;
  10638. /**
  10639. * Sanitizes the given unsafe, untrusted HTML fragment, and returns HTML text that is safe to add to
  10640. * the DOM in a browser environment.
  10641. */
  10642. function _sanitizeHtml(defaultDoc, unsafeHtmlInput) {
  10643. let inertBodyElement = null;
  10644. try {
  10645. inertBodyHelper = inertBodyHelper || getInertBodyHelper(defaultDoc);
  10646. // Make sure unsafeHtml is actually a string (TypeScript types are not enforced at runtime).
  10647. let unsafeHtml = unsafeHtmlInput ? String(unsafeHtmlInput) : '';
  10648. inertBodyElement = inertBodyHelper.getInertBodyElement(unsafeHtml);
  10649. // mXSS protection. Repeatedly parse the document to make sure it stabilizes, so that a browser
  10650. // trying to auto-correct incorrect HTML cannot cause formerly inert HTML to become dangerous.
  10651. let mXSSAttempts = 5;
  10652. let parsedHtml = unsafeHtml;
  10653. do {
  10654. if (mXSSAttempts === 0) {
  10655. throw new Error('Failed to sanitize html because the input is unstable');
  10656. }
  10657. mXSSAttempts--;
  10658. unsafeHtml = parsedHtml;
  10659. parsedHtml = inertBodyElement.innerHTML;
  10660. inertBodyElement = inertBodyHelper.getInertBodyElement(unsafeHtml);
  10661. } while (unsafeHtml !== parsedHtml);
  10662. const sanitizer = new SanitizingHtmlSerializer();
  10663. const safeHtml = sanitizer.sanitizeChildren(getTemplateContent(inertBodyElement) || inertBodyElement);
  10664. if ((typeof ngDevMode === 'undefined' || ngDevMode) && sanitizer.sanitizedSomething) {
  10665. console.warn(`WARNING: sanitizing HTML stripped some content, see ${XSS_SECURITY_URL}`);
  10666. }
  10667. return trustedHTMLFromString(safeHtml);
  10668. }
  10669. finally {
  10670. // In case anything goes wrong, clear out inertElement to reset the entire DOM structure.
  10671. if (inertBodyElement) {
  10672. const parent = getTemplateContent(inertBodyElement) || inertBodyElement;
  10673. while (parent.firstChild) {
  10674. parent.firstChild.remove();
  10675. }
  10676. }
  10677. }
  10678. }
  10679. function getTemplateContent(el) {
  10680. return 'content' in el /** Microsoft/TypeScript#21517 */ && isTemplateElement(el)
  10681. ? el.content
  10682. : null;
  10683. }
  10684. function isTemplateElement(el) {
  10685. return el.nodeType === Node.ELEMENT_NODE && el.nodeName === 'TEMPLATE';
  10686. }
  10687. /**
  10688. * A SecurityContext marks a location that has dangerous security implications, e.g. a DOM property
  10689. * like `innerHTML` that could cause Cross Site Scripting (XSS) security bugs when improperly
  10690. * handled.
  10691. *
  10692. * See DomSanitizer for more details on security in Angular applications.
  10693. *
  10694. * @publicApi
  10695. */
  10696. var SecurityContext;
  10697. (function (SecurityContext) {
  10698. SecurityContext[SecurityContext["NONE"] = 0] = "NONE";
  10699. SecurityContext[SecurityContext["HTML"] = 1] = "HTML";
  10700. SecurityContext[SecurityContext["STYLE"] = 2] = "STYLE";
  10701. SecurityContext[SecurityContext["SCRIPT"] = 3] = "SCRIPT";
  10702. SecurityContext[SecurityContext["URL"] = 4] = "URL";
  10703. SecurityContext[SecurityContext["RESOURCE_URL"] = 5] = "RESOURCE_URL";
  10704. })(SecurityContext || (SecurityContext = {}));
  10705. /**
  10706. * An `html` sanitizer which converts untrusted `html` **string** into trusted string by removing
  10707. * dangerous content.
  10708. *
  10709. * This method parses the `html` and locates potentially dangerous content (such as urls and
  10710. * javascript) and removes it.
  10711. *
  10712. * It is possible to mark a string as trusted by calling {@link bypassSanitizationTrustHtml}.
  10713. *
  10714. * @param unsafeHtml untrusted `html`, typically from the user.
  10715. * @returns `html` string which is safe to display to user, because all of the dangerous javascript
  10716. * and urls have been removed.
  10717. *
  10718. * @codeGenApi
  10719. */
  10720. function ɵɵsanitizeHtml(unsafeHtml) {
  10721. const sanitizer = getSanitizer();
  10722. if (sanitizer) {
  10723. return trustedHTMLFromStringBypass(sanitizer.sanitize(SecurityContext.HTML, unsafeHtml) || '');
  10724. }
  10725. if (allowSanitizationBypassAndThrow(unsafeHtml, "HTML" /* BypassType.Html */)) {
  10726. return trustedHTMLFromStringBypass(unwrapSafeValue(unsafeHtml));
  10727. }
  10728. return _sanitizeHtml(getDocument(), renderStringify(unsafeHtml));
  10729. }
  10730. /**
  10731. * A `style` sanitizer which converts untrusted `style` **string** into trusted string by removing
  10732. * dangerous content.
  10733. *
  10734. * It is possible to mark a string as trusted by calling {@link bypassSanitizationTrustStyle}.
  10735. *
  10736. * @param unsafeStyle untrusted `style`, typically from the user.
  10737. * @returns `style` string which is safe to bind to the `style` properties.
  10738. *
  10739. * @codeGenApi
  10740. */
  10741. function ɵɵsanitizeStyle(unsafeStyle) {
  10742. const sanitizer = getSanitizer();
  10743. if (sanitizer) {
  10744. return sanitizer.sanitize(SecurityContext.STYLE, unsafeStyle) || '';
  10745. }
  10746. if (allowSanitizationBypassAndThrow(unsafeStyle, "Style" /* BypassType.Style */)) {
  10747. return unwrapSafeValue(unsafeStyle);
  10748. }
  10749. return renderStringify(unsafeStyle);
  10750. }
  10751. /**
  10752. * A `url` sanitizer which converts untrusted `url` **string** into trusted string by removing
  10753. * dangerous
  10754. * content.
  10755. *
  10756. * This method parses the `url` and locates potentially dangerous content (such as javascript) and
  10757. * removes it.
  10758. *
  10759. * It is possible to mark a string as trusted by calling {@link bypassSanitizationTrustUrl}.
  10760. *
  10761. * @param unsafeUrl untrusted `url`, typically from the user.
  10762. * @returns `url` string which is safe to bind to the `src` properties such as `<img src>`, because
  10763. * all of the dangerous javascript has been removed.
  10764. *
  10765. * @codeGenApi
  10766. */
  10767. function ɵɵsanitizeUrl(unsafeUrl) {
  10768. const sanitizer = getSanitizer();
  10769. if (sanitizer) {
  10770. return sanitizer.sanitize(SecurityContext.URL, unsafeUrl) || '';
  10771. }
  10772. if (allowSanitizationBypassAndThrow(unsafeUrl, "URL" /* BypassType.Url */)) {
  10773. return unwrapSafeValue(unsafeUrl);
  10774. }
  10775. return _sanitizeUrl(renderStringify(unsafeUrl));
  10776. }
  10777. /**
  10778. * A `url` sanitizer which only lets trusted `url`s through.
  10779. *
  10780. * This passes only `url`s marked trusted by calling {@link bypassSanitizationTrustResourceUrl}.
  10781. *
  10782. * @param unsafeResourceUrl untrusted `url`, typically from the user.
  10783. * @returns `url` string which is safe to bind to the `src` properties such as `<img src>`, because
  10784. * only trusted `url`s have been allowed to pass.
  10785. *
  10786. * @codeGenApi
  10787. */
  10788. function ɵɵsanitizeResourceUrl(unsafeResourceUrl) {
  10789. const sanitizer = getSanitizer();
  10790. if (sanitizer) {
  10791. return trustedScriptURLFromStringBypass(sanitizer.sanitize(SecurityContext.RESOURCE_URL, unsafeResourceUrl) || '');
  10792. }
  10793. if (allowSanitizationBypassAndThrow(unsafeResourceUrl, "ResourceURL" /* BypassType.ResourceUrl */)) {
  10794. return trustedScriptURLFromStringBypass(unwrapSafeValue(unsafeResourceUrl));
  10795. }
  10796. throw new RuntimeError(904 /* RuntimeErrorCode.UNSAFE_VALUE_IN_RESOURCE_URL */, ngDevMode && `unsafe value used in a resource URL context (see ${XSS_SECURITY_URL})`);
  10797. }
  10798. /**
  10799. * A `script` sanitizer which only lets trusted javascript through.
  10800. *
  10801. * This passes only `script`s marked trusted by calling {@link
  10802. * bypassSanitizationTrustScript}.
  10803. *
  10804. * @param unsafeScript untrusted `script`, typically from the user.
  10805. * @returns `url` string which is safe to bind to the `<script>` element such as `<img src>`,
  10806. * because only trusted `scripts` have been allowed to pass.
  10807. *
  10808. * @codeGenApi
  10809. */
  10810. function ɵɵsanitizeScript(unsafeScript) {
  10811. const sanitizer = getSanitizer();
  10812. if (sanitizer) {
  10813. return trustedScriptFromStringBypass(sanitizer.sanitize(SecurityContext.SCRIPT, unsafeScript) || '');
  10814. }
  10815. if (allowSanitizationBypassAndThrow(unsafeScript, "Script" /* BypassType.Script */)) {
  10816. return trustedScriptFromStringBypass(unwrapSafeValue(unsafeScript));
  10817. }
  10818. throw new RuntimeError(905 /* RuntimeErrorCode.UNSAFE_VALUE_IN_SCRIPT */, ngDevMode && 'unsafe value used in a script context');
  10819. }
  10820. /**
  10821. * A template tag function for promoting the associated constant literal to a
  10822. * TrustedHTML. Interpolation is explicitly not allowed.
  10823. *
  10824. * @param html constant template literal containing trusted HTML.
  10825. * @returns TrustedHTML wrapping `html`.
  10826. *
  10827. * @security This is a security-sensitive function and should only be used to
  10828. * convert constant values of attributes and properties found in
  10829. * application-provided Angular templates to TrustedHTML.
  10830. *
  10831. * @codeGenApi
  10832. */
  10833. function ɵɵtrustConstantHtml(html) {
  10834. // The following runtime check ensures that the function was called as a
  10835. // template tag (e.g. ɵɵtrustConstantHtml`content`), without any interpolation
  10836. // (e.g. not ɵɵtrustConstantHtml`content ${variable}`). A TemplateStringsArray
  10837. // is an array with a `raw` property that is also an array. The associated
  10838. // template literal has no interpolation if and only if the length of the
  10839. // TemplateStringsArray is 1.
  10840. if (ngDevMode && (!Array.isArray(html) || !Array.isArray(html.raw) || html.length !== 1)) {
  10841. throw new Error(`Unexpected interpolation in trusted HTML constant: ${html.join('?')}`);
  10842. }
  10843. return trustedHTMLFromString(html[0]);
  10844. }
  10845. /**
  10846. * A template tag function for promoting the associated constant literal to a
  10847. * TrustedScriptURL. Interpolation is explicitly not allowed.
  10848. *
  10849. * @param url constant template literal containing a trusted script URL.
  10850. * @returns TrustedScriptURL wrapping `url`.
  10851. *
  10852. * @security This is a security-sensitive function and should only be used to
  10853. * convert constant values of attributes and properties found in
  10854. * application-provided Angular templates to TrustedScriptURL.
  10855. *
  10856. * @codeGenApi
  10857. */
  10858. function ɵɵtrustConstantResourceUrl(url) {
  10859. // The following runtime check ensures that the function was called as a
  10860. // template tag (e.g. ɵɵtrustConstantResourceUrl`content`), without any
  10861. // interpolation (e.g. not ɵɵtrustConstantResourceUrl`content ${variable}`). A
  10862. // TemplateStringsArray is an array with a `raw` property that is also an
  10863. // array. The associated template literal has no interpolation if and only if
  10864. // the length of the TemplateStringsArray is 1.
  10865. if (ngDevMode && (!Array.isArray(url) || !Array.isArray(url.raw) || url.length !== 1)) {
  10866. throw new Error(`Unexpected interpolation in trusted URL constant: ${url.join('?')}`);
  10867. }
  10868. return trustedScriptURLFromString(url[0]);
  10869. }
  10870. /**
  10871. * Detects which sanitizer to use for URL property, based on tag name and prop name.
  10872. *
  10873. * The rules are based on the RESOURCE_URL context config from
  10874. * `packages/compiler/src/schema/dom_security_schema.ts`.
  10875. * If tag and prop names don't match Resource URL schema, use URL sanitizer.
  10876. */
  10877. function getUrlSanitizer(tag, prop) {
  10878. if ((prop === 'src' &&
  10879. (tag === 'embed' ||
  10880. tag === 'frame' ||
  10881. tag === 'iframe' ||
  10882. tag === 'media' ||
  10883. tag === 'script')) ||
  10884. (prop === 'href' && (tag === 'base' || tag === 'link'))) {
  10885. return ɵɵsanitizeResourceUrl;
  10886. }
  10887. return ɵɵsanitizeUrl;
  10888. }
  10889. /**
  10890. * Sanitizes URL, selecting sanitizer function based on tag and property names.
  10891. *
  10892. * This function is used in case we can't define security context at compile time, when only prop
  10893. * name is available. This happens when we generate host bindings for Directives/Components. The
  10894. * host element is unknown at compile time, so we defer calculation of specific sanitizer to
  10895. * runtime.
  10896. *
  10897. * @param unsafeUrl untrusted `url`, typically from the user.
  10898. * @param tag target element tag name.
  10899. * @param prop name of the property that contains the value.
  10900. * @returns `url` string which is safe to bind.
  10901. *
  10902. * @codeGenApi
  10903. */
  10904. function ɵɵsanitizeUrlOrResourceUrl(unsafeUrl, tag, prop) {
  10905. return getUrlSanitizer(tag, prop)(unsafeUrl);
  10906. }
  10907. function validateAgainstEventProperties(name) {
  10908. if (name.toLowerCase().startsWith('on')) {
  10909. const errorMessage = `Binding to event property '${name}' is disallowed for security reasons, ` +
  10910. `please use (${name.slice(2)})=...` +
  10911. `\nIf '${name}' is a directive input, make sure the directive is imported by the` +
  10912. ` current module.`;
  10913. throw new RuntimeError(306 /* RuntimeErrorCode.INVALID_EVENT_BINDING */, errorMessage);
  10914. }
  10915. }
  10916. function validateAgainstEventAttributes(name) {
  10917. if (name.toLowerCase().startsWith('on')) {
  10918. const errorMessage = `Binding to event attribute '${name}' is disallowed for security reasons, ` +
  10919. `please use (${name.slice(2)})=...`;
  10920. throw new RuntimeError(306 /* RuntimeErrorCode.INVALID_EVENT_BINDING */, errorMessage);
  10921. }
  10922. }
  10923. function getSanitizer() {
  10924. const lView = getLView();
  10925. return lView && lView[ENVIRONMENT].sanitizer;
  10926. }
  10927. /**
  10928. * Disallowed strings in the comment.
  10929. *
  10930. * see: https://html.spec.whatwg.org/multipage/syntax.html#comments
  10931. */
  10932. const COMMENT_DISALLOWED = /^>|^->|<!--|-->|--!>|<!-$/g;
  10933. /**
  10934. * Delimiter in the disallowed strings which needs to be wrapped with zero with character.
  10935. */
  10936. const COMMENT_DELIMITER = /(<|>)/g;
  10937. const COMMENT_DELIMITER_ESCAPED = '\u200B$1\u200B';
  10938. /**
  10939. * Escape the content of comment strings so that it can be safely inserted into a comment node.
  10940. *
  10941. * The issue is that HTML does not specify any way to escape comment end text inside the comment.
  10942. * Consider: `<!-- The way you close a comment is with ">", and "->" at the beginning or by "-->" or
  10943. * "--!>" at the end. -->`. Above the `"-->"` is meant to be text not an end to the comment. This
  10944. * can be created programmatically through DOM APIs. (`<!--` are also disallowed.)
  10945. *
  10946. * see: https://html.spec.whatwg.org/multipage/syntax.html#comments
  10947. *
  10948. * ```ts
  10949. * div.innerHTML = div.innerHTML
  10950. * ```
  10951. *
  10952. * One would expect that the above code would be safe to do, but it turns out that because comment
  10953. * text is not escaped, the comment may contain text which will prematurely close the comment
  10954. * opening up the application for XSS attack. (In SSR we programmatically create comment nodes which
  10955. * may contain such text and expect them to be safe.)
  10956. *
  10957. * This function escapes the comment text by looking for comment delimiters (`<` and `>`) and
  10958. * surrounding them with `_>_` where the `_` is a zero width space `\u200B`. The result is that if a
  10959. * comment contains any of the comment start/end delimiters (such as `<!--`, `-->` or `--!>`) the
  10960. * text it will render normally but it will not cause the HTML parser to close/open the comment.
  10961. *
  10962. * @param value text to make safe for comment node by escaping the comment open/close character
  10963. * sequence.
  10964. */
  10965. function escapeCommentText(value) {
  10966. return value.replace(COMMENT_DISALLOWED, (text) => text.replace(COMMENT_DELIMITER, COMMENT_DELIMITER_ESCAPED));
  10967. }
  10968. function normalizeDebugBindingName(name) {
  10969. // Attribute names with `$` (eg `x-y$`) are valid per spec, but unsupported by some browsers
  10970. name = camelCaseToDashCase(name.replace(/[$@]/g, '_'));
  10971. return `ng-reflect-${name}`;
  10972. }
  10973. const CAMEL_CASE_REGEXP = /([A-Z])/g;
  10974. function camelCaseToDashCase(input) {
  10975. return input.replace(CAMEL_CASE_REGEXP, (...m) => '-' + m[1].toLowerCase());
  10976. }
  10977. function normalizeDebugBindingValue(value) {
  10978. try {
  10979. // Limit the size of the value as otherwise the DOM just gets polluted.
  10980. return value != null ? value.toString().slice(0, 30) : value;
  10981. }
  10982. catch (e) {
  10983. return '[ERROR] Exception while trying to serialize the value';
  10984. }
  10985. }
  10986. /**
  10987. * Defines a schema that allows an NgModule to contain the following:
  10988. * - Non-Angular elements named with dash case (`-`).
  10989. * - Element properties named with dash case (`-`).
  10990. * Dash case is the naming convention for custom elements.
  10991. *
  10992. * @publicApi
  10993. */
  10994. const CUSTOM_ELEMENTS_SCHEMA = {
  10995. name: 'custom-elements',
  10996. };
  10997. /**
  10998. * Defines a schema that allows any property on any element.
  10999. *
  11000. * This schema allows you to ignore the errors related to any unknown elements or properties in a
  11001. * template. The usage of this schema is generally discouraged because it prevents useful validation
  11002. * and may hide real errors in your template. Consider using the `CUSTOM_ELEMENTS_SCHEMA` instead.
  11003. *
  11004. * @publicApi
  11005. */
  11006. const NO_ERRORS_SCHEMA = {
  11007. name: 'no-errors-schema',
  11008. };
  11009. let shouldThrowErrorOnUnknownElement = false;
  11010. /**
  11011. * Sets a strict mode for JIT-compiled components to throw an error on unknown elements,
  11012. * instead of just logging the error.
  11013. * (for AOT-compiled ones this check happens at build time).
  11014. */
  11015. function ɵsetUnknownElementStrictMode(shouldThrow) {
  11016. shouldThrowErrorOnUnknownElement = shouldThrow;
  11017. }
  11018. /**
  11019. * Gets the current value of the strict mode.
  11020. */
  11021. function ɵgetUnknownElementStrictMode() {
  11022. return shouldThrowErrorOnUnknownElement;
  11023. }
  11024. let shouldThrowErrorOnUnknownProperty = false;
  11025. /**
  11026. * Sets a strict mode for JIT-compiled components to throw an error on unknown properties,
  11027. * instead of just logging the error.
  11028. * (for AOT-compiled ones this check happens at build time).
  11029. */
  11030. function ɵsetUnknownPropertyStrictMode(shouldThrow) {
  11031. shouldThrowErrorOnUnknownProperty = shouldThrow;
  11032. }
  11033. /**
  11034. * Gets the current value of the strict mode.
  11035. */
  11036. function ɵgetUnknownPropertyStrictMode() {
  11037. return shouldThrowErrorOnUnknownProperty;
  11038. }
  11039. /**
  11040. * Validates that the element is known at runtime and produces
  11041. * an error if it's not the case.
  11042. * This check is relevant for JIT-compiled components (for AOT-compiled
  11043. * ones this check happens at build time).
  11044. *
  11045. * The element is considered known if either:
  11046. * - it's a known HTML element
  11047. * - it's a known custom element
  11048. * - the element matches any directive
  11049. * - the element is allowed by one of the schemas
  11050. *
  11051. * @param element Element to validate
  11052. * @param lView An `LView` that represents a current component that is being rendered
  11053. * @param tagName Name of the tag to check
  11054. * @param schemas Array of schemas
  11055. * @param hasDirectives Boolean indicating that the element matches any directive
  11056. */
  11057. function validateElementIsKnown(element, lView, tagName, schemas, hasDirectives) {
  11058. // If `schemas` is set to `null`, that's an indication that this Component was compiled in AOT
  11059. // mode where this check happens at compile time. In JIT mode, `schemas` is always present and
  11060. // defined as an array (as an empty array in case `schemas` field is not defined) and we should
  11061. // execute the check below.
  11062. if (schemas === null)
  11063. return;
  11064. // If the element matches any directive, it's considered as valid.
  11065. if (!hasDirectives && tagName !== null) {
  11066. // The element is unknown if it's an instance of HTMLUnknownElement, or it isn't registered
  11067. // as a custom element. Note that unknown elements with a dash in their name won't be instances
  11068. // of HTMLUnknownElement in browsers that support web components.
  11069. const isUnknown =
  11070. // Note that we can't check for `typeof HTMLUnknownElement === 'function'` because
  11071. // Domino doesn't expose HTMLUnknownElement globally.
  11072. (typeof HTMLUnknownElement !== 'undefined' &&
  11073. HTMLUnknownElement &&
  11074. element instanceof HTMLUnknownElement) ||
  11075. (typeof customElements !== 'undefined' &&
  11076. tagName.indexOf('-') > -1 &&
  11077. !customElements.get(tagName));
  11078. if (isUnknown && !matchingSchemas(schemas, tagName)) {
  11079. const isHostStandalone = isHostComponentStandalone(lView);
  11080. const templateLocation = getTemplateLocationDetails(lView);
  11081. const schemas = `'${isHostStandalone ? '@Component' : '@NgModule'}.schemas'`;
  11082. let message = `'${tagName}' is not a known element${templateLocation}:\n`;
  11083. message += `1. If '${tagName}' is an Angular component, then verify that it is ${isHostStandalone
  11084. ? "included in the '@Component.imports' of this component"
  11085. : 'a part of an @NgModule where this component is declared'}.\n`;
  11086. if (tagName && tagName.indexOf('-') > -1) {
  11087. message += `2. If '${tagName}' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the ${schemas} of this component to suppress this message.`;
  11088. }
  11089. else {
  11090. message += `2. To allow any element add 'NO_ERRORS_SCHEMA' to the ${schemas} of this component.`;
  11091. }
  11092. if (shouldThrowErrorOnUnknownElement) {
  11093. throw new RuntimeError(304 /* RuntimeErrorCode.UNKNOWN_ELEMENT */, message);
  11094. }
  11095. else {
  11096. console.error(formatRuntimeError(304 /* RuntimeErrorCode.UNKNOWN_ELEMENT */, message));
  11097. }
  11098. }
  11099. }
  11100. }
  11101. /**
  11102. * Validates that the property of the element is known at runtime and returns
  11103. * false if it's not the case.
  11104. * This check is relevant for JIT-compiled components (for AOT-compiled
  11105. * ones this check happens at build time).
  11106. *
  11107. * The property is considered known if either:
  11108. * - it's a known property of the element
  11109. * - the element is allowed by one of the schemas
  11110. * - the property is used for animations
  11111. *
  11112. * @param element Element to validate
  11113. * @param propName Name of the property to check
  11114. * @param tagName Name of the tag hosting the property
  11115. * @param schemas Array of schemas
  11116. */
  11117. function isPropertyValid(element, propName, tagName, schemas) {
  11118. // If `schemas` is set to `null`, that's an indication that this Component was compiled in AOT
  11119. // mode where this check happens at compile time. In JIT mode, `schemas` is always present and
  11120. // defined as an array (as an empty array in case `schemas` field is not defined) and we should
  11121. // execute the check below.
  11122. if (schemas === null)
  11123. return true;
  11124. // The property is considered valid if the element matches the schema, it exists on the element,
  11125. // or it is synthetic.
  11126. if (matchingSchemas(schemas, tagName) || propName in element || isAnimationProp(propName)) {
  11127. return true;
  11128. }
  11129. // Note: `typeof Node` returns 'function' in most browsers, but is undefined with domino.
  11130. return typeof Node === 'undefined' || Node === null || !(element instanceof Node);
  11131. }
  11132. /**
  11133. * Logs or throws an error that a property is not supported on an element.
  11134. *
  11135. * @param propName Name of the invalid property
  11136. * @param tagName Name of the tag hosting the property
  11137. * @param nodeType Type of the node hosting the property
  11138. * @param lView An `LView` that represents a current component
  11139. */
  11140. function handleUnknownPropertyError(propName, tagName, nodeType, lView) {
  11141. // Special-case a situation when a structural directive is applied to
  11142. // an `<ng-template>` element, for example: `<ng-template *ngIf="true">`.
  11143. // In this case the compiler generates the `ɵɵtemplate` instruction with
  11144. // the `null` as the tagName. The directive matching logic at runtime relies
  11145. // on this effect (see `isInlineTemplate`), thus using the 'ng-template' as
  11146. // a default value of the `tNode.value` is not feasible at this moment.
  11147. if (!tagName && nodeType === 4 /* TNodeType.Container */) {
  11148. tagName = 'ng-template';
  11149. }
  11150. const isHostStandalone = isHostComponentStandalone(lView);
  11151. const templateLocation = getTemplateLocationDetails(lView);
  11152. let message = `Can't bind to '${propName}' since it isn't a known property of '${tagName}'${templateLocation}.`;
  11153. const schemas = `'${isHostStandalone ? '@Component' : '@NgModule'}.schemas'`;
  11154. const importLocation = isHostStandalone
  11155. ? "included in the '@Component.imports' of this component"
  11156. : 'a part of an @NgModule where this component is declared';
  11157. if (KNOWN_CONTROL_FLOW_DIRECTIVES.has(propName)) {
  11158. // Most likely this is a control flow directive (such as `*ngIf`) used in
  11159. // a template, but the directive or the `CommonModule` is not imported.
  11160. const correspondingImport = KNOWN_CONTROL_FLOW_DIRECTIVES.get(propName);
  11161. message +=
  11162. `\nIf the '${propName}' is an Angular control flow directive, ` +
  11163. `please make sure that either the '${correspondingImport}' directive or the 'CommonModule' is ${importLocation}.`;
  11164. }
  11165. else {
  11166. // May be an Angular component, which is not imported/declared?
  11167. message +=
  11168. `\n1. If '${tagName}' is an Angular component and it has the ` +
  11169. `'${propName}' input, then verify that it is ${importLocation}.`;
  11170. // May be a Web Component?
  11171. if (tagName && tagName.indexOf('-') > -1) {
  11172. message +=
  11173. `\n2. If '${tagName}' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' ` +
  11174. `to the ${schemas} of this component to suppress this message.`;
  11175. message +=
  11176. `\n3. To allow any property add 'NO_ERRORS_SCHEMA' to ` +
  11177. `the ${schemas} of this component.`;
  11178. }
  11179. else {
  11180. // If it's expected, the error can be suppressed by the `NO_ERRORS_SCHEMA` schema.
  11181. message +=
  11182. `\n2. To allow any property add 'NO_ERRORS_SCHEMA' to ` +
  11183. `the ${schemas} of this component.`;
  11184. }
  11185. }
  11186. reportUnknownPropertyError(message);
  11187. }
  11188. function reportUnknownPropertyError(message) {
  11189. if (shouldThrowErrorOnUnknownProperty) {
  11190. throw new RuntimeError(303 /* RuntimeErrorCode.UNKNOWN_BINDING */, message);
  11191. }
  11192. else {
  11193. console.error(formatRuntimeError(303 /* RuntimeErrorCode.UNKNOWN_BINDING */, message));
  11194. }
  11195. }
  11196. /**
  11197. * WARNING: this is a **dev-mode only** function (thus should always be guarded by the `ngDevMode`)
  11198. * and must **not** be used in production bundles. The function makes megamorphic reads, which might
  11199. * be too slow for production mode and also it relies on the constructor function being available.
  11200. *
  11201. * Gets a reference to the host component def (where a current component is declared).
  11202. *
  11203. * @param lView An `LView` that represents a current component that is being rendered.
  11204. */
  11205. function getDeclarationComponentDef(lView) {
  11206. !ngDevMode && throwError('Must never be called in production mode');
  11207. const declarationLView = lView[DECLARATION_COMPONENT_VIEW];
  11208. const context = declarationLView[CONTEXT];
  11209. // Unable to obtain a context.
  11210. if (!context)
  11211. return null;
  11212. return context.constructor ? getComponentDef(context.constructor) : null;
  11213. }
  11214. /**
  11215. * WARNING: this is a **dev-mode only** function (thus should always be guarded by the `ngDevMode`)
  11216. * and must **not** be used in production bundles. The function makes megamorphic reads, which might
  11217. * be too slow for production mode.
  11218. *
  11219. * Checks if the current component is declared inside of a standalone component template.
  11220. *
  11221. * @param lView An `LView` that represents a current component that is being rendered.
  11222. */
  11223. function isHostComponentStandalone(lView) {
  11224. !ngDevMode && throwError('Must never be called in production mode');
  11225. const componentDef = getDeclarationComponentDef(lView);
  11226. // Treat host component as non-standalone if we can't obtain the def.
  11227. return !!componentDef?.standalone;
  11228. }
  11229. /**
  11230. * WARNING: this is a **dev-mode only** function (thus should always be guarded by the `ngDevMode`)
  11231. * and must **not** be used in production bundles. The function makes megamorphic reads, which might
  11232. * be too slow for production mode.
  11233. *
  11234. * Constructs a string describing the location of the host component template. The function is used
  11235. * in dev mode to produce error messages.
  11236. *
  11237. * @param lView An `LView` that represents a current component that is being rendered.
  11238. */
  11239. function getTemplateLocationDetails(lView) {
  11240. !ngDevMode && throwError('Must never be called in production mode');
  11241. const hostComponentDef = getDeclarationComponentDef(lView);
  11242. const componentClassName = hostComponentDef?.type?.name;
  11243. return componentClassName ? ` (used in the '${componentClassName}' component template)` : '';
  11244. }
  11245. /**
  11246. * The set of known control flow directives and their corresponding imports.
  11247. * We use this set to produce a more precises error message with a note
  11248. * that the `CommonModule` should also be included.
  11249. */
  11250. const KNOWN_CONTROL_FLOW_DIRECTIVES = new Map([
  11251. ['ngIf', 'NgIf'],
  11252. ['ngFor', 'NgFor'],
  11253. ['ngSwitchCase', 'NgSwitchCase'],
  11254. ['ngSwitchDefault', 'NgSwitchDefault'],
  11255. ]);
  11256. /**
  11257. * Returns true if the tag name is allowed by specified schemas.
  11258. * @param schemas Array of schemas
  11259. * @param tagName Name of the tag
  11260. */
  11261. function matchingSchemas(schemas, tagName) {
  11262. if (schemas !== null) {
  11263. for (let i = 0; i < schemas.length; i++) {
  11264. const schema = schemas[i];
  11265. if (schema === NO_ERRORS_SCHEMA ||
  11266. (schema === CUSTOM_ELEMENTS_SCHEMA && tagName && tagName.indexOf('-') > -1)) {
  11267. return true;
  11268. }
  11269. }
  11270. }
  11271. return false;
  11272. }
  11273. /**
  11274. *
  11275. * @codeGenApi
  11276. */
  11277. function ɵɵresolveWindow(element) {
  11278. return element.ownerDocument.defaultView;
  11279. }
  11280. /**
  11281. *
  11282. * @codeGenApi
  11283. */
  11284. function ɵɵresolveDocument(element) {
  11285. return element.ownerDocument;
  11286. }
  11287. /**
  11288. *
  11289. * @codeGenApi
  11290. */
  11291. function ɵɵresolveBody(element) {
  11292. return element.ownerDocument.body;
  11293. }
  11294. /**
  11295. * The special delimiter we use to separate property names, prefixes, and suffixes
  11296. * in property binding metadata. See storeBindingMetadata().
  11297. *
  11298. * We intentionally use the Unicode "REPLACEMENT CHARACTER" (U+FFFD) as a delimiter
  11299. * because it is a very uncommon character that is unlikely to be part of a user's
  11300. * property names or interpolation strings. If it is in fact used in a property
  11301. * binding, DebugElement.properties will not return the correct value for that
  11302. * binding. However, there should be no runtime effect for real applications.
  11303. *
  11304. * This character is typically rendered as a question mark inside of a diamond.
  11305. * See https://en.wikipedia.org/wiki/Specials_(Unicode_block)
  11306. *
  11307. */
  11308. const INTERPOLATION_DELIMITER = `�`;
  11309. /**
  11310. * Unwrap a value which might be behind a closure (for forward declaration reasons).
  11311. */
  11312. function maybeUnwrapFn(value) {
  11313. if (value instanceof Function) {
  11314. return value();
  11315. }
  11316. else {
  11317. return value;
  11318. }
  11319. }
  11320. /**
  11321. * The max length of the string representation of a value in an error message
  11322. */
  11323. const VALUE_STRING_LENGTH_LIMIT = 200;
  11324. /** Verifies that a given type is a Standalone Component. */
  11325. function assertStandaloneComponentType(type) {
  11326. assertComponentDef(type);
  11327. const componentDef = getComponentDef(type);
  11328. if (!componentDef.standalone) {
  11329. throw new RuntimeError(907 /* RuntimeErrorCode.TYPE_IS_NOT_STANDALONE */, `The ${stringifyForError(type)} component is not marked as standalone, ` +
  11330. `but Angular expects to have a standalone component here. ` +
  11331. `Please make sure the ${stringifyForError(type)} component has ` +
  11332. `the \`standalone: true\` flag in the decorator.`);
  11333. }
  11334. }
  11335. /** Verifies whether a given type is a component */
  11336. function assertComponentDef(type) {
  11337. if (!getComponentDef(type)) {
  11338. throw new RuntimeError(906 /* RuntimeErrorCode.MISSING_GENERATED_DEF */, `The ${stringifyForError(type)} is not an Angular component, ` +
  11339. `make sure it has the \`@Component\` decorator.`);
  11340. }
  11341. }
  11342. /** Called when there are multiple component selectors that match a given node */
  11343. function throwMultipleComponentError(tNode, first, second) {
  11344. throw new RuntimeError(-300 /* RuntimeErrorCode.MULTIPLE_COMPONENTS_MATCH */, `Multiple components match node with tagname ${tNode.value}: ` +
  11345. `${stringifyForError(first)} and ` +
  11346. `${stringifyForError(second)}`);
  11347. }
  11348. /** Throws an ExpressionChangedAfterChecked error if checkNoChanges mode is on. */
  11349. function throwErrorIfNoChangesMode(creationMode, oldValue, currValue, propName, lView) {
  11350. const hostComponentDef = getDeclarationComponentDef(lView);
  11351. const componentClassName = hostComponentDef?.type?.name;
  11352. const field = propName ? ` for '${propName}'` : '';
  11353. let msg = `ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value${field}: '${formatValue(oldValue)}'. Current value: '${formatValue(currValue)}'.${componentClassName ? ` Expression location: ${componentClassName} component` : ''}`;
  11354. if (creationMode) {
  11355. msg +=
  11356. ` It seems like the view has been created after its parent and its children have been dirty checked.` +
  11357. ` Has it been created in a change detection hook?`;
  11358. }
  11359. throw new RuntimeError(-100 /* RuntimeErrorCode.EXPRESSION_CHANGED_AFTER_CHECKED */, msg);
  11360. }
  11361. function formatValue(value) {
  11362. let strValue = String(value);
  11363. // JSON.stringify will throw on circular references
  11364. try {
  11365. if (Array.isArray(value) || strValue === '[object Object]') {
  11366. strValue = JSON.stringify(value);
  11367. }
  11368. }
  11369. catch (error) { }
  11370. return strValue.length > VALUE_STRING_LENGTH_LIMIT
  11371. ? strValue.substring(0, VALUE_STRING_LENGTH_LIMIT) + '…'
  11372. : strValue;
  11373. }
  11374. function constructDetailsForInterpolation(lView, rootIndex, expressionIndex, meta, changedValue) {
  11375. const [propName, prefix, ...chunks] = meta.split(INTERPOLATION_DELIMITER);
  11376. let oldValue = prefix, newValue = prefix;
  11377. for (let i = 0; i < chunks.length; i++) {
  11378. const slotIdx = rootIndex + i;
  11379. oldValue += `${lView[slotIdx]}${chunks[i]}`;
  11380. newValue += `${slotIdx === expressionIndex ? changedValue : lView[slotIdx]}${chunks[i]}`;
  11381. }
  11382. return { propName, oldValue, newValue };
  11383. }
  11384. /**
  11385. * Constructs an object that contains details for the ExpressionChangedAfterItHasBeenCheckedError:
  11386. * - property name (for property bindings or interpolations)
  11387. * - old and new values, enriched using information from metadata
  11388. *
  11389. * More information on the metadata storage format can be found in `storePropertyBindingMetadata`
  11390. * function description.
  11391. */
  11392. function getExpressionChangedErrorDetails(lView, bindingIndex, oldValue, newValue) {
  11393. const tData = lView[TVIEW].data;
  11394. const metadata = tData[bindingIndex];
  11395. if (typeof metadata === 'string') {
  11396. // metadata for property interpolation
  11397. if (metadata.indexOf(INTERPOLATION_DELIMITER) > -1) {
  11398. return constructDetailsForInterpolation(lView, bindingIndex, bindingIndex, metadata, newValue);
  11399. }
  11400. // metadata for property binding
  11401. return { propName: metadata, oldValue, newValue };
  11402. }
  11403. // metadata is not available for this expression, check if this expression is a part of the
  11404. // property interpolation by going from the current binding index left and look for a string that
  11405. // contains INTERPOLATION_DELIMITER, the layout in tView.data for this case will look like this:
  11406. // [..., 'id�Prefix � and � suffix', null, null, null, ...]
  11407. if (metadata === null) {
  11408. let idx = bindingIndex - 1;
  11409. while (typeof tData[idx] !== 'string' && tData[idx + 1] === null) {
  11410. idx--;
  11411. }
  11412. const meta = tData[idx];
  11413. if (typeof meta === 'string') {
  11414. const matches = meta.match(new RegExp(INTERPOLATION_DELIMITER, 'g'));
  11415. // first interpolation delimiter separates property name from interpolation parts (in case of
  11416. // property interpolations), so we subtract one from total number of found delimiters
  11417. if (matches && matches.length - 1 > bindingIndex - idx) {
  11418. return constructDetailsForInterpolation(lView, idx, bindingIndex, meta, newValue);
  11419. }
  11420. }
  11421. }
  11422. return { propName: undefined, oldValue, newValue };
  11423. }
  11424. /**
  11425. * Returns an index of `classToSearch` in `className` taking token boundaries into account.
  11426. *
  11427. * `classIndexOf('AB A', 'A', 0)` will be 3 (not 0 since `AB!==A`)
  11428. *
  11429. * @param className A string containing classes (whitespace separated)
  11430. * @param classToSearch A class name to locate
  11431. * @param startingIndex Starting location of search
  11432. * @returns an index of the located class (or -1 if not found)
  11433. */
  11434. function classIndexOf(className, classToSearch, startingIndex) {
  11435. ngDevMode && assertNotEqual(classToSearch, '', 'can not look for "" string.');
  11436. let end = className.length;
  11437. while (true) {
  11438. const foundIndex = className.indexOf(classToSearch, startingIndex);
  11439. if (foundIndex === -1)
  11440. return foundIndex;
  11441. if (foundIndex === 0 || className.charCodeAt(foundIndex - 1) <= 32 /* CharCode.SPACE */) {
  11442. // Ensure that it has leading whitespace
  11443. const length = classToSearch.length;
  11444. if (foundIndex + length === end ||
  11445. className.charCodeAt(foundIndex + length) <= 32 /* CharCode.SPACE */) {
  11446. // Ensure that it has trailing whitespace
  11447. return foundIndex;
  11448. }
  11449. }
  11450. // False positive, keep searching from where we left off.
  11451. startingIndex = foundIndex + 1;
  11452. }
  11453. }
  11454. const NG_TEMPLATE_SELECTOR = 'ng-template';
  11455. /**
  11456. * Search the `TAttributes` to see if it contains `cssClassToMatch` (case insensitive)
  11457. *
  11458. * @param tNode static data of the node to match
  11459. * @param attrs `TAttributes` to search through.
  11460. * @param cssClassToMatch class to match (lowercase)
  11461. * @param isProjectionMode Whether or not class matching should look into the attribute `class` in
  11462. * addition to the `AttributeMarker.Classes`.
  11463. */
  11464. function isCssClassMatching(tNode, attrs, cssClassToMatch, isProjectionMode) {
  11465. ngDevMode &&
  11466. assertEqual(cssClassToMatch, cssClassToMatch.toLowerCase(), 'Class name expected to be lowercase.');
  11467. let i = 0;
  11468. if (isProjectionMode) {
  11469. for (; i < attrs.length && typeof attrs[i] === 'string'; i += 2) {
  11470. // Search for an implicit `class` attribute and check if its value matches `cssClassToMatch`.
  11471. if (attrs[i] === 'class' &&
  11472. classIndexOf(attrs[i + 1].toLowerCase(), cssClassToMatch, 0) !== -1) {
  11473. return true;
  11474. }
  11475. }
  11476. }
  11477. else if (isInlineTemplate(tNode)) {
  11478. // Matching directives (i.e. when not matching for projection mode) should not consider the
  11479. // class bindings that are present on inline templates, as those class bindings only target
  11480. // the root node of the template, not the template itself.
  11481. return false;
  11482. }
  11483. // Resume the search for classes after the `Classes` marker.
  11484. i = attrs.indexOf(1 /* AttributeMarker.Classes */, i);
  11485. if (i > -1) {
  11486. // We found the classes section. Start searching for the class.
  11487. let item;
  11488. while (++i < attrs.length && typeof (item = attrs[i]) === 'string') {
  11489. if (item.toLowerCase() === cssClassToMatch) {
  11490. return true;
  11491. }
  11492. }
  11493. }
  11494. return false;
  11495. }
  11496. /**
  11497. * Checks whether the `tNode` represents an inline template (e.g. `*ngFor`).
  11498. *
  11499. * @param tNode current TNode
  11500. */
  11501. function isInlineTemplate(tNode) {
  11502. return tNode.type === 4 /* TNodeType.Container */ && tNode.value !== NG_TEMPLATE_SELECTOR;
  11503. }
  11504. /**
  11505. * Function that checks whether a given tNode matches tag-based selector and has a valid type.
  11506. *
  11507. * Matching can be performed in 2 modes: projection mode (when we project nodes) and regular
  11508. * directive matching mode:
  11509. * - in the "directive matching" mode we do _not_ take TContainer's tagName into account if it is
  11510. * different from NG_TEMPLATE_SELECTOR (value different from NG_TEMPLATE_SELECTOR indicates that a
  11511. * tag name was extracted from * syntax so we would match the same directive twice);
  11512. * - in the "projection" mode, we use a tag name potentially extracted from the * syntax processing
  11513. * (applicable to TNodeType.Container only).
  11514. */
  11515. function hasTagAndTypeMatch(tNode, currentSelector, isProjectionMode) {
  11516. const tagNameToCompare = tNode.type === 4 /* TNodeType.Container */ && !isProjectionMode ? NG_TEMPLATE_SELECTOR : tNode.value;
  11517. return currentSelector === tagNameToCompare;
  11518. }
  11519. /**
  11520. * A utility function to match an Ivy node static data against a simple CSS selector
  11521. *
  11522. * @param tNode static data of the node to match
  11523. * @param selector The selector to try matching against the node.
  11524. * @param isProjectionMode if `true` we are matching for content projection, otherwise we are doing
  11525. * directive matching.
  11526. * @returns true if node matches the selector.
  11527. */
  11528. function isNodeMatchingSelector(tNode, selector, isProjectionMode) {
  11529. ngDevMode && assertDefined(selector[0], 'Selector should have a tag name');
  11530. let mode = 4 /* SelectorFlags.ELEMENT */;
  11531. const nodeAttrs = tNode.attrs;
  11532. // Find the index of first attribute that has no value, only a name.
  11533. const nameOnlyMarkerIdx = nodeAttrs !== null ? getNameOnlyMarkerIndex(nodeAttrs) : 0;
  11534. // When processing ":not" selectors, we skip to the next ":not" if the
  11535. // current one doesn't match
  11536. let skipToNextSelector = false;
  11537. for (let i = 0; i < selector.length; i++) {
  11538. const current = selector[i];
  11539. if (typeof current === 'number') {
  11540. // If we finish processing a :not selector and it hasn't failed, return false
  11541. if (!skipToNextSelector && !isPositive(mode) && !isPositive(current)) {
  11542. return false;
  11543. }
  11544. // If we are skipping to the next :not() and this mode flag is positive,
  11545. // it's a part of the current :not() selector, and we should keep skipping
  11546. if (skipToNextSelector && isPositive(current))
  11547. continue;
  11548. skipToNextSelector = false;
  11549. mode = current | (mode & 1 /* SelectorFlags.NOT */);
  11550. continue;
  11551. }
  11552. if (skipToNextSelector)
  11553. continue;
  11554. if (mode & 4 /* SelectorFlags.ELEMENT */) {
  11555. mode = 2 /* SelectorFlags.ATTRIBUTE */ | (mode & 1 /* SelectorFlags.NOT */);
  11556. if ((current !== '' && !hasTagAndTypeMatch(tNode, current, isProjectionMode)) ||
  11557. (current === '' && selector.length === 1)) {
  11558. if (isPositive(mode))
  11559. return false;
  11560. skipToNextSelector = true;
  11561. }
  11562. }
  11563. else if (mode & 8 /* SelectorFlags.CLASS */) {
  11564. if (nodeAttrs === null || !isCssClassMatching(tNode, nodeAttrs, current, isProjectionMode)) {
  11565. if (isPositive(mode))
  11566. return false;
  11567. skipToNextSelector = true;
  11568. }
  11569. }
  11570. else {
  11571. const selectorAttrValue = selector[++i];
  11572. const attrIndexInNode = findAttrIndexInNode(current, nodeAttrs, isInlineTemplate(tNode), isProjectionMode);
  11573. if (attrIndexInNode === -1) {
  11574. if (isPositive(mode))
  11575. return false;
  11576. skipToNextSelector = true;
  11577. continue;
  11578. }
  11579. if (selectorAttrValue !== '') {
  11580. let nodeAttrValue;
  11581. if (attrIndexInNode > nameOnlyMarkerIdx) {
  11582. nodeAttrValue = '';
  11583. }
  11584. else {
  11585. ngDevMode &&
  11586. assertNotEqual(nodeAttrs[attrIndexInNode], 0 /* AttributeMarker.NamespaceURI */, 'We do not match directives on namespaced attributes');
  11587. // we lowercase the attribute value to be able to match
  11588. // selectors without case-sensitivity
  11589. // (selectors are already in lowercase when generated)
  11590. nodeAttrValue = nodeAttrs[attrIndexInNode + 1].toLowerCase();
  11591. }
  11592. if (mode & 2 /* SelectorFlags.ATTRIBUTE */ && selectorAttrValue !== nodeAttrValue) {
  11593. if (isPositive(mode))
  11594. return false;
  11595. skipToNextSelector = true;
  11596. }
  11597. }
  11598. }
  11599. }
  11600. return isPositive(mode) || skipToNextSelector;
  11601. }
  11602. function isPositive(mode) {
  11603. return (mode & 1 /* SelectorFlags.NOT */) === 0;
  11604. }
  11605. /**
  11606. * Examines the attribute's definition array for a node to find the index of the
  11607. * attribute that matches the given `name`.
  11608. *
  11609. * NOTE: This will not match namespaced attributes.
  11610. *
  11611. * Attribute matching depends upon `isInlineTemplate` and `isProjectionMode`.
  11612. * The following table summarizes which types of attributes we attempt to match:
  11613. *
  11614. * ===========================================================================================================
  11615. * Modes | Normal Attributes | Bindings Attributes | Template Attributes | I18n
  11616. * Attributes
  11617. * ===========================================================================================================
  11618. * Inline + Projection | YES | YES | NO | YES
  11619. * -----------------------------------------------------------------------------------------------------------
  11620. * Inline + Directive | NO | NO | YES | NO
  11621. * -----------------------------------------------------------------------------------------------------------
  11622. * Non-inline + Projection | YES | YES | NO | YES
  11623. * -----------------------------------------------------------------------------------------------------------
  11624. * Non-inline + Directive | YES | YES | NO | YES
  11625. * ===========================================================================================================
  11626. *
  11627. * @param name the name of the attribute to find
  11628. * @param attrs the attribute array to examine
  11629. * @param isInlineTemplate true if the node being matched is an inline template (e.g. `*ngFor`)
  11630. * rather than a manually expanded template node (e.g `<ng-template>`).
  11631. * @param isProjectionMode true if we are matching against content projection otherwise we are
  11632. * matching against directives.
  11633. */
  11634. function findAttrIndexInNode(name, attrs, isInlineTemplate, isProjectionMode) {
  11635. if (attrs === null)
  11636. return -1;
  11637. let i = 0;
  11638. if (isProjectionMode || !isInlineTemplate) {
  11639. let bindingsMode = false;
  11640. while (i < attrs.length) {
  11641. const maybeAttrName = attrs[i];
  11642. if (maybeAttrName === name) {
  11643. return i;
  11644. }
  11645. else if (maybeAttrName === 3 /* AttributeMarker.Bindings */ ||
  11646. maybeAttrName === 6 /* AttributeMarker.I18n */) {
  11647. bindingsMode = true;
  11648. }
  11649. else if (maybeAttrName === 1 /* AttributeMarker.Classes */ ||
  11650. maybeAttrName === 2 /* AttributeMarker.Styles */) {
  11651. let value = attrs[++i];
  11652. // We should skip classes here because we have a separate mechanism for
  11653. // matching classes in projection mode.
  11654. while (typeof value === 'string') {
  11655. value = attrs[++i];
  11656. }
  11657. continue;
  11658. }
  11659. else if (maybeAttrName === 4 /* AttributeMarker.Template */) {
  11660. // We do not care about Template attributes in this scenario.
  11661. break;
  11662. }
  11663. else if (maybeAttrName === 0 /* AttributeMarker.NamespaceURI */) {
  11664. // Skip the whole namespaced attribute and value. This is by design.
  11665. i += 4;
  11666. continue;
  11667. }
  11668. // In binding mode there are only names, rather than name-value pairs.
  11669. i += bindingsMode ? 1 : 2;
  11670. }
  11671. // We did not match the attribute
  11672. return -1;
  11673. }
  11674. else {
  11675. return matchTemplateAttribute(attrs, name);
  11676. }
  11677. }
  11678. function isNodeMatchingSelectorList(tNode, selector, isProjectionMode = false) {
  11679. for (let i = 0; i < selector.length; i++) {
  11680. if (isNodeMatchingSelector(tNode, selector[i], isProjectionMode)) {
  11681. return true;
  11682. }
  11683. }
  11684. return false;
  11685. }
  11686. function getProjectAsAttrValue(tNode) {
  11687. const nodeAttrs = tNode.attrs;
  11688. if (nodeAttrs != null) {
  11689. const ngProjectAsAttrIdx = nodeAttrs.indexOf(5 /* AttributeMarker.ProjectAs */);
  11690. // only check for ngProjectAs in attribute names, don't accidentally match attribute's value
  11691. // (attribute names are stored at even indexes)
  11692. if ((ngProjectAsAttrIdx & 1) === 0) {
  11693. return nodeAttrs[ngProjectAsAttrIdx + 1];
  11694. }
  11695. }
  11696. return null;
  11697. }
  11698. function getNameOnlyMarkerIndex(nodeAttrs) {
  11699. for (let i = 0; i < nodeAttrs.length; i++) {
  11700. const nodeAttr = nodeAttrs[i];
  11701. if (isNameOnlyAttributeMarker(nodeAttr)) {
  11702. return i;
  11703. }
  11704. }
  11705. return nodeAttrs.length;
  11706. }
  11707. function matchTemplateAttribute(attrs, name) {
  11708. let i = attrs.indexOf(4 /* AttributeMarker.Template */);
  11709. if (i > -1) {
  11710. i++;
  11711. while (i < attrs.length) {
  11712. const attr = attrs[i];
  11713. // Return in case we checked all template attrs and are switching to the next section in the
  11714. // attrs array (that starts with a number that represents an attribute marker).
  11715. if (typeof attr === 'number')
  11716. return -1;
  11717. if (attr === name)
  11718. return i;
  11719. i++;
  11720. }
  11721. }
  11722. return -1;
  11723. }
  11724. /**
  11725. * Checks whether a selector is inside a CssSelectorList
  11726. * @param selector Selector to be checked.
  11727. * @param list List in which to look for the selector.
  11728. */
  11729. function isSelectorInSelectorList(selector, list) {
  11730. selectorListLoop: for (let i = 0; i < list.length; i++) {
  11731. const currentSelectorInList = list[i];
  11732. if (selector.length !== currentSelectorInList.length) {
  11733. continue;
  11734. }
  11735. for (let j = 0; j < selector.length; j++) {
  11736. if (selector[j] !== currentSelectorInList[j]) {
  11737. continue selectorListLoop;
  11738. }
  11739. }
  11740. return true;
  11741. }
  11742. return false;
  11743. }
  11744. function maybeWrapInNotSelector(isNegativeMode, chunk) {
  11745. return isNegativeMode ? ':not(' + chunk.trim() + ')' : chunk;
  11746. }
  11747. function stringifyCSSSelector(selector) {
  11748. let result = selector[0];
  11749. let i = 1;
  11750. let mode = 2 /* SelectorFlags.ATTRIBUTE */;
  11751. let currentChunk = '';
  11752. let isNegativeMode = false;
  11753. while (i < selector.length) {
  11754. let valueOrMarker = selector[i];
  11755. if (typeof valueOrMarker === 'string') {
  11756. if (mode & 2 /* SelectorFlags.ATTRIBUTE */) {
  11757. const attrValue = selector[++i];
  11758. currentChunk +=
  11759. '[' + valueOrMarker + (attrValue.length > 0 ? '="' + attrValue + '"' : '') + ']';
  11760. }
  11761. else if (mode & 8 /* SelectorFlags.CLASS */) {
  11762. currentChunk += '.' + valueOrMarker;
  11763. }
  11764. else if (mode & 4 /* SelectorFlags.ELEMENT */) {
  11765. currentChunk += ' ' + valueOrMarker;
  11766. }
  11767. }
  11768. else {
  11769. //
  11770. // Append current chunk to the final result in case we come across SelectorFlag, which
  11771. // indicates that the previous section of a selector is over. We need to accumulate content
  11772. // between flags to make sure we wrap the chunk later in :not() selector if needed, e.g.
  11773. // ```
  11774. // ['', Flags.CLASS, '.classA', Flags.CLASS | Flags.NOT, '.classB', '.classC']
  11775. // ```
  11776. // should be transformed to `.classA :not(.classB .classC)`.
  11777. //
  11778. // Note: for negative selector part, we accumulate content between flags until we find the
  11779. // next negative flag. This is needed to support a case where `:not()` rule contains more than
  11780. // one chunk, e.g. the following selector:
  11781. // ```
  11782. // ['', Flags.ELEMENT | Flags.NOT, 'p', Flags.CLASS, 'foo', Flags.CLASS | Flags.NOT, 'bar']
  11783. // ```
  11784. // should be stringified to `:not(p.foo) :not(.bar)`
  11785. //
  11786. if (currentChunk !== '' && !isPositive(valueOrMarker)) {
  11787. result += maybeWrapInNotSelector(isNegativeMode, currentChunk);
  11788. currentChunk = '';
  11789. }
  11790. mode = valueOrMarker;
  11791. // According to CssSelector spec, once we come across `SelectorFlags.NOT` flag, the negative
  11792. // mode is maintained for remaining chunks of a selector.
  11793. isNegativeMode = isNegativeMode || !isPositive(mode);
  11794. }
  11795. i++;
  11796. }
  11797. if (currentChunk !== '') {
  11798. result += maybeWrapInNotSelector(isNegativeMode, currentChunk);
  11799. }
  11800. return result;
  11801. }
  11802. /**
  11803. * Generates string representation of CSS selector in parsed form.
  11804. *
  11805. * ComponentDef and DirectiveDef are generated with the selector in parsed form to avoid doing
  11806. * additional parsing at runtime (for example, for directive matching). However in some cases (for
  11807. * example, while bootstrapping a component), a string version of the selector is required to query
  11808. * for the host element on the page. This function takes the parsed form of a selector and returns
  11809. * its string representation.
  11810. *
  11811. * @param selectorList selector in parsed form
  11812. * @returns string representation of a given selector
  11813. */
  11814. function stringifyCSSSelectorList(selectorList) {
  11815. return selectorList.map(stringifyCSSSelector).join(',');
  11816. }
  11817. /**
  11818. * Extracts attributes and classes information from a given CSS selector.
  11819. *
  11820. * This function is used while creating a component dynamically. In this case, the host element
  11821. * (that is created dynamically) should contain attributes and classes specified in component's CSS
  11822. * selector.
  11823. *
  11824. * @param selector CSS selector in parsed form (in a form of array)
  11825. * @returns object with `attrs` and `classes` fields that contain extracted information
  11826. */
  11827. function extractAttrsAndClassesFromSelector(selector) {
  11828. const attrs = [];
  11829. const classes = [];
  11830. let i = 1;
  11831. let mode = 2 /* SelectorFlags.ATTRIBUTE */;
  11832. while (i < selector.length) {
  11833. let valueOrMarker = selector[i];
  11834. if (typeof valueOrMarker === 'string') {
  11835. if (mode === 2 /* SelectorFlags.ATTRIBUTE */) {
  11836. if (valueOrMarker !== '') {
  11837. attrs.push(valueOrMarker, selector[++i]);
  11838. }
  11839. }
  11840. else if (mode === 8 /* SelectorFlags.CLASS */) {
  11841. classes.push(valueOrMarker);
  11842. }
  11843. }
  11844. else {
  11845. // According to CssSelector spec, once we come across `SelectorFlags.NOT` flag, the negative
  11846. // mode is maintained for remaining chunks of a selector. Since attributes and classes are
  11847. // extracted only for "positive" part of the selector, we can stop here.
  11848. if (!isPositive(mode))
  11849. break;
  11850. mode = valueOrMarker;
  11851. }
  11852. i++;
  11853. }
  11854. if (classes.length) {
  11855. attrs.push(1 /* AttributeMarker.Classes */, ...classes);
  11856. }
  11857. return attrs;
  11858. }
  11859. /** A special value which designates that a value has not changed. */
  11860. const NO_CHANGE = typeof ngDevMode === 'undefined' || ngDevMode ? { __brand__: 'NO_CHANGE' } : {};
  11861. function createTextNode(renderer, value) {
  11862. ngDevMode && ngDevMode.rendererCreateTextNode++;
  11863. ngDevMode && ngDevMode.rendererSetText++;
  11864. return renderer.createText(value);
  11865. }
  11866. function updateTextNode(renderer, rNode, value) {
  11867. ngDevMode && ngDevMode.rendererSetText++;
  11868. renderer.setValue(rNode, value);
  11869. }
  11870. function createCommentNode(renderer, value) {
  11871. ngDevMode && ngDevMode.rendererCreateComment++;
  11872. return renderer.createComment(escapeCommentText(value));
  11873. }
  11874. /**
  11875. * Creates a native element from a tag name, using a renderer.
  11876. * @param renderer A renderer to use
  11877. * @param name the tag name
  11878. * @param namespace Optional namespace for element.
  11879. * @returns the element created
  11880. */
  11881. function createElementNode(renderer, name, namespace) {
  11882. ngDevMode && ngDevMode.rendererCreateElement++;
  11883. return renderer.createElement(name, namespace);
  11884. }
  11885. /**
  11886. * Inserts a native node before another native node for a given parent.
  11887. * This is a utility function that can be used when native nodes were determined.
  11888. */
  11889. function nativeInsertBefore(renderer, parent, child, beforeNode, isMove) {
  11890. ngDevMode && ngDevMode.rendererInsertBefore++;
  11891. renderer.insertBefore(parent, child, beforeNode, isMove);
  11892. }
  11893. function nativeAppendChild(renderer, parent, child) {
  11894. ngDevMode && ngDevMode.rendererAppendChild++;
  11895. ngDevMode && assertDefined(parent, 'parent node must be defined');
  11896. renderer.appendChild(parent, child);
  11897. }
  11898. function nativeAppendOrInsertBefore(renderer, parent, child, beforeNode, isMove) {
  11899. if (beforeNode !== null) {
  11900. nativeInsertBefore(renderer, parent, child, beforeNode, isMove);
  11901. }
  11902. else {
  11903. nativeAppendChild(renderer, parent, child);
  11904. }
  11905. }
  11906. /**
  11907. * Removes a native node itself using a given renderer. To remove the node we are looking up its
  11908. * parent from the native tree as not all platforms / browsers support the equivalent of
  11909. * node.remove().
  11910. *
  11911. * @param renderer A renderer to be used
  11912. * @param rNode The native node that should be removed
  11913. * @param isHostElement A flag indicating if a node to be removed is a host of a component.
  11914. */
  11915. function nativeRemoveNode(renderer, rNode, isHostElement) {
  11916. ngDevMode && ngDevMode.rendererRemoveNode++;
  11917. renderer.removeChild(null, rNode, isHostElement);
  11918. }
  11919. /**
  11920. * Clears the contents of a given RElement.
  11921. *
  11922. * @param rElement the native RElement to be cleared
  11923. */
  11924. function clearElementContents(rElement) {
  11925. rElement.textContent = '';
  11926. }
  11927. /**
  11928. * Write `cssText` to `RElement`.
  11929. *
  11930. * This function does direct write without any reconciliation. Used for writing initial values, so
  11931. * that static styling values do not pull in the style parser.
  11932. *
  11933. * @param renderer Renderer to use
  11934. * @param element The element which needs to be updated.
  11935. * @param newValue The new class list to write.
  11936. */
  11937. function writeDirectStyle(renderer, element, newValue) {
  11938. ngDevMode && assertString(newValue, "'newValue' should be a string");
  11939. renderer.setAttribute(element, 'style', newValue);
  11940. ngDevMode && ngDevMode.rendererSetStyle++;
  11941. }
  11942. /**
  11943. * Write `className` to `RElement`.
  11944. *
  11945. * This function does direct write without any reconciliation. Used for writing initial values, so
  11946. * that static styling values do not pull in the style parser.
  11947. *
  11948. * @param renderer Renderer to use
  11949. * @param element The element which needs to be updated.
  11950. * @param newValue The new class list to write.
  11951. */
  11952. function writeDirectClass(renderer, element, newValue) {
  11953. ngDevMode && assertString(newValue, "'newValue' should be a string");
  11954. if (newValue === '') {
  11955. // There are tests in `google3` which expect `element.getAttribute('class')` to be `null`.
  11956. renderer.removeAttribute(element, 'class');
  11957. }
  11958. else {
  11959. renderer.setAttribute(element, 'class', newValue);
  11960. }
  11961. ngDevMode && ngDevMode.rendererSetClassName++;
  11962. }
  11963. /** Sets up the static DOM attributes on an `RNode`. */
  11964. function setupStaticAttributes(renderer, element, tNode) {
  11965. const { mergedAttrs, classes, styles } = tNode;
  11966. if (mergedAttrs !== null) {
  11967. setUpAttributes(renderer, element, mergedAttrs);
  11968. }
  11969. if (classes !== null) {
  11970. writeDirectClass(renderer, element, classes);
  11971. }
  11972. if (styles !== null) {
  11973. writeDirectStyle(renderer, element, styles);
  11974. }
  11975. }
  11976. /**
  11977. * Creates a TView instance
  11978. *
  11979. * @param type Type of `TView`.
  11980. * @param declTNode Declaration location of this `TView`.
  11981. * @param templateFn Template function
  11982. * @param decls The number of nodes, local refs, and pipes in this template
  11983. * @param directives Registry of directives for this view
  11984. * @param pipes Registry of pipes for this view
  11985. * @param viewQuery View queries for this view
  11986. * @param schemas Schemas for this view
  11987. * @param consts Constants for this view
  11988. */
  11989. function createTView(type, declTNode, templateFn, decls, vars, directives, pipes, viewQuery, schemas, constsOrFactory, ssrId) {
  11990. ngDevMode && ngDevMode.tView++;
  11991. const bindingStartIndex = HEADER_OFFSET + decls;
  11992. // This length does not yet contain host bindings from child directives because at this point,
  11993. // we don't know which directives are active on this template. As soon as a directive is matched
  11994. // that has a host binding, we will update the blueprint with that def's hostVars count.
  11995. const initialViewLength = bindingStartIndex + vars;
  11996. const blueprint = createViewBlueprint(bindingStartIndex, initialViewLength);
  11997. const consts = typeof constsOrFactory === 'function' ? constsOrFactory() : constsOrFactory;
  11998. const tView = (blueprint[TVIEW] = {
  11999. type: type,
  12000. blueprint: blueprint,
  12001. template: templateFn,
  12002. queries: null,
  12003. viewQuery: viewQuery,
  12004. declTNode: declTNode,
  12005. data: blueprint.slice().fill(null, bindingStartIndex),
  12006. bindingStartIndex: bindingStartIndex,
  12007. expandoStartIndex: initialViewLength,
  12008. hostBindingOpCodes: null,
  12009. firstCreatePass: true,
  12010. firstUpdatePass: true,
  12011. staticViewQueries: false,
  12012. staticContentQueries: false,
  12013. preOrderHooks: null,
  12014. preOrderCheckHooks: null,
  12015. contentHooks: null,
  12016. contentCheckHooks: null,
  12017. viewHooks: null,
  12018. viewCheckHooks: null,
  12019. destroyHooks: null,
  12020. cleanup: null,
  12021. contentQueries: null,
  12022. components: null,
  12023. directiveRegistry: typeof directives === 'function' ? directives() : directives,
  12024. pipeRegistry: typeof pipes === 'function' ? pipes() : pipes,
  12025. firstChild: null,
  12026. schemas: schemas,
  12027. consts: consts,
  12028. incompleteFirstPass: false,
  12029. ssrId,
  12030. });
  12031. if (ngDevMode) {
  12032. // For performance reasons it is important that the tView retains the same shape during runtime.
  12033. // (To make sure that all of the code is monomorphic.) For this reason we seal the object to
  12034. // prevent class transitions.
  12035. Object.seal(tView);
  12036. }
  12037. return tView;
  12038. }
  12039. function createViewBlueprint(bindingStartIndex, initialViewLength) {
  12040. const blueprint = [];
  12041. for (let i = 0; i < initialViewLength; i++) {
  12042. blueprint.push(i < bindingStartIndex ? null : NO_CHANGE);
  12043. }
  12044. return blueprint;
  12045. }
  12046. /**
  12047. * Gets TView from a template function or creates a new TView
  12048. * if it doesn't already exist.
  12049. *
  12050. * @param def ComponentDef
  12051. * @returns TView
  12052. */
  12053. function getOrCreateComponentTView(def) {
  12054. const tView = def.tView;
  12055. // Create a TView if there isn't one, or recreate it if the first create pass didn't
  12056. // complete successfully since we can't know for sure whether it's in a usable shape.
  12057. if (tView === null || tView.incompleteFirstPass) {
  12058. // Declaration node here is null since this function is called when we dynamically create a
  12059. // component and hence there is no declaration.
  12060. const declTNode = null;
  12061. 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));
  12062. }
  12063. return tView;
  12064. }
  12065. function createLView(parentLView, tView, context, flags, host, tHostNode, environment, renderer, injector, embeddedViewInjector, hydrationInfo) {
  12066. const lView = tView.blueprint.slice();
  12067. lView[HOST] = host;
  12068. lView[FLAGS] =
  12069. flags |
  12070. 4 /* LViewFlags.CreationMode */ |
  12071. 128 /* LViewFlags.Attached */ |
  12072. 8 /* LViewFlags.FirstLViewPass */ |
  12073. 64 /* LViewFlags.Dirty */ |
  12074. 1024 /* LViewFlags.RefreshView */;
  12075. if (embeddedViewInjector !== null ||
  12076. (parentLView && parentLView[FLAGS] & 2048 /* LViewFlags.HasEmbeddedViewInjector */)) {
  12077. lView[FLAGS] |= 2048 /* LViewFlags.HasEmbeddedViewInjector */;
  12078. }
  12079. resetPreOrderHookFlags(lView);
  12080. ngDevMode && tView.declTNode && parentLView && assertTNodeForLView(tView.declTNode, parentLView);
  12081. lView[PARENT] = lView[DECLARATION_VIEW] = parentLView;
  12082. lView[CONTEXT] = context;
  12083. lView[ENVIRONMENT] = (environment || (parentLView && parentLView[ENVIRONMENT]));
  12084. ngDevMode && assertDefined(lView[ENVIRONMENT], 'LViewEnvironment is required');
  12085. lView[RENDERER] = (renderer || (parentLView && parentLView[RENDERER]));
  12086. ngDevMode && assertDefined(lView[RENDERER], 'Renderer is required');
  12087. lView[INJECTOR] = injector || (parentLView && parentLView[INJECTOR]) || null;
  12088. lView[T_HOST] = tHostNode;
  12089. lView[ID] = getUniqueLViewId();
  12090. lView[HYDRATION] = hydrationInfo;
  12091. lView[EMBEDDED_VIEW_INJECTOR] = embeddedViewInjector;
  12092. ngDevMode &&
  12093. assertEqual(tView.type == 2 /* TViewType.Embedded */ ? parentLView !== null : true, true, 'Embedded views must have parentLView');
  12094. lView[DECLARATION_COMPONENT_VIEW] =
  12095. tView.type == 2 /* TViewType.Embedded */ ? parentLView[DECLARATION_COMPONENT_VIEW] : lView;
  12096. return lView;
  12097. }
  12098. function createComponentLView(lView, hostTNode, def) {
  12099. const native = getNativeByTNode(hostTNode, lView);
  12100. const tView = getOrCreateComponentTView(def);
  12101. // Only component views should be added to the view tree directly. Embedded views are
  12102. // accessed through their containers because they may be removed / re-added later.
  12103. const rendererFactory = lView[ENVIRONMENT].rendererFactory;
  12104. const componentView = addToEndOfViewTree(lView, createLView(lView, tView, null, getInitialLViewFlagsFromDef(def), native, hostTNode, null, rendererFactory.createRenderer(native, def), null, null, null));
  12105. // Component view will always be created before any injected LContainers,
  12106. // so this is a regular element, wrap it with the component view
  12107. return (lView[hostTNode.index] = componentView);
  12108. }
  12109. /**
  12110. * Gets the initial set of LView flags based on the component definition that the LView represents.
  12111. * @param def Component definition from which to determine the flags.
  12112. */
  12113. function getInitialLViewFlagsFromDef(def) {
  12114. let flags = 16 /* LViewFlags.CheckAlways */;
  12115. if (def.signals) {
  12116. flags = 4096 /* LViewFlags.SignalView */;
  12117. }
  12118. else if (def.onPush) {
  12119. flags = 64 /* LViewFlags.Dirty */;
  12120. }
  12121. return flags;
  12122. }
  12123. /**
  12124. * When elements are created dynamically after a view blueprint is created (e.g. through
  12125. * i18nApply()), we need to adjust the blueprint for future template passes.
  12126. *
  12127. * @param tView `TView` associated with `LView`
  12128. * @param lView The `LView` containing the blueprint to adjust
  12129. * @param numSlotsToAlloc The number of slots to alloc in the LView, should be >0
  12130. * @param initialValue Initial value to store in blueprint
  12131. */
  12132. function allocExpando(tView, lView, numSlotsToAlloc, initialValue) {
  12133. if (numSlotsToAlloc === 0)
  12134. return -1;
  12135. if (ngDevMode) {
  12136. assertFirstCreatePass(tView);
  12137. assertSame(tView, lView[TVIEW], '`LView` must be associated with `TView`!');
  12138. assertEqual(tView.data.length, lView.length, 'Expecting LView to be same size as TView');
  12139. assertEqual(tView.data.length, tView.blueprint.length, 'Expecting Blueprint to be same size as TView');
  12140. assertFirstUpdatePass(tView);
  12141. }
  12142. const allocIdx = lView.length;
  12143. for (let i = 0; i < numSlotsToAlloc; i++) {
  12144. lView.push(initialValue);
  12145. tView.blueprint.push(initialValue);
  12146. tView.data.push(null);
  12147. }
  12148. return allocIdx;
  12149. }
  12150. /**
  12151. * Adds LView or LContainer to the end of the current view tree.
  12152. *
  12153. * This structure will be used to traverse through nested views to remove listeners
  12154. * and call onDestroy callbacks.
  12155. *
  12156. * @param lView The view where LView or LContainer should be added
  12157. * @param adjustedHostIndex Index of the view's host node in LView[], adjusted for header
  12158. * @param lViewOrLContainer The LView or LContainer to add to the view tree
  12159. * @returns The state passed in
  12160. */
  12161. function addToEndOfViewTree(lView, lViewOrLContainer) {
  12162. // TODO(benlesh/misko): This implementation is incorrect, because it always adds the LContainer
  12163. // to the end of the queue, which means if the developer retrieves the LContainers from RNodes out
  12164. // of order, the change detection will run out of order, as the act of retrieving the the
  12165. // LContainer from the RNode is what adds it to the queue.
  12166. if (lView[CHILD_HEAD]) {
  12167. lView[CHILD_TAIL][NEXT] = lViewOrLContainer;
  12168. }
  12169. else {
  12170. lView[CHILD_HEAD] = lViewOrLContainer;
  12171. }
  12172. lView[CHILD_TAIL] = lViewOrLContainer;
  12173. return lViewOrLContainer;
  12174. }
  12175. /**
  12176. * Advances to an element for later binding instructions.
  12177. *
  12178. * Used in conjunction with instructions like {@link property} to act on elements with specified
  12179. * indices, for example those created with {@link element} or {@link elementStart}.
  12180. *
  12181. * ```ts
  12182. * (rf: RenderFlags, ctx: any) => {
  12183. * if (rf & 1) {
  12184. * text(0, 'Hello');
  12185. * text(1, 'Goodbye')
  12186. * element(2, 'div');
  12187. * }
  12188. * if (rf & 2) {
  12189. * advance(2); // Advance twice to the <div>.
  12190. * property('title', 'test');
  12191. * }
  12192. * }
  12193. * ```
  12194. * @param delta Number of elements to advance forwards by.
  12195. *
  12196. * @codeGenApi
  12197. */
  12198. function ɵɵadvance(delta = 1) {
  12199. ngDevMode && assertGreaterThan(delta, 0, 'Can only advance forward');
  12200. selectIndexInternal(getTView(), getLView(), getSelectedIndex() + delta, !!ngDevMode && isInCheckNoChangesMode());
  12201. }
  12202. function selectIndexInternal(tView, lView, index, checkNoChangesMode) {
  12203. ngDevMode && assertIndexInDeclRange(lView[TVIEW], index);
  12204. // Flush the initial hooks for elements in the view that have been added up to this point.
  12205. // PERF WARNING: do NOT extract this to a separate function without running benchmarks
  12206. if (!checkNoChangesMode) {
  12207. const hooksInitPhaseCompleted = (lView[FLAGS] & 3 /* LViewFlags.InitPhaseStateMask */) === 3 /* InitPhaseState.InitPhaseCompleted */;
  12208. if (hooksInitPhaseCompleted) {
  12209. const preOrderCheckHooks = tView.preOrderCheckHooks;
  12210. if (preOrderCheckHooks !== null) {
  12211. executeCheckHooks(lView, preOrderCheckHooks, index);
  12212. }
  12213. }
  12214. else {
  12215. const preOrderHooks = tView.preOrderHooks;
  12216. if (preOrderHooks !== null) {
  12217. executeInitAndCheckHooks(lView, preOrderHooks, 0 /* InitPhaseState.OnInitHooksToBeRun */, index);
  12218. }
  12219. }
  12220. }
  12221. // We must set the selected index *after* running the hooks, because hooks may have side-effects
  12222. // that cause other template functions to run, thus updating the selected index, which is global
  12223. // state. If we run `setSelectedIndex` *before* we run the hooks, in some cases the selected index
  12224. // will be altered by the time we leave the `ɵɵadvance` instruction.
  12225. setSelectedIndex(index);
  12226. }
  12227. /** Flags describing an input for a directive. */
  12228. var InputFlags;
  12229. (function (InputFlags) {
  12230. InputFlags[InputFlags["None"] = 0] = "None";
  12231. InputFlags[InputFlags["SignalBased"] = 1] = "SignalBased";
  12232. InputFlags[InputFlags["HasDecoratorInputTransform"] = 2] = "HasDecoratorInputTransform";
  12233. })(InputFlags || (InputFlags = {}));
  12234. function writeToDirectiveInput(def, instance, publicName, value) {
  12235. const prevConsumer = setActiveConsumer$1(null);
  12236. try {
  12237. if (ngDevMode) {
  12238. if (!def.inputs.hasOwnProperty(publicName)) {
  12239. throw new Error(`ASSERTION ERROR: Directive ${def.type.name} does not have an input with a public name of "${publicName}"`);
  12240. }
  12241. // Usually we resolve the directive instance using `LView[someIndex]` before writing to an
  12242. // input, however if the read happens to early, the `LView[someIndex]` might actually be a
  12243. // `NodeInjectorFactory`. Check for this specific case here since it can break in subtle ways.
  12244. if (instance instanceof NodeInjectorFactory) {
  12245. throw new Error(`ASSERTION ERROR: Cannot write input to factory for type ${def.type.name}. Directive has not been created yet.`);
  12246. }
  12247. }
  12248. const [privateName, flags, transform] = def.inputs[publicName];
  12249. // If we know we are dealing with a signal input, we cache its reference
  12250. // in a tree-shakable way. The input signal node can then be used for
  12251. // value transform execution or actual value updates without introducing
  12252. // additional megamorphic accesses for accessing the instance field.
  12253. let inputSignalNode = null;
  12254. if ((flags & InputFlags.SignalBased) !== 0) {
  12255. const field = instance[privateName];
  12256. inputSignalNode = field[SIGNAL];
  12257. }
  12258. // If there is a signal node and a transform, run it before potentially
  12259. // delegating to features like `NgOnChanges`.
  12260. if (inputSignalNode !== null && inputSignalNode.transformFn !== undefined) {
  12261. value = inputSignalNode.transformFn(value);
  12262. }
  12263. else if (transform !== null) {
  12264. // If there is a decorator input transform, run it.
  12265. value = transform.call(instance, value);
  12266. }
  12267. if (def.setInput !== null) {
  12268. def.setInput(instance, inputSignalNode, value, publicName, privateName);
  12269. }
  12270. else {
  12271. applyValueToInputField(instance, inputSignalNode, privateName, value);
  12272. }
  12273. }
  12274. finally {
  12275. setActiveConsumer$1(prevConsumer);
  12276. }
  12277. }
  12278. function executeTemplate(tView, lView, templateFn, rf, context) {
  12279. const prevSelectedIndex = getSelectedIndex();
  12280. const isUpdatePhase = rf & 2 /* RenderFlags.Update */;
  12281. try {
  12282. setSelectedIndex(-1);
  12283. if (isUpdatePhase && lView.length > HEADER_OFFSET) {
  12284. // When we're updating, inherently select 0 so we don't
  12285. // have to generate that instruction for most update blocks.
  12286. selectIndexInternal(tView, lView, HEADER_OFFSET, !!ngDevMode && isInCheckNoChangesMode());
  12287. }
  12288. const preHookType = isUpdatePhase
  12289. ? 2 /* ProfilerEvent.TemplateUpdateStart */
  12290. : 0 /* ProfilerEvent.TemplateCreateStart */;
  12291. profiler(preHookType, context);
  12292. templateFn(rf, context);
  12293. }
  12294. finally {
  12295. setSelectedIndex(prevSelectedIndex);
  12296. const postHookType = isUpdatePhase
  12297. ? 3 /* ProfilerEvent.TemplateUpdateEnd */
  12298. : 1 /* ProfilerEvent.TemplateCreateEnd */;
  12299. profiler(postHookType, context);
  12300. }
  12301. }
  12302. /**
  12303. * Creates directive instances.
  12304. */
  12305. function createDirectivesInstances(tView, lView, tNode) {
  12306. instantiateAllDirectives(tView, lView, tNode);
  12307. if ((tNode.flags & 64 /* TNodeFlags.hasHostBindings */) === 64 /* TNodeFlags.hasHostBindings */) {
  12308. invokeDirectivesHostBindings(tView, lView, tNode);
  12309. }
  12310. }
  12311. /**
  12312. * Takes a list of local names and indices and pushes the resolved local variable values
  12313. * to LView in the same order as they are loaded in the template with load().
  12314. */
  12315. function saveResolvedLocalsInData(viewData, tNode, localRefExtractor = getNativeByTNode) {
  12316. const localNames = tNode.localNames;
  12317. if (localNames !== null) {
  12318. let localIndex = tNode.index + 1;
  12319. for (let i = 0; i < localNames.length; i += 2) {
  12320. const index = localNames[i + 1];
  12321. const value = index === -1
  12322. ? localRefExtractor(tNode, viewData)
  12323. : viewData[index];
  12324. viewData[localIndex++] = value;
  12325. }
  12326. }
  12327. }
  12328. /**
  12329. * Locates the host native element, used for bootstrapping existing nodes into rendering pipeline.
  12330. *
  12331. * @param renderer the renderer used to locate the element.
  12332. * @param elementOrSelector Render element or CSS selector to locate the element.
  12333. * @param encapsulation View Encapsulation defined for component that requests host element.
  12334. * @param injector Root view injector instance.
  12335. */
  12336. function locateHostElement(renderer, elementOrSelector, encapsulation, injector) {
  12337. // Note: we use default value for the `PRESERVE_HOST_CONTENT` here even though it's a
  12338. // tree-shakable one (providedIn:'root'). This code path can be triggered during dynamic
  12339. // component creation (after calling ViewContainerRef.createComponent) when an injector
  12340. // instance can be provided. The injector instance might be disconnected from the main DI
  12341. // tree, thus the `PRESERVE_HOST_CONTENT` would not be able to instantiate. In this case, the
  12342. // default value will be used.
  12343. const preserveHostContent = injector.get(PRESERVE_HOST_CONTENT, PRESERVE_HOST_CONTENT_DEFAULT);
  12344. // When using native Shadow DOM, do not clear host element to allow native slot
  12345. // projection.
  12346. const preserveContent = preserveHostContent || encapsulation === ViewEncapsulation.ShadowDom;
  12347. const rootElement = renderer.selectRootElement(elementOrSelector, preserveContent);
  12348. applyRootElementTransform(rootElement);
  12349. return rootElement;
  12350. }
  12351. /**
  12352. * Applies any root element transformations that are needed. If hydration is enabled,
  12353. * this will process corrupted text nodes.
  12354. *
  12355. * @param rootElement the app root HTML Element
  12356. */
  12357. function applyRootElementTransform(rootElement) {
  12358. _applyRootElementTransformImpl(rootElement);
  12359. }
  12360. /**
  12361. * Reference to a function that applies transformations to the root HTML element
  12362. * of an app. When hydration is enabled, this processes any corrupt text nodes
  12363. * so they are properly hydratable on the client.
  12364. *
  12365. * @param rootElement the app root HTML Element
  12366. */
  12367. let _applyRootElementTransformImpl = () => null;
  12368. /**
  12369. * Processes text node markers before hydration begins. This replaces any special comment
  12370. * nodes that were added prior to serialization are swapped out to restore proper text
  12371. * nodes before hydration.
  12372. *
  12373. * @param rootElement the app root HTML Element
  12374. */
  12375. function applyRootElementTransformImpl(rootElement) {
  12376. if (hasSkipHydrationAttrOnRElement(rootElement)) {
  12377. // Handle a situation when the `ngSkipHydration` attribute is applied
  12378. // to the root node of an application. In this case, we should clear
  12379. // the contents and render everything from scratch.
  12380. clearElementContents(rootElement);
  12381. }
  12382. else {
  12383. processTextNodeMarkersBeforeHydration(rootElement);
  12384. }
  12385. }
  12386. /**
  12387. * Sets the implementation for the `applyRootElementTransform` function.
  12388. */
  12389. function enableApplyRootElementTransformImpl() {
  12390. _applyRootElementTransformImpl = applyRootElementTransformImpl;
  12391. }
  12392. /**
  12393. * Mapping between attributes names that don't correspond to their element property names.
  12394. *
  12395. * Performance note: this function is written as a series of if checks (instead of, say, a property
  12396. * object lookup) for performance reasons - the series of `if` checks seems to be the fastest way of
  12397. * mapping property names. Do NOT change without benchmarking.
  12398. *
  12399. * Note: this mapping has to be kept in sync with the equally named mapping in the template
  12400. * type-checking machinery of ngtsc.
  12401. */
  12402. function mapPropName(name) {
  12403. if (name === 'class')
  12404. return 'className';
  12405. if (name === 'for')
  12406. return 'htmlFor';
  12407. if (name === 'formaction')
  12408. return 'formAction';
  12409. if (name === 'innerHtml')
  12410. return 'innerHTML';
  12411. if (name === 'readonly')
  12412. return 'readOnly';
  12413. if (name === 'tabindex')
  12414. return 'tabIndex';
  12415. return name;
  12416. }
  12417. function elementPropertyInternal(tView, tNode, lView, propName, value, renderer, sanitizer, nativeOnly) {
  12418. ngDevMode && assertNotSame(value, NO_CHANGE, 'Incoming value should never be NO_CHANGE.');
  12419. if (!nativeOnly) {
  12420. const hasSetInput = setAllInputsForProperty(tNode, tView, lView, propName, value);
  12421. if (hasSetInput) {
  12422. isComponentHost(tNode) && markDirtyIfOnPush(lView, tNode.index);
  12423. ngDevMode && setNgReflectProperties(lView, tView, tNode, propName, value);
  12424. return; // Stop propcessing if we've matched at least one input.
  12425. }
  12426. }
  12427. if (tNode.type & 3 /* TNodeType.AnyRNode */) {
  12428. const element = getNativeByTNode(tNode, lView);
  12429. propName = mapPropName(propName);
  12430. if (ngDevMode) {
  12431. validateAgainstEventProperties(propName);
  12432. if (!isPropertyValid(element, propName, tNode.value, tView.schemas)) {
  12433. handleUnknownPropertyError(propName, tNode.value, tNode.type, lView);
  12434. }
  12435. ngDevMode.rendererSetProperty++;
  12436. }
  12437. // It is assumed that the sanitizer is only added when the compiler determines that the
  12438. // property is risky, so sanitization can be done without further checks.
  12439. value = sanitizer != null ? sanitizer(value, tNode.value || '', propName) : value;
  12440. renderer.setProperty(element, propName, value);
  12441. }
  12442. else if (tNode.type & 12 /* TNodeType.AnyContainer */) {
  12443. // If the node is a container and the property didn't
  12444. // match any of the inputs or schemas we should throw.
  12445. if (ngDevMode && !matchingSchemas(tView.schemas, tNode.value)) {
  12446. handleUnknownPropertyError(propName, tNode.value, tNode.type, lView);
  12447. }
  12448. }
  12449. }
  12450. /** If node is an OnPush component, marks its LView dirty. */
  12451. function markDirtyIfOnPush(lView, viewIndex) {
  12452. ngDevMode && assertLView(lView);
  12453. const childComponentLView = getComponentLViewByIndex(viewIndex, lView);
  12454. if (!(childComponentLView[FLAGS] & 16 /* LViewFlags.CheckAlways */)) {
  12455. childComponentLView[FLAGS] |= 64 /* LViewFlags.Dirty */;
  12456. }
  12457. }
  12458. function setNgReflectProperty(lView, tNode, attrName, value) {
  12459. const element = getNativeByTNode(tNode, lView);
  12460. const renderer = lView[RENDERER];
  12461. attrName = normalizeDebugBindingName(attrName);
  12462. const debugValue = normalizeDebugBindingValue(value);
  12463. if (tNode.type & 3 /* TNodeType.AnyRNode */) {
  12464. if (value == null) {
  12465. renderer.removeAttribute(element, attrName);
  12466. }
  12467. else {
  12468. renderer.setAttribute(element, attrName, debugValue);
  12469. }
  12470. }
  12471. else {
  12472. const textContent = escapeCommentText(`bindings=${JSON.stringify({ [attrName]: debugValue }, null, 2)}`);
  12473. renderer.setValue(element, textContent);
  12474. }
  12475. }
  12476. function setNgReflectProperties(lView, tView, tNode, publicName, value) {
  12477. if (!(tNode.type & (3 /* TNodeType.AnyRNode */ | 4 /* TNodeType.Container */))) {
  12478. return;
  12479. }
  12480. const inputConfig = tNode.inputs?.[publicName];
  12481. const hostInputConfig = tNode.hostDirectiveInputs?.[publicName];
  12482. if (hostInputConfig) {
  12483. for (let i = 0; i < hostInputConfig.length; i += 2) {
  12484. const index = hostInputConfig[i];
  12485. const publicName = hostInputConfig[i + 1];
  12486. const def = tView.data[index];
  12487. setNgReflectProperty(lView, tNode, def.inputs[publicName][0], value);
  12488. }
  12489. }
  12490. // Note: we set the private name of the input as the reflected property, not the public one.
  12491. if (inputConfig) {
  12492. for (const index of inputConfig) {
  12493. const def = tView.data[index];
  12494. setNgReflectProperty(lView, tNode, def.inputs[publicName][0], value);
  12495. }
  12496. }
  12497. }
  12498. /**
  12499. * Instantiate all the directives that were previously resolved on the current node.
  12500. */
  12501. function instantiateAllDirectives(tView, lView, tNode) {
  12502. const start = tNode.directiveStart;
  12503. const end = tNode.directiveEnd;
  12504. // The component view needs to be created before creating the node injector
  12505. // since it is used to inject some special symbols like `ChangeDetectorRef`.
  12506. if (isComponentHost(tNode)) {
  12507. ngDevMode && assertTNodeType(tNode, 3 /* TNodeType.AnyRNode */);
  12508. createComponentLView(lView, tNode, tView.data[start + tNode.componentOffset]);
  12509. }
  12510. if (!tView.firstCreatePass) {
  12511. getOrCreateNodeInjectorForNode(tNode, lView);
  12512. }
  12513. const initialInputs = tNode.initialInputs;
  12514. for (let i = start; i < end; i++) {
  12515. const def = tView.data[i];
  12516. const directive = getNodeInjectable(lView, tView, i, tNode);
  12517. attachPatchData(directive, lView);
  12518. if (initialInputs !== null) {
  12519. setInputsFromAttrs(lView, i - start, directive, def, tNode, initialInputs);
  12520. }
  12521. if (isComponentDef(def)) {
  12522. const componentView = getComponentLViewByIndex(tNode.index, lView);
  12523. componentView[CONTEXT] = getNodeInjectable(lView, tView, i, tNode);
  12524. }
  12525. }
  12526. }
  12527. function invokeDirectivesHostBindings(tView, lView, tNode) {
  12528. const start = tNode.directiveStart;
  12529. const end = tNode.directiveEnd;
  12530. const elementIndex = tNode.index;
  12531. const currentDirectiveIndex = getCurrentDirectiveIndex();
  12532. try {
  12533. setSelectedIndex(elementIndex);
  12534. for (let dirIndex = start; dirIndex < end; dirIndex++) {
  12535. const def = tView.data[dirIndex];
  12536. const directive = lView[dirIndex];
  12537. setCurrentDirectiveIndex(dirIndex);
  12538. if (def.hostBindings !== null || def.hostVars !== 0 || def.hostAttrs !== null) {
  12539. invokeHostBindingsInCreationMode(def, directive);
  12540. }
  12541. }
  12542. }
  12543. finally {
  12544. setSelectedIndex(-1);
  12545. setCurrentDirectiveIndex(currentDirectiveIndex);
  12546. }
  12547. }
  12548. /**
  12549. * Invoke the host bindings in creation mode.
  12550. *
  12551. * @param def `DirectiveDef` which may contain the `hostBindings` function.
  12552. * @param directive Instance of directive.
  12553. */
  12554. function invokeHostBindingsInCreationMode(def, directive) {
  12555. if (def.hostBindings !== null) {
  12556. def.hostBindings(1 /* RenderFlags.Create */, directive);
  12557. }
  12558. }
  12559. /**
  12560. * Matches the current node against all available selectors.
  12561. * If a component is matched (at most one), it is returned in first position in the array.
  12562. */
  12563. function findDirectiveDefMatches(tView, tNode) {
  12564. ngDevMode && assertFirstCreatePass(tView);
  12565. ngDevMode && assertTNodeType(tNode, 3 /* TNodeType.AnyRNode */ | 12 /* TNodeType.AnyContainer */);
  12566. const registry = tView.directiveRegistry;
  12567. let matches = null;
  12568. if (registry) {
  12569. for (let i = 0; i < registry.length; i++) {
  12570. const def = registry[i];
  12571. if (isNodeMatchingSelectorList(tNode, def.selectors, /* isProjectionMode */ false)) {
  12572. matches ??= [];
  12573. if (isComponentDef(def)) {
  12574. if (ngDevMode) {
  12575. assertTNodeType(tNode, 2 /* TNodeType.Element */, `"${tNode.value}" tags cannot be used as component hosts. ` +
  12576. `Please use a different tag to activate the ${stringify(def.type)} component.`);
  12577. if (matches.length && isComponentDef(matches[0])) {
  12578. throwMultipleComponentError(tNode, matches.find(isComponentDef).type, def.type);
  12579. }
  12580. }
  12581. matches.unshift(def);
  12582. }
  12583. else {
  12584. matches.push(def);
  12585. }
  12586. }
  12587. }
  12588. }
  12589. return matches;
  12590. }
  12591. function elementAttributeInternal(tNode, lView, name, value, sanitizer, namespace) {
  12592. if (ngDevMode) {
  12593. assertNotSame(value, NO_CHANGE, 'Incoming value should never be NO_CHANGE.');
  12594. validateAgainstEventAttributes(name);
  12595. assertTNodeType(tNode, 2 /* TNodeType.Element */, `Attempted to set attribute \`${name}\` on a container node. ` +
  12596. `Host bindings are not valid on ng-container or ng-template.`);
  12597. }
  12598. const element = getNativeByTNode(tNode, lView);
  12599. setElementAttribute(lView[RENDERER], element, namespace, tNode.value, name, value, sanitizer);
  12600. }
  12601. function setElementAttribute(renderer, element, namespace, tagName, name, value, sanitizer) {
  12602. if (value == null) {
  12603. ngDevMode && ngDevMode.rendererRemoveAttribute++;
  12604. renderer.removeAttribute(element, name, namespace);
  12605. }
  12606. else {
  12607. ngDevMode && ngDevMode.rendererSetAttribute++;
  12608. const strValue = sanitizer == null ? renderStringify(value) : sanitizer(value, tagName || '', name);
  12609. renderer.setAttribute(element, name, strValue, namespace);
  12610. }
  12611. }
  12612. /**
  12613. * Sets initial input properties on directive instances from attribute data
  12614. *
  12615. * @param lView Current LView that is being processed.
  12616. * @param directiveIndex Index of the directive in directives array
  12617. * @param instance Instance of the directive on which to set the initial inputs
  12618. * @param def The directive def that contains the list of inputs
  12619. * @param tNode The static data for this node
  12620. */
  12621. function setInputsFromAttrs(lView, directiveIndex, instance, def, tNode, initialInputData) {
  12622. const initialInputs = initialInputData[directiveIndex];
  12623. if (initialInputs !== null) {
  12624. for (let i = 0; i < initialInputs.length; i += 2) {
  12625. const lookupName = initialInputs[i];
  12626. const value = initialInputs[i + 1];
  12627. writeToDirectiveInput(def, instance, lookupName, value);
  12628. if (ngDevMode) {
  12629. setNgReflectProperty(lView, tNode, def.inputs[lookupName][0], value);
  12630. }
  12631. }
  12632. }
  12633. }
  12634. ///////////////////////////////
  12635. //// Bindings & interpolations
  12636. ///////////////////////////////
  12637. /**
  12638. * Stores meta-data for a property binding to be used by TestBed's `DebugElement.properties`.
  12639. *
  12640. * In order to support TestBed's `DebugElement.properties` we need to save, for each binding:
  12641. * - a bound property name;
  12642. * - a static parts of interpolated strings;
  12643. *
  12644. * A given property metadata is saved at the binding's index in the `TView.data` (in other words, a
  12645. * property binding metadata will be stored in `TView.data` at the same index as a bound value in
  12646. * `LView`). Metadata are represented as `INTERPOLATION_DELIMITER`-delimited string with the
  12647. * following format:
  12648. * - `propertyName` for bound properties;
  12649. * - `propertyName�prefix�interpolation_static_part1�..interpolation_static_partN�suffix` for
  12650. * interpolated properties.
  12651. *
  12652. * @param tData `TData` where meta-data will be saved;
  12653. * @param tNode `TNode` that is a target of the binding;
  12654. * @param propertyName bound property name;
  12655. * @param bindingIndex binding index in `LView`
  12656. * @param interpolationParts static interpolation parts (for property interpolations)
  12657. */
  12658. function storePropertyBindingMetadata(tData, tNode, propertyName, bindingIndex, ...interpolationParts) {
  12659. // Binding meta-data are stored only the first time a given property instruction is processed.
  12660. // Since we don't have a concept of the "first update pass" we need to check for presence of the
  12661. // binding meta-data to decide if one should be stored (or if was stored already).
  12662. if (tData[bindingIndex] === null) {
  12663. if (!tNode.inputs?.[propertyName] && !tNode.hostDirectiveInputs?.[propertyName]) {
  12664. const propBindingIdxs = tNode.propertyBindings || (tNode.propertyBindings = []);
  12665. propBindingIdxs.push(bindingIndex);
  12666. let bindingMetadata = propertyName;
  12667. if (interpolationParts.length > 0) {
  12668. bindingMetadata +=
  12669. INTERPOLATION_DELIMITER + interpolationParts.join(INTERPOLATION_DELIMITER);
  12670. }
  12671. tData[bindingIndex] = bindingMetadata;
  12672. }
  12673. }
  12674. }
  12675. /**
  12676. * There are cases where the sub component's renderer needs to be included
  12677. * instead of the current renderer (see the componentSyntheticHost* instructions).
  12678. */
  12679. function loadComponentRenderer(currentDef, tNode, lView) {
  12680. // TODO(FW-2043): the `currentDef` is null when host bindings are invoked while creating root
  12681. // component (see packages/core/src/render3/component.ts). This is not consistent with the process
  12682. // of creating inner components, when current directive index is available in the state. In order
  12683. // to avoid relying on current def being `null` (thus special-casing root component creation), the
  12684. // process of creating root component should be unified with the process of creating inner
  12685. // components.
  12686. if (currentDef === null || isComponentDef(currentDef)) {
  12687. lView = unwrapLView(lView[tNode.index]);
  12688. }
  12689. return lView[RENDERER];
  12690. }
  12691. /** Handles an error thrown in an LView. */
  12692. function handleError$1(lView, error) {
  12693. const injector = lView[INJECTOR];
  12694. const errorHandler = injector ? injector.get(ErrorHandler, null) : null;
  12695. errorHandler && errorHandler.handleError(error);
  12696. }
  12697. /**
  12698. * Set all directive inputs with the specific public name on the node.
  12699. *
  12700. * @param tNode TNode on which the input is being set.
  12701. * @param tView Current TView
  12702. * @param lView `LView` which contains the directives.
  12703. * @param publicName Public name of the input being set.
  12704. * @param value Value to set.
  12705. */
  12706. function setAllInputsForProperty(tNode, tView, lView, publicName, value) {
  12707. const inputs = tNode.inputs?.[publicName];
  12708. const hostDirectiveInputs = tNode.hostDirectiveInputs?.[publicName];
  12709. let hasMatch = false;
  12710. if (hostDirectiveInputs) {
  12711. for (let i = 0; i < hostDirectiveInputs.length; i += 2) {
  12712. const index = hostDirectiveInputs[i];
  12713. ngDevMode && assertIndexInRange(lView, index);
  12714. const publicName = hostDirectiveInputs[i + 1];
  12715. const def = tView.data[index];
  12716. writeToDirectiveInput(def, lView[index], publicName, value);
  12717. hasMatch = true;
  12718. }
  12719. }
  12720. if (inputs) {
  12721. for (const index of inputs) {
  12722. ngDevMode && assertIndexInRange(lView, index);
  12723. const instance = lView[index];
  12724. const def = tView.data[index];
  12725. writeToDirectiveInput(def, instance, publicName, value);
  12726. hasMatch = true;
  12727. }
  12728. }
  12729. return hasMatch;
  12730. }
  12731. function renderComponent(hostLView, componentHostIdx) {
  12732. ngDevMode && assertEqual(isCreationMode(hostLView), true, 'Should be run in creation mode');
  12733. const componentView = getComponentLViewByIndex(componentHostIdx, hostLView);
  12734. const componentTView = componentView[TVIEW];
  12735. syncViewWithBlueprint(componentTView, componentView);
  12736. const hostRNode = componentView[HOST];
  12737. // Populate an LView with hydration info retrieved from the DOM via TransferState.
  12738. if (hostRNode !== null && componentView[HYDRATION] === null) {
  12739. componentView[HYDRATION] = retrieveHydrationInfo(hostRNode, componentView[INJECTOR]);
  12740. }
  12741. profiler(18 /* ProfilerEvent.ComponentStart */);
  12742. renderView(componentTView, componentView, componentView[CONTEXT]);
  12743. profiler(19 /* ProfilerEvent.ComponentEnd */, componentView[CONTEXT]);
  12744. }
  12745. /**
  12746. * Syncs an LView instance with its blueprint if they have gotten out of sync.
  12747. *
  12748. * Typically, blueprints and their view instances should always be in sync, so the loop here
  12749. * will be skipped. However, consider this case of two components side-by-side:
  12750. *
  12751. * App template:
  12752. * ```html
  12753. * <comp></comp>
  12754. * <comp></comp>
  12755. * ```
  12756. *
  12757. * The following will happen:
  12758. * 1. App template begins processing.
  12759. * 2. First <comp> is matched as a component and its LView is created.
  12760. * 3. Second <comp> is matched as a component and its LView is created.
  12761. * 4. App template completes processing, so it's time to check child templates.
  12762. * 5. First <comp> template is checked. It has a directive, so its def is pushed to blueprint.
  12763. * 6. Second <comp> template is checked. Its blueprint has been updated by the first
  12764. * <comp> template, but its LView was created before this update, so it is out of sync.
  12765. *
  12766. * Note that embedded views inside ngFor loops will never be out of sync because these views
  12767. * are processed as soon as they are created.
  12768. *
  12769. * @param tView The `TView` that contains the blueprint for syncing
  12770. * @param lView The view to sync
  12771. */
  12772. function syncViewWithBlueprint(tView, lView) {
  12773. for (let i = lView.length; i < tView.blueprint.length; i++) {
  12774. lView.push(tView.blueprint[i]);
  12775. }
  12776. }
  12777. /**
  12778. * Processes a view in the creation mode. This includes a number of steps in a specific order:
  12779. * - creating view query functions (if any);
  12780. * - executing a template function in the creation mode;
  12781. * - updating static queries (if any);
  12782. * - creating child components defined in a given view.
  12783. */
  12784. function renderView(tView, lView, context) {
  12785. ngDevMode && assertEqual(isCreationMode(lView), true, 'Should be run in creation mode');
  12786. ngDevMode && assertNotReactive(renderView.name);
  12787. enterView(lView);
  12788. try {
  12789. const viewQuery = tView.viewQuery;
  12790. if (viewQuery !== null) {
  12791. executeViewQueryFn(1 /* RenderFlags.Create */, viewQuery, context);
  12792. }
  12793. // Execute a template associated with this view, if it exists. A template function might not be
  12794. // defined for the root component views.
  12795. const templateFn = tView.template;
  12796. if (templateFn !== null) {
  12797. executeTemplate(tView, lView, templateFn, 1 /* RenderFlags.Create */, context);
  12798. }
  12799. // This needs to be set before children are processed to support recursive components.
  12800. // This must be set to false immediately after the first creation run because in an
  12801. // ngFor loop, all the views will be created together before update mode runs and turns
  12802. // off firstCreatePass. If we don't set it here, instances will perform directive
  12803. // matching, etc again and again.
  12804. if (tView.firstCreatePass) {
  12805. tView.firstCreatePass = false;
  12806. }
  12807. // Mark all queries active in this view as dirty. This is necessary for signal-based queries to
  12808. // have a clear marking point where we can read query results atomically (for a given view).
  12809. lView[QUERIES]?.finishViewCreation(tView);
  12810. // We resolve content queries specifically marked as `static` in creation mode. Dynamic
  12811. // content queries are resolved during change detection (i.e. update mode), after embedded
  12812. // views are refreshed (see block above).
  12813. if (tView.staticContentQueries) {
  12814. refreshContentQueries(tView, lView);
  12815. }
  12816. // We must materialize query results before child components are processed
  12817. // in case a child component has projected a container. The LContainer needs
  12818. // to exist so the embedded views are properly attached by the container.
  12819. if (tView.staticViewQueries) {
  12820. executeViewQueryFn(2 /* RenderFlags.Update */, tView.viewQuery, context);
  12821. }
  12822. // Render child component views.
  12823. const components = tView.components;
  12824. if (components !== null) {
  12825. renderChildComponents(lView, components);
  12826. }
  12827. }
  12828. catch (error) {
  12829. // If we didn't manage to get past the first template pass due to
  12830. // an error, mark the view as corrupted so we can try to recover.
  12831. if (tView.firstCreatePass) {
  12832. tView.incompleteFirstPass = true;
  12833. tView.firstCreatePass = false;
  12834. }
  12835. throw error;
  12836. }
  12837. finally {
  12838. lView[FLAGS] &= -5 /* LViewFlags.CreationMode */;
  12839. leaveView();
  12840. }
  12841. }
  12842. /** Renders child components in the current view (creation mode). */
  12843. function renderChildComponents(hostLView, components) {
  12844. for (let i = 0; i < components.length; i++) {
  12845. renderComponent(hostLView, components[i]);
  12846. }
  12847. }
  12848. function createAndRenderEmbeddedLView(declarationLView, templateTNode, context, options) {
  12849. const prevConsumer = setActiveConsumer$1(null);
  12850. try {
  12851. const embeddedTView = templateTNode.tView;
  12852. ngDevMode && assertDefined(embeddedTView, 'TView must be defined for a template node.');
  12853. ngDevMode && assertTNodeForLView(templateTNode, declarationLView);
  12854. // Embedded views follow the change detection strategy of the view they're declared in.
  12855. const isSignalView = declarationLView[FLAGS] & 4096 /* LViewFlags.SignalView */;
  12856. const viewFlags = isSignalView ? 4096 /* LViewFlags.SignalView */ : 16 /* LViewFlags.CheckAlways */;
  12857. const embeddedLView = createLView(declarationLView, embeddedTView, context, viewFlags, null, templateTNode, null, null, options?.injector ?? null, options?.embeddedViewInjector ?? null, options?.dehydratedView ?? null);
  12858. const declarationLContainer = declarationLView[templateTNode.index];
  12859. ngDevMode && assertLContainer(declarationLContainer);
  12860. embeddedLView[DECLARATION_LCONTAINER] = declarationLContainer;
  12861. const declarationViewLQueries = declarationLView[QUERIES];
  12862. if (declarationViewLQueries !== null) {
  12863. embeddedLView[QUERIES] = declarationViewLQueries.createEmbeddedView(embeddedTView);
  12864. }
  12865. // execute creation mode of a view
  12866. renderView(embeddedTView, embeddedLView, context);
  12867. return embeddedLView;
  12868. }
  12869. finally {
  12870. setActiveConsumer$1(prevConsumer);
  12871. }
  12872. }
  12873. /**
  12874. * Returns whether an elements that belong to a view should be
  12875. * inserted into the DOM. For client-only cases, DOM elements are
  12876. * always inserted. For hydration cases, we check whether serialized
  12877. * info is available for a view and the view is not in a "skip hydration"
  12878. * block (in which case view contents was re-created, thus needing insertion).
  12879. */
  12880. function shouldAddViewToDom(tNode, dehydratedView) {
  12881. return (!dehydratedView || dehydratedView.firstChild === null || hasInSkipHydrationBlockFlag(tNode));
  12882. }
  12883. let _icuContainerIterate;
  12884. /**
  12885. * Iterator which provides ability to visit all of the `TIcuContainerNode` root `RNode`s.
  12886. */
  12887. function icuContainerIterate(tIcuContainerNode, lView) {
  12888. return _icuContainerIterate(tIcuContainerNode, lView);
  12889. }
  12890. /**
  12891. * Ensures that `IcuContainerVisitor`'s implementation is present.
  12892. *
  12893. * This function is invoked when i18n instruction comes across an ICU. The purpose is to allow the
  12894. * bundler to tree shake ICU logic and only load it if ICU instruction is executed.
  12895. */
  12896. function ensureIcuContainerVisitorLoaded(loader) {
  12897. if (_icuContainerIterate === undefined) {
  12898. // Do not inline this function. We want to keep `ensureIcuContainerVisitorLoaded` light, so it
  12899. // can be inlined into call-site.
  12900. _icuContainerIterate = loader();
  12901. }
  12902. }
  12903. /**
  12904. * Flags for renderer-specific style modifiers.
  12905. * @publicApi
  12906. */
  12907. var RendererStyleFlags2;
  12908. (function (RendererStyleFlags2) {
  12909. // TODO(misko): This needs to be refactored into a separate file so that it can be imported from
  12910. // `node_manipulation.ts` Currently doing the import cause resolution order to change and fails
  12911. // the tests. The work around is to have hard coded value in `node_manipulation.ts` for now.
  12912. /**
  12913. * Marks a style as important.
  12914. */
  12915. RendererStyleFlags2[RendererStyleFlags2["Important"] = 1] = "Important";
  12916. /**
  12917. * Marks a style as using dash case naming (this-is-dash-case).
  12918. */
  12919. RendererStyleFlags2[RendererStyleFlags2["DashCase"] = 2] = "DashCase";
  12920. })(RendererStyleFlags2 || (RendererStyleFlags2 = {}));
  12921. /**
  12922. * Checks whether a TNode is considered detached, i.e. not present in the
  12923. * translated i18n template. We should not attempt hydration for such nodes
  12924. * and instead, use a regular "creation mode".
  12925. */
  12926. function isDetachedByI18n(tNode) {
  12927. return (tNode.flags & 32 /* TNodeFlags.isDetached */) === 32 /* TNodeFlags.isDetached */;
  12928. }
  12929. /**
  12930. * NOTE: for performance reasons, the possible actions are inlined within the function instead of
  12931. * being passed as an argument.
  12932. */
  12933. function applyToElementOrContainer(action, renderer, parent, lNodeToHandle, beforeNode) {
  12934. // If this slot was allocated for a text node dynamically created by i18n, the text node itself
  12935. // won't be created until i18nApply() in the update block, so this node should be skipped.
  12936. // For more info, see "ICU expressions should work inside an ngTemplateOutlet inside an ngFor"
  12937. // in `i18n_spec.ts`.
  12938. if (lNodeToHandle != null) {
  12939. let lContainer;
  12940. let isComponent = false;
  12941. // We are expecting an RNode, but in the case of a component or LContainer the `RNode` is
  12942. // wrapped in an array which needs to be unwrapped. We need to know if it is a component and if
  12943. // it has LContainer so that we can process all of those cases appropriately.
  12944. if (isLContainer(lNodeToHandle)) {
  12945. lContainer = lNodeToHandle;
  12946. }
  12947. else if (isLView(lNodeToHandle)) {
  12948. isComponent = true;
  12949. ngDevMode && assertDefined(lNodeToHandle[HOST], 'HOST must be defined for a component LView');
  12950. lNodeToHandle = lNodeToHandle[HOST];
  12951. }
  12952. const rNode = unwrapRNode(lNodeToHandle);
  12953. if (action === 0 /* WalkTNodeTreeAction.Create */ && parent !== null) {
  12954. if (beforeNode == null) {
  12955. nativeAppendChild(renderer, parent, rNode);
  12956. }
  12957. else {
  12958. nativeInsertBefore(renderer, parent, rNode, beforeNode || null, true);
  12959. }
  12960. }
  12961. else if (action === 1 /* WalkTNodeTreeAction.Insert */ && parent !== null) {
  12962. nativeInsertBefore(renderer, parent, rNode, beforeNode || null, true);
  12963. }
  12964. else if (action === 2 /* WalkTNodeTreeAction.Detach */) {
  12965. nativeRemoveNode(renderer, rNode, isComponent);
  12966. }
  12967. else if (action === 3 /* WalkTNodeTreeAction.Destroy */) {
  12968. ngDevMode && ngDevMode.rendererDestroyNode++;
  12969. renderer.destroyNode(rNode);
  12970. }
  12971. if (lContainer != null) {
  12972. applyContainer(renderer, action, lContainer, parent, beforeNode);
  12973. }
  12974. }
  12975. }
  12976. /**
  12977. * Removes all DOM elements associated with a view.
  12978. *
  12979. * Because some root nodes of the view may be containers, we sometimes need
  12980. * to propagate deeply into the nested containers to remove all elements in the
  12981. * views beneath it.
  12982. *
  12983. * @param tView The `TView' of the `LView` from which elements should be added or removed
  12984. * @param lView The view from which elements should be added or removed
  12985. */
  12986. function removeViewFromDOM(tView, lView) {
  12987. detachViewFromDOM(tView, lView);
  12988. lView[HOST] = null;
  12989. lView[T_HOST] = null;
  12990. }
  12991. /**
  12992. * Adds all DOM elements associated with a view.
  12993. *
  12994. * Because some root nodes of the view may be containers, we sometimes need
  12995. * to propagate deeply into the nested containers to add all elements in the
  12996. * views beneath it.
  12997. *
  12998. * @param tView The `TView' of the `LView` from which elements should be added or removed
  12999. * @param parentTNode The `TNode` where the `LView` should be attached to.
  13000. * @param renderer Current renderer to use for DOM manipulations.
  13001. * @param lView The view from which elements should be added or removed
  13002. * @param parentNativeNode The parent `RElement` where it should be inserted into.
  13003. * @param beforeNode The node before which elements should be added, if insert mode
  13004. */
  13005. function addViewToDOM(tView, parentTNode, renderer, lView, parentNativeNode, beforeNode) {
  13006. lView[HOST] = parentNativeNode;
  13007. lView[T_HOST] = parentTNode;
  13008. applyView(tView, lView, renderer, 1 /* WalkTNodeTreeAction.Insert */, parentNativeNode, beforeNode);
  13009. }
  13010. /**
  13011. * Detach a `LView` from the DOM by detaching its nodes.
  13012. *
  13013. * @param tView The `TView' of the `LView` to be detached
  13014. * @param lView the `LView` to be detached.
  13015. */
  13016. function detachViewFromDOM(tView, lView) {
  13017. // When we remove a view from the DOM, we need to rerun afterRender hooks
  13018. // We don't necessarily needs to run change detection. DOM removal only requires
  13019. // change detection if animations are enabled (this notification is handled by animations).
  13020. lView[ENVIRONMENT].changeDetectionScheduler?.notify(9 /* NotificationSource.ViewDetachedFromDOM */);
  13021. applyView(tView, lView, lView[RENDERER], 2 /* WalkTNodeTreeAction.Detach */, null, null);
  13022. }
  13023. /**
  13024. * Traverses down and up the tree of views and containers to remove listeners and
  13025. * call onDestroy callbacks.
  13026. *
  13027. * Notes:
  13028. * - Because it's used for onDestroy calls, it needs to be bottom-up.
  13029. * - Must process containers instead of their views to avoid splicing
  13030. * when views are destroyed and re-added.
  13031. * - Using a while loop because it's faster than recursion
  13032. * - Destroy only called on movement to sibling or movement to parent (laterally or up)
  13033. *
  13034. * @param rootView The view to destroy
  13035. */
  13036. function destroyViewTree(rootView) {
  13037. // If the view has no children, we can clean it up and return early.
  13038. let lViewOrLContainer = rootView[CHILD_HEAD];
  13039. if (!lViewOrLContainer) {
  13040. return cleanUpView(rootView[TVIEW], rootView);
  13041. }
  13042. while (lViewOrLContainer) {
  13043. let next = null;
  13044. if (isLView(lViewOrLContainer)) {
  13045. // If LView, traverse down to child.
  13046. next = lViewOrLContainer[CHILD_HEAD];
  13047. }
  13048. else {
  13049. ngDevMode && assertLContainer(lViewOrLContainer);
  13050. // If container, traverse down to its first LView.
  13051. const firstView = lViewOrLContainer[CONTAINER_HEADER_OFFSET];
  13052. if (firstView)
  13053. next = firstView;
  13054. }
  13055. if (!next) {
  13056. // Only clean up view when moving to the side or up, as destroy hooks
  13057. // should be called in order from the bottom up.
  13058. while (lViewOrLContainer && !lViewOrLContainer[NEXT] && lViewOrLContainer !== rootView) {
  13059. if (isLView(lViewOrLContainer)) {
  13060. cleanUpView(lViewOrLContainer[TVIEW], lViewOrLContainer);
  13061. }
  13062. lViewOrLContainer = lViewOrLContainer[PARENT];
  13063. }
  13064. if (lViewOrLContainer === null)
  13065. lViewOrLContainer = rootView;
  13066. if (isLView(lViewOrLContainer)) {
  13067. cleanUpView(lViewOrLContainer[TVIEW], lViewOrLContainer);
  13068. }
  13069. next = lViewOrLContainer && lViewOrLContainer[NEXT];
  13070. }
  13071. lViewOrLContainer = next;
  13072. }
  13073. }
  13074. function detachMovedView(declarationContainer, lView) {
  13075. ngDevMode && assertLContainer(declarationContainer);
  13076. ngDevMode &&
  13077. assertDefined(declarationContainer[MOVED_VIEWS], 'A projected view should belong to a non-empty projected views collection');
  13078. const movedViews = declarationContainer[MOVED_VIEWS];
  13079. const declarationViewIndex = movedViews.indexOf(lView);
  13080. movedViews.splice(declarationViewIndex, 1);
  13081. }
  13082. /**
  13083. * A standalone function which destroys an LView,
  13084. * conducting clean up (e.g. removing listeners, calling onDestroys).
  13085. *
  13086. * @param tView The `TView' of the `LView` to be destroyed
  13087. * @param lView The view to be destroyed.
  13088. */
  13089. function destroyLView(tView, lView) {
  13090. if (isDestroyed(lView)) {
  13091. return;
  13092. }
  13093. const renderer = lView[RENDERER];
  13094. if (renderer.destroyNode) {
  13095. applyView(tView, lView, renderer, 3 /* WalkTNodeTreeAction.Destroy */, null, null);
  13096. }
  13097. destroyViewTree(lView);
  13098. }
  13099. /**
  13100. * Calls onDestroys hooks for all directives and pipes in a given view and then removes all
  13101. * listeners. Listeners are removed as the last step so events delivered in the onDestroys hooks
  13102. * can be propagated to @Output listeners.
  13103. *
  13104. * @param tView `TView` for the `LView` to clean up.
  13105. * @param lView The LView to clean up
  13106. */
  13107. function cleanUpView(tView, lView) {
  13108. if (isDestroyed(lView)) {
  13109. return;
  13110. }
  13111. const prevConsumer = setActiveConsumer$1(null);
  13112. try {
  13113. // Usually the Attached flag is removed when the view is detached from its parent, however
  13114. // if it's a root view, the flag won't be unset hence why we're also removing on destroy.
  13115. lView[FLAGS] &= ~128 /* LViewFlags.Attached */;
  13116. // Mark the LView as destroyed *before* executing the onDestroy hooks. An onDestroy hook
  13117. // runs arbitrary user code, which could include its own `viewRef.destroy()` (or similar). If
  13118. // We don't flag the view as destroyed before the hooks, this could lead to an infinite loop.
  13119. // This also aligns with the ViewEngine behavior. It also means that the onDestroy hook is
  13120. // really more of an "afterDestroy" hook if you think about it.
  13121. lView[FLAGS] |= 256 /* LViewFlags.Destroyed */;
  13122. lView[REACTIVE_TEMPLATE_CONSUMER] && consumerDestroy(lView[REACTIVE_TEMPLATE_CONSUMER]);
  13123. executeOnDestroys(tView, lView);
  13124. processCleanups(tView, lView);
  13125. // For component views only, the local renderer is destroyed at clean up time.
  13126. if (lView[TVIEW].type === 1 /* TViewType.Component */) {
  13127. ngDevMode && ngDevMode.rendererDestroy++;
  13128. lView[RENDERER].destroy();
  13129. }
  13130. const declarationContainer = lView[DECLARATION_LCONTAINER];
  13131. // we are dealing with an embedded view that is still inserted into a container
  13132. if (declarationContainer !== null && isLContainer(lView[PARENT])) {
  13133. // and this is a projected view
  13134. if (declarationContainer !== lView[PARENT]) {
  13135. detachMovedView(declarationContainer, lView);
  13136. }
  13137. // For embedded views still attached to a container: remove query result from this view.
  13138. const lQueries = lView[QUERIES];
  13139. if (lQueries !== null) {
  13140. lQueries.detachView(tView);
  13141. }
  13142. }
  13143. // Unregister the view once everything else has been cleaned up.
  13144. unregisterLView(lView);
  13145. }
  13146. finally {
  13147. setActiveConsumer$1(prevConsumer);
  13148. }
  13149. }
  13150. /** Removes listeners and unsubscribes from output subscriptions */
  13151. function processCleanups(tView, lView) {
  13152. ngDevMode && assertNotReactive(processCleanups.name);
  13153. const tCleanup = tView.cleanup;
  13154. const lCleanup = lView[CLEANUP];
  13155. if (tCleanup !== null) {
  13156. for (let i = 0; i < tCleanup.length - 1; i += 2) {
  13157. if (typeof tCleanup[i] === 'string') {
  13158. // This is a native DOM listener. It will occupy 4 entries in the TCleanup array (hence i +=
  13159. // 2 at the end of this block).
  13160. const targetIdx = tCleanup[i + 3];
  13161. ngDevMode && assertNumber(targetIdx, 'cleanup target must be a number');
  13162. if (targetIdx >= 0) {
  13163. // Destroy anything whose teardown is a function call (e.g. QueryList, ModelSignal).
  13164. lCleanup[targetIdx]();
  13165. }
  13166. else {
  13167. // Subscription
  13168. lCleanup[-targetIdx].unsubscribe();
  13169. }
  13170. i += 2;
  13171. }
  13172. else {
  13173. // This is a cleanup function that is grouped with the index of its context
  13174. const context = lCleanup[tCleanup[i + 1]];
  13175. tCleanup[i].call(context);
  13176. }
  13177. }
  13178. }
  13179. if (lCleanup !== null) {
  13180. lView[CLEANUP] = null;
  13181. }
  13182. const destroyHooks = lView[ON_DESTROY_HOOKS];
  13183. if (destroyHooks !== null) {
  13184. // Reset the ON_DESTROY_HOOKS array before iterating over it to prevent hooks that unregister
  13185. // themselves from mutating the array during iteration.
  13186. lView[ON_DESTROY_HOOKS] = null;
  13187. for (let i = 0; i < destroyHooks.length; i++) {
  13188. const destroyHooksFn = destroyHooks[i];
  13189. ngDevMode && assertFunction(destroyHooksFn, 'Expecting destroy hook to be a function.');
  13190. destroyHooksFn();
  13191. }
  13192. }
  13193. // Destroy effects registered to the view. Many of these will have been processed above.
  13194. const effects = lView[EFFECTS];
  13195. if (effects !== null) {
  13196. lView[EFFECTS] = null;
  13197. for (const effect of effects) {
  13198. effect.destroy();
  13199. }
  13200. }
  13201. }
  13202. /** Calls onDestroy hooks for this view */
  13203. function executeOnDestroys(tView, lView) {
  13204. ngDevMode && assertNotReactive(executeOnDestroys.name);
  13205. let destroyHooks;
  13206. if (tView != null && (destroyHooks = tView.destroyHooks) != null) {
  13207. for (let i = 0; i < destroyHooks.length; i += 2) {
  13208. const context = lView[destroyHooks[i]];
  13209. // Only call the destroy hook if the context has been requested.
  13210. if (!(context instanceof NodeInjectorFactory)) {
  13211. const toCall = destroyHooks[i + 1];
  13212. if (Array.isArray(toCall)) {
  13213. for (let j = 0; j < toCall.length; j += 2) {
  13214. const callContext = context[toCall[j]];
  13215. const hook = toCall[j + 1];
  13216. profiler(4 /* ProfilerEvent.LifecycleHookStart */, callContext, hook);
  13217. try {
  13218. hook.call(callContext);
  13219. }
  13220. finally {
  13221. profiler(5 /* ProfilerEvent.LifecycleHookEnd */, callContext, hook);
  13222. }
  13223. }
  13224. }
  13225. else {
  13226. profiler(4 /* ProfilerEvent.LifecycleHookStart */, context, toCall);
  13227. try {
  13228. toCall.call(context);
  13229. }
  13230. finally {
  13231. profiler(5 /* ProfilerEvent.LifecycleHookEnd */, context, toCall);
  13232. }
  13233. }
  13234. }
  13235. }
  13236. }
  13237. }
  13238. /**
  13239. * Returns a native element if a node can be inserted into the given parent.
  13240. *
  13241. * There are two reasons why we may not be able to insert a element immediately.
  13242. * - Projection: When creating a child content element of a component, we have to skip the
  13243. * insertion because the content of a component will be projected.
  13244. * `<component><content>delayed due to projection</content></component>`
  13245. * - Parent container is disconnected: This can happen when we are inserting a view into
  13246. * parent container, which itself is disconnected. For example the parent container is part
  13247. * of a View which has not be inserted or is made for projection but has not been inserted
  13248. * into destination.
  13249. *
  13250. * @param tView: Current `TView`.
  13251. * @param tNode: `TNode` for which we wish to retrieve render parent.
  13252. * @param lView: Current `LView`.
  13253. */
  13254. function getParentRElement(tView, tNode, lView) {
  13255. return getClosestRElement(tView, tNode.parent, lView);
  13256. }
  13257. /**
  13258. * Get closest `RElement` or `null` if it can't be found.
  13259. *
  13260. * If `TNode` is `TNodeType.Element` => return `RElement` at `LView[tNode.index]` location.
  13261. * If `TNode` is `TNodeType.ElementContainer|IcuContain` => return the parent (recursively).
  13262. * If `TNode` is `null` then return host `RElement`:
  13263. * - return `null` if projection
  13264. * - return `null` if parent container is disconnected (we have no parent.)
  13265. *
  13266. * @param tView: Current `TView`.
  13267. * @param tNode: `TNode` for which we wish to retrieve `RElement` (or `null` if host element is
  13268. * needed).
  13269. * @param lView: Current `LView`.
  13270. * @returns `null` if the `RElement` can't be determined at this time (no parent / projection)
  13271. */
  13272. function getClosestRElement(tView, tNode, lView) {
  13273. let parentTNode = tNode;
  13274. // Skip over element and ICU containers as those are represented by a comment node and
  13275. // can't be used as a render parent. Also skip let declarations since they don't have a
  13276. // corresponding DOM node at all.
  13277. while (parentTNode !== null &&
  13278. parentTNode.type & (8 /* TNodeType.ElementContainer */ | 32 /* TNodeType.Icu */ | 128 /* TNodeType.LetDeclaration */)) {
  13279. tNode = parentTNode;
  13280. parentTNode = tNode.parent;
  13281. }
  13282. // If the parent tNode is null, then we are inserting across views: either into an embedded view
  13283. // or a component view.
  13284. if (parentTNode === null) {
  13285. // We are inserting a root element of the component view into the component host element and
  13286. // it should always be eager.
  13287. return lView[HOST];
  13288. }
  13289. else {
  13290. ngDevMode && assertTNodeType(parentTNode, 3 /* TNodeType.AnyRNode */ | 4 /* TNodeType.Container */);
  13291. if (isComponentHost(parentTNode)) {
  13292. ngDevMode && assertTNodeForLView(parentTNode, lView);
  13293. const { encapsulation } = tView.data[parentTNode.directiveStart + parentTNode.componentOffset];
  13294. // We've got a parent which is an element in the current view. We just need to verify if the
  13295. // parent element is not a component. Component's content nodes are not inserted immediately
  13296. // because they will be projected, and so doing insert at this point would be wasteful.
  13297. // Since the projection would then move it to its final destination. Note that we can't
  13298. // make this assumption when using the Shadow DOM, because the native projection placeholders
  13299. // (<content> or <slot>) have to be in place as elements are being inserted.
  13300. if (encapsulation === ViewEncapsulation.None ||
  13301. encapsulation === ViewEncapsulation.Emulated) {
  13302. return null;
  13303. }
  13304. }
  13305. return getNativeByTNode(parentTNode, lView);
  13306. }
  13307. }
  13308. /**
  13309. * Find a node in front of which `currentTNode` should be inserted.
  13310. *
  13311. * This method determines the `RNode` in front of which we should insert the `currentRNode`. This
  13312. * takes `TNode.insertBeforeIndex` into account if i18n code has been invoked.
  13313. *
  13314. * @param parentTNode parent `TNode`
  13315. * @param currentTNode current `TNode` (The node which we would like to insert into the DOM)
  13316. * @param lView current `LView`
  13317. */
  13318. function getInsertInFrontOfRNode(parentTNode, currentTNode, lView) {
  13319. return _getInsertInFrontOfRNodeWithI18n(parentTNode, currentTNode, lView);
  13320. }
  13321. /**
  13322. * Find a node in front of which `currentTNode` should be inserted. (Does not take i18n into
  13323. * account)
  13324. *
  13325. * This method determines the `RNode` in front of which we should insert the `currentRNode`. This
  13326. * does not take `TNode.insertBeforeIndex` into account.
  13327. *
  13328. * @param parentTNode parent `TNode`
  13329. * @param currentTNode current `TNode` (The node which we would like to insert into the DOM)
  13330. * @param lView current `LView`
  13331. */
  13332. function getInsertInFrontOfRNodeWithNoI18n(parentTNode, currentTNode, lView) {
  13333. if (parentTNode.type & (8 /* TNodeType.ElementContainer */ | 32 /* TNodeType.Icu */)) {
  13334. return getNativeByTNode(parentTNode, lView);
  13335. }
  13336. return null;
  13337. }
  13338. /**
  13339. * Tree shakable boundary for `getInsertInFrontOfRNodeWithI18n` function.
  13340. *
  13341. * This function will only be set if i18n code runs.
  13342. */
  13343. let _getInsertInFrontOfRNodeWithI18n = getInsertInFrontOfRNodeWithNoI18n;
  13344. /**
  13345. * Tree shakable boundary for `processI18nInsertBefore` function.
  13346. *
  13347. * This function will only be set if i18n code runs.
  13348. */
  13349. let _processI18nInsertBefore;
  13350. function setI18nHandling(getInsertInFrontOfRNodeWithI18n, processI18nInsertBefore) {
  13351. _getInsertInFrontOfRNodeWithI18n = getInsertInFrontOfRNodeWithI18n;
  13352. _processI18nInsertBefore = processI18nInsertBefore;
  13353. }
  13354. /**
  13355. * Appends the `child` native node (or a collection of nodes) to the `parent`.
  13356. *
  13357. * @param tView The `TView' to be appended
  13358. * @param lView The current LView
  13359. * @param childRNode The native child (or children) that should be appended
  13360. * @param childTNode The TNode of the child element
  13361. */
  13362. function appendChild(tView, lView, childRNode, childTNode) {
  13363. const parentRNode = getParentRElement(tView, childTNode, lView);
  13364. const renderer = lView[RENDERER];
  13365. const parentTNode = childTNode.parent || lView[T_HOST];
  13366. const anchorNode = getInsertInFrontOfRNode(parentTNode, childTNode, lView);
  13367. if (parentRNode != null) {
  13368. if (Array.isArray(childRNode)) {
  13369. for (let i = 0; i < childRNode.length; i++) {
  13370. nativeAppendOrInsertBefore(renderer, parentRNode, childRNode[i], anchorNode, false);
  13371. }
  13372. }
  13373. else {
  13374. nativeAppendOrInsertBefore(renderer, parentRNode, childRNode, anchorNode, false);
  13375. }
  13376. }
  13377. _processI18nInsertBefore !== undefined &&
  13378. _processI18nInsertBefore(renderer, childTNode, lView, childRNode, parentRNode);
  13379. }
  13380. /**
  13381. * Returns the first native node for a given LView, starting from the provided TNode.
  13382. *
  13383. * Native nodes are returned in the order in which those appear in the native tree (DOM).
  13384. */
  13385. function getFirstNativeNode(lView, tNode) {
  13386. if (tNode !== null) {
  13387. ngDevMode &&
  13388. assertTNodeType(tNode, 3 /* TNodeType.AnyRNode */ |
  13389. 12 /* TNodeType.AnyContainer */ |
  13390. 32 /* TNodeType.Icu */ |
  13391. 16 /* TNodeType.Projection */ |
  13392. 128 /* TNodeType.LetDeclaration */);
  13393. const tNodeType = tNode.type;
  13394. if (tNodeType & 3 /* TNodeType.AnyRNode */) {
  13395. return getNativeByTNode(tNode, lView);
  13396. }
  13397. else if (tNodeType & 4 /* TNodeType.Container */) {
  13398. return getBeforeNodeForView(-1, lView[tNode.index]);
  13399. }
  13400. else if (tNodeType & 8 /* TNodeType.ElementContainer */) {
  13401. const elIcuContainerChild = tNode.child;
  13402. if (elIcuContainerChild !== null) {
  13403. return getFirstNativeNode(lView, elIcuContainerChild);
  13404. }
  13405. else {
  13406. const rNodeOrLContainer = lView[tNode.index];
  13407. if (isLContainer(rNodeOrLContainer)) {
  13408. return getBeforeNodeForView(-1, rNodeOrLContainer);
  13409. }
  13410. else {
  13411. return unwrapRNode(rNodeOrLContainer);
  13412. }
  13413. }
  13414. }
  13415. else if (tNodeType & 128 /* TNodeType.LetDeclaration */) {
  13416. return getFirstNativeNode(lView, tNode.next);
  13417. }
  13418. else if (tNodeType & 32 /* TNodeType.Icu */) {
  13419. let nextRNode = icuContainerIterate(tNode, lView);
  13420. let rNode = nextRNode();
  13421. // If the ICU container has no nodes, than we use the ICU anchor as the node.
  13422. return rNode || unwrapRNode(lView[tNode.index]);
  13423. }
  13424. else {
  13425. const projectionNodes = getProjectionNodes(lView, tNode);
  13426. if (projectionNodes !== null) {
  13427. if (Array.isArray(projectionNodes)) {
  13428. return projectionNodes[0];
  13429. }
  13430. const parentView = getLViewParent(lView[DECLARATION_COMPONENT_VIEW]);
  13431. ngDevMode && assertParentView(parentView);
  13432. return getFirstNativeNode(parentView, projectionNodes);
  13433. }
  13434. else {
  13435. return getFirstNativeNode(lView, tNode.next);
  13436. }
  13437. }
  13438. }
  13439. return null;
  13440. }
  13441. function getProjectionNodes(lView, tNode) {
  13442. if (tNode !== null) {
  13443. const componentView = lView[DECLARATION_COMPONENT_VIEW];
  13444. const componentHost = componentView[T_HOST];
  13445. const slotIdx = tNode.projection;
  13446. ngDevMode && assertProjectionSlots(lView);
  13447. return componentHost.projection[slotIdx];
  13448. }
  13449. return null;
  13450. }
  13451. function getBeforeNodeForView(viewIndexInContainer, lContainer) {
  13452. const nextViewIndex = CONTAINER_HEADER_OFFSET + viewIndexInContainer + 1;
  13453. if (nextViewIndex < lContainer.length) {
  13454. const lView = lContainer[nextViewIndex];
  13455. const firstTNodeOfView = lView[TVIEW].firstChild;
  13456. if (firstTNodeOfView !== null) {
  13457. return getFirstNativeNode(lView, firstTNodeOfView);
  13458. }
  13459. }
  13460. return lContainer[NATIVE];
  13461. }
  13462. /**
  13463. * Performs the operation of `action` on the node. Typically this involves inserting or removing
  13464. * nodes on the LView or projection boundary.
  13465. */
  13466. function applyNodes(renderer, action, tNode, lView, parentRElement, beforeNode, isProjection) {
  13467. while (tNode != null) {
  13468. ngDevMode && assertTNodeForLView(tNode, lView);
  13469. // Let declarations don't have corresponding DOM nodes so we skip over them.
  13470. if (tNode.type === 128 /* TNodeType.LetDeclaration */) {
  13471. tNode = tNode.next;
  13472. continue;
  13473. }
  13474. ngDevMode &&
  13475. assertTNodeType(tNode, 3 /* TNodeType.AnyRNode */ | 12 /* TNodeType.AnyContainer */ | 16 /* TNodeType.Projection */ | 32 /* TNodeType.Icu */);
  13476. const rawSlotValue = lView[tNode.index];
  13477. const tNodeType = tNode.type;
  13478. if (isProjection) {
  13479. if (action === 0 /* WalkTNodeTreeAction.Create */) {
  13480. rawSlotValue && attachPatchData(unwrapRNode(rawSlotValue), lView);
  13481. tNode.flags |= 2 /* TNodeFlags.isProjected */;
  13482. }
  13483. }
  13484. if (!isDetachedByI18n(tNode)) {
  13485. if (tNodeType & 8 /* TNodeType.ElementContainer */) {
  13486. applyNodes(renderer, action, tNode.child, lView, parentRElement, beforeNode, false);
  13487. applyToElementOrContainer(action, renderer, parentRElement, rawSlotValue, beforeNode);
  13488. }
  13489. else if (tNodeType & 32 /* TNodeType.Icu */) {
  13490. const nextRNode = icuContainerIterate(tNode, lView);
  13491. let rNode;
  13492. while ((rNode = nextRNode())) {
  13493. applyToElementOrContainer(action, renderer, parentRElement, rNode, beforeNode);
  13494. }
  13495. applyToElementOrContainer(action, renderer, parentRElement, rawSlotValue, beforeNode);
  13496. }
  13497. else if (tNodeType & 16 /* TNodeType.Projection */) {
  13498. applyProjectionRecursive(renderer, action, lView, tNode, parentRElement, beforeNode);
  13499. }
  13500. else {
  13501. ngDevMode && assertTNodeType(tNode, 3 /* TNodeType.AnyRNode */ | 4 /* TNodeType.Container */);
  13502. applyToElementOrContainer(action, renderer, parentRElement, rawSlotValue, beforeNode);
  13503. }
  13504. }
  13505. tNode = isProjection ? tNode.projectionNext : tNode.next;
  13506. }
  13507. }
  13508. function applyView(tView, lView, renderer, action, parentRElement, beforeNode) {
  13509. applyNodes(renderer, action, tView.firstChild, lView, parentRElement, beforeNode, false);
  13510. }
  13511. /**
  13512. * `applyProjection` performs operation on the projection.
  13513. *
  13514. * Inserting a projection requires us to locate the projected nodes from the parent component. The
  13515. * complication is that those nodes themselves could be re-projected from their parent component.
  13516. *
  13517. * @param tView The `TView` of `LView` which needs to be inserted, detached, destroyed
  13518. * @param lView The `LView` which needs to be inserted, detached, destroyed.
  13519. * @param tProjectionNode node to project
  13520. */
  13521. function applyProjection(tView, lView, tProjectionNode) {
  13522. const renderer = lView[RENDERER];
  13523. const parentRNode = getParentRElement(tView, tProjectionNode, lView);
  13524. const parentTNode = tProjectionNode.parent || lView[T_HOST];
  13525. let beforeNode = getInsertInFrontOfRNode(parentTNode, tProjectionNode, lView);
  13526. applyProjectionRecursive(renderer, 0 /* WalkTNodeTreeAction.Create */, lView, tProjectionNode, parentRNode, beforeNode);
  13527. }
  13528. /**
  13529. * `applyProjectionRecursive` performs operation on the projection specified by `action` (insert,
  13530. * detach, destroy)
  13531. *
  13532. * Inserting a projection requires us to locate the projected nodes from the parent component. The
  13533. * complication is that those nodes themselves could be re-projected from their parent component.
  13534. *
  13535. * @param renderer Render to use
  13536. * @param action action to perform (insert, detach, destroy)
  13537. * @param lView The LView which needs to be inserted, detached, destroyed.
  13538. * @param tProjectionNode node to project
  13539. * @param parentRElement parent DOM element for insertion/removal.
  13540. * @param beforeNode Before which node the insertions should happen.
  13541. */
  13542. function applyProjectionRecursive(renderer, action, lView, tProjectionNode, parentRElement, beforeNode) {
  13543. const componentLView = lView[DECLARATION_COMPONENT_VIEW];
  13544. const componentNode = componentLView[T_HOST];
  13545. ngDevMode &&
  13546. assertEqual(typeof tProjectionNode.projection, 'number', 'expecting projection index');
  13547. const nodeToProjectOrRNodes = componentNode.projection[tProjectionNode.projection];
  13548. if (Array.isArray(nodeToProjectOrRNodes)) {
  13549. // This should not exist, it is a bit of a hack. When we bootstrap a top level node and we
  13550. // need to support passing projectable nodes, so we cheat and put them in the TNode
  13551. // of the Host TView. (Yes we put instance info at the T Level). We can get away with it
  13552. // because we know that TView is not shared and therefore it will not be a problem.
  13553. // This should be refactored and cleaned up.
  13554. for (let i = 0; i < nodeToProjectOrRNodes.length; i++) {
  13555. const rNode = nodeToProjectOrRNodes[i];
  13556. applyToElementOrContainer(action, renderer, parentRElement, rNode, beforeNode);
  13557. }
  13558. }
  13559. else {
  13560. let nodeToProject = nodeToProjectOrRNodes;
  13561. const projectedComponentLView = componentLView[PARENT];
  13562. // If a parent <ng-content> is located within a skip hydration block,
  13563. // annotate an actual node that is being projected with the same flag too.
  13564. if (hasInSkipHydrationBlockFlag(tProjectionNode)) {
  13565. nodeToProject.flags |= 128 /* TNodeFlags.inSkipHydrationBlock */;
  13566. }
  13567. applyNodes(renderer, action, nodeToProject, projectedComponentLView, parentRElement, beforeNode, true);
  13568. }
  13569. }
  13570. /**
  13571. * `applyContainer` performs an operation on the container and its views as specified by
  13572. * `action` (insert, detach, destroy)
  13573. *
  13574. * Inserting a Container is complicated by the fact that the container may have Views which
  13575. * themselves have containers or projections.
  13576. *
  13577. * @param renderer Renderer to use
  13578. * @param action action to perform (insert, detach, destroy)
  13579. * @param lContainer The LContainer which needs to be inserted, detached, destroyed.
  13580. * @param parentRElement parent DOM element for insertion/removal.
  13581. * @param beforeNode Before which node the insertions should happen.
  13582. */
  13583. function applyContainer(renderer, action, lContainer, parentRElement, beforeNode) {
  13584. ngDevMode && assertLContainer(lContainer);
  13585. const anchor = lContainer[NATIVE]; // LContainer has its own before node.
  13586. const native = unwrapRNode(lContainer);
  13587. // An LContainer can be created dynamically on any node by injecting ViewContainerRef.
  13588. // Asking for a ViewContainerRef on an element will result in a creation of a separate anchor
  13589. // node (comment in the DOM) that will be different from the LContainer's host node. In this
  13590. // particular case we need to execute action on 2 nodes:
  13591. // - container's host node (this is done in the executeActionOnElementOrContainer)
  13592. // - container's host node (this is done here)
  13593. if (anchor !== native) {
  13594. // This is very strange to me (Misko). I would expect that the native is same as anchor. I
  13595. // don't see a reason why they should be different, but they are.
  13596. //
  13597. // If they are we need to process the second anchor as well.
  13598. applyToElementOrContainer(action, renderer, parentRElement, anchor, beforeNode);
  13599. }
  13600. for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
  13601. const lView = lContainer[i];
  13602. applyView(lView[TVIEW], lView, renderer, action, parentRElement, anchor);
  13603. }
  13604. }
  13605. /**
  13606. * Writes class/style to element.
  13607. *
  13608. * @param renderer Renderer to use.
  13609. * @param isClassBased `true` if it should be written to `class` (`false` to write to `style`)
  13610. * @param rNode The Node to write to.
  13611. * @param prop Property to write to. This would be the class/style name.
  13612. * @param value Value to write. If `null`/`undefined`/`false` this is considered a remove (set/add
  13613. * otherwise).
  13614. */
  13615. function applyStyling(renderer, isClassBased, rNode, prop, value) {
  13616. if (isClassBased) {
  13617. // We actually want JS true/false here because any truthy value should add the class
  13618. if (!value) {
  13619. ngDevMode && ngDevMode.rendererRemoveClass++;
  13620. renderer.removeClass(rNode, prop);
  13621. }
  13622. else {
  13623. ngDevMode && ngDevMode.rendererAddClass++;
  13624. renderer.addClass(rNode, prop);
  13625. }
  13626. }
  13627. else {
  13628. let flags = prop.indexOf('-') === -1 ? undefined : RendererStyleFlags2.DashCase;
  13629. if (value == null /** || value === undefined */) {
  13630. ngDevMode && ngDevMode.rendererRemoveStyle++;
  13631. renderer.removeStyle(rNode, prop, flags);
  13632. }
  13633. else {
  13634. // A value is important if it ends with `!important`. The style
  13635. // parser strips any semicolons at the end of the value.
  13636. const isImportant = typeof value === 'string' ? value.endsWith('!important') : false;
  13637. if (isImportant) {
  13638. // !important has to be stripped from the value for it to be valid.
  13639. value = value.slice(0, -10);
  13640. flags |= RendererStyleFlags2.Important;
  13641. }
  13642. ngDevMode && ngDevMode.rendererSetStyle++;
  13643. renderer.setStyle(rNode, prop, value, flags);
  13644. }
  13645. }
  13646. }
  13647. function collectNativeNodes(tView, lView, tNode, result, isProjection = false) {
  13648. while (tNode !== null) {
  13649. // Let declarations don't have corresponding DOM nodes so we skip over them.
  13650. if (tNode.type === 128 /* TNodeType.LetDeclaration */) {
  13651. tNode = isProjection ? tNode.projectionNext : tNode.next;
  13652. continue;
  13653. }
  13654. ngDevMode &&
  13655. assertTNodeType(tNode, 3 /* TNodeType.AnyRNode */ | 12 /* TNodeType.AnyContainer */ | 16 /* TNodeType.Projection */ | 32 /* TNodeType.Icu */);
  13656. const lNode = lView[tNode.index];
  13657. if (lNode !== null) {
  13658. result.push(unwrapRNode(lNode));
  13659. }
  13660. // A given lNode can represent either a native node or a LContainer (when it is a host of a
  13661. // ViewContainerRef). When we find a LContainer we need to descend into it to collect root nodes
  13662. // from the views in this container.
  13663. if (isLContainer(lNode)) {
  13664. collectNativeNodesInLContainer(lNode, result);
  13665. }
  13666. const tNodeType = tNode.type;
  13667. if (tNodeType & 8 /* TNodeType.ElementContainer */) {
  13668. collectNativeNodes(tView, lView, tNode.child, result);
  13669. }
  13670. else if (tNodeType & 32 /* TNodeType.Icu */) {
  13671. const nextRNode = icuContainerIterate(tNode, lView);
  13672. let rNode;
  13673. while ((rNode = nextRNode())) {
  13674. result.push(rNode);
  13675. }
  13676. }
  13677. else if (tNodeType & 16 /* TNodeType.Projection */) {
  13678. const nodesInSlot = getProjectionNodes(lView, tNode);
  13679. if (Array.isArray(nodesInSlot)) {
  13680. result.push(...nodesInSlot);
  13681. }
  13682. else {
  13683. const parentView = getLViewParent(lView[DECLARATION_COMPONENT_VIEW]);
  13684. ngDevMode && assertParentView(parentView);
  13685. collectNativeNodes(parentView[TVIEW], parentView, nodesInSlot, result, true);
  13686. }
  13687. }
  13688. tNode = isProjection ? tNode.projectionNext : tNode.next;
  13689. }
  13690. return result;
  13691. }
  13692. /**
  13693. * Collects all root nodes in all views in a given LContainer.
  13694. */
  13695. function collectNativeNodesInLContainer(lContainer, result) {
  13696. for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
  13697. const lViewInAContainer = lContainer[i];
  13698. const lViewFirstChildTNode = lViewInAContainer[TVIEW].firstChild;
  13699. if (lViewFirstChildTNode !== null) {
  13700. collectNativeNodes(lViewInAContainer[TVIEW], lViewInAContainer, lViewFirstChildTNode, result);
  13701. }
  13702. }
  13703. // When an LContainer is created, the anchor (comment) node is:
  13704. // - (1) either reused in case of an ElementContainer (<ng-container>)
  13705. // - (2) or a new comment node is created
  13706. // In the first case, the anchor comment node would be added to the final
  13707. // list by the code in the `collectNativeNodes` function
  13708. // (see the `result.push(unwrapRNode(lNode))` line), but the second
  13709. // case requires extra handling: the anchor node needs to be added to the
  13710. // final list manually. See additional information in the `createAnchorNode`
  13711. // function in the `view_container_ref.ts`.
  13712. //
  13713. // In the first case, the same reference would be stored in the `NATIVE`
  13714. // and `HOST` slots in an LContainer. Otherwise, this is the second case and
  13715. // we should add an element to the final list.
  13716. if (lContainer[NATIVE] !== lContainer[HOST]) {
  13717. result.push(lContainer[NATIVE]);
  13718. }
  13719. }
  13720. function addAfterRenderSequencesForView(lView) {
  13721. if (lView[AFTER_RENDER_SEQUENCES_TO_ADD] !== null) {
  13722. for (const sequence of lView[AFTER_RENDER_SEQUENCES_TO_ADD]) {
  13723. sequence.impl.addSequence(sequence);
  13724. }
  13725. lView[AFTER_RENDER_SEQUENCES_TO_ADD].length = 0;
  13726. }
  13727. }
  13728. let freeConsumers = [];
  13729. /**
  13730. * Create a new template consumer pointing at the specified LView.
  13731. * Sometimes, a previously created consumer may be reused, in order to save on allocations. In that
  13732. * case, the LView will be updated.
  13733. */
  13734. function getOrBorrowReactiveLViewConsumer(lView) {
  13735. return lView[REACTIVE_TEMPLATE_CONSUMER] ?? borrowReactiveLViewConsumer(lView);
  13736. }
  13737. function borrowReactiveLViewConsumer(lView) {
  13738. const consumer = freeConsumers.pop() ?? Object.create(REACTIVE_LVIEW_CONSUMER_NODE);
  13739. consumer.lView = lView;
  13740. return consumer;
  13741. }
  13742. function maybeReturnReactiveLViewConsumer(consumer) {
  13743. if (consumer.lView[REACTIVE_TEMPLATE_CONSUMER] === consumer) {
  13744. // The consumer got committed.
  13745. return;
  13746. }
  13747. consumer.lView = null;
  13748. freeConsumers.push(consumer);
  13749. }
  13750. const REACTIVE_LVIEW_CONSUMER_NODE = {
  13751. ...REACTIVE_NODE,
  13752. consumerIsAlwaysLive: true,
  13753. kind: 'template',
  13754. consumerMarkedDirty: (node) => {
  13755. markAncestorsForTraversal(node.lView);
  13756. },
  13757. consumerOnSignalRead() {
  13758. this.lView[REACTIVE_TEMPLATE_CONSUMER] = this;
  13759. },
  13760. };
  13761. /**
  13762. * Creates a temporary consumer for use with `LView`s that should not have consumers.
  13763. * If the LView already has a consumer, returns the existing one instead.
  13764. *
  13765. * This is necessary because some APIs may cause change detection directly on an LView
  13766. * that we do not want to have a consumer (Embedded views today). As a result, there
  13767. * would be no active consumer from running change detection on its host component
  13768. * and any signals in the LView template would be untracked. Instead, we create
  13769. * this temporary consumer that marks the first parent that _should_ have a consumer
  13770. * for refresh. Once change detection runs as part of that refresh, we throw away
  13771. * this consumer because its signals will then be tracked by the parent's consumer.
  13772. */
  13773. function getOrCreateTemporaryConsumer(lView) {
  13774. const consumer = lView[REACTIVE_TEMPLATE_CONSUMER] ?? Object.create(TEMPORARY_CONSUMER_NODE);
  13775. consumer.lView = lView;
  13776. return consumer;
  13777. }
  13778. const TEMPORARY_CONSUMER_NODE = {
  13779. ...REACTIVE_NODE,
  13780. consumerIsAlwaysLive: true,
  13781. kind: 'template',
  13782. consumerMarkedDirty: (node) => {
  13783. let parent = getLViewParent(node.lView);
  13784. while (parent && !viewShouldHaveReactiveConsumer(parent[TVIEW])) {
  13785. parent = getLViewParent(parent);
  13786. }
  13787. if (!parent) {
  13788. // If we can't find an appropriate parent that should have a consumer, we
  13789. // don't have a way of appropriately refreshing this LView as part of application synchronization.
  13790. return;
  13791. }
  13792. markViewForRefresh(parent);
  13793. },
  13794. consumerOnSignalRead() {
  13795. this.lView[REACTIVE_TEMPLATE_CONSUMER] = this;
  13796. },
  13797. };
  13798. /**
  13799. * Indicates if the view should get its own reactive consumer node.
  13800. *
  13801. * In the current design, all embedded views share a consumer with the component view. This allows
  13802. * us to refresh at the component level rather than at a per-view level. In addition, root views get
  13803. * their own reactive node because root component will have a host view that executes the
  13804. * component's host bindings. This needs to be tracked in a consumer as well.
  13805. *
  13806. * To get a more granular change detection than per-component, all we would just need to update the
  13807. * condition here so that a given view gets a reactive consumer which can become dirty independently
  13808. * from its parent component. For example embedded views for signal components could be created with
  13809. * a new type "SignalEmbeddedView" and the condition here wouldn't even need updating in order to
  13810. * get granular per-view change detection for signal components.
  13811. */
  13812. function viewShouldHaveReactiveConsumer(tView) {
  13813. return tView.type !== 2 /* TViewType.Embedded */;
  13814. }
  13815. function runEffectsInView(view) {
  13816. if (view[EFFECTS] === null) {
  13817. return;
  13818. }
  13819. // Since effects can make other effects dirty, we flush them in a loop until there are no more to
  13820. // flush.
  13821. let tryFlushEffects = true;
  13822. while (tryFlushEffects) {
  13823. let foundDirtyEffect = false;
  13824. for (const effect of view[EFFECTS]) {
  13825. if (!effect.dirty) {
  13826. continue;
  13827. }
  13828. foundDirtyEffect = true;
  13829. // `runEffectsInView` is called during change detection, and therefore runs
  13830. // in the Angular zone if it's available.
  13831. if (effect.zone === null || Zone.current === effect.zone) {
  13832. effect.run();
  13833. }
  13834. else {
  13835. effect.zone.run(() => effect.run());
  13836. }
  13837. }
  13838. // Check if we need to continue flushing. If we didn't find any dirty effects, then there's
  13839. // no need to loop back. Otherwise, check the view to see if it was marked for traversal
  13840. // again. If so, there's a chance that one of the effects we ran caused another effect to
  13841. // become dirty.
  13842. tryFlushEffects = foundDirtyEffect && !!(view[FLAGS] & 8192 /* LViewFlags.HasChildViewsToRefresh */);
  13843. }
  13844. }
  13845. /**
  13846. * The maximum number of times the change detection traversal will rerun before throwing an error.
  13847. */
  13848. const MAXIMUM_REFRESH_RERUNS$1 = 100;
  13849. function detectChangesInternal(lView, notifyErrorHandler = true, mode = 0 /* ChangeDetectionMode.Global */) {
  13850. const environment = lView[ENVIRONMENT];
  13851. const rendererFactory = environment.rendererFactory;
  13852. // Check no changes mode is a dev only mode used to verify that bindings have not changed
  13853. // since they were assigned. We do not want to invoke renderer factory functions in that mode
  13854. // to avoid any possible side-effects.
  13855. const checkNoChangesMode = !!ngDevMode && isInCheckNoChangesMode();
  13856. if (!checkNoChangesMode) {
  13857. rendererFactory.begin?.();
  13858. }
  13859. try {
  13860. detectChangesInViewWhileDirty(lView, mode);
  13861. }
  13862. catch (error) {
  13863. if (notifyErrorHandler) {
  13864. handleError$1(lView, error);
  13865. }
  13866. throw error;
  13867. }
  13868. finally {
  13869. if (!checkNoChangesMode) {
  13870. rendererFactory.end?.();
  13871. }
  13872. }
  13873. }
  13874. function detectChangesInViewWhileDirty(lView, mode) {
  13875. const lastIsRefreshingViewsValue = isRefreshingViews();
  13876. try {
  13877. setIsRefreshingViews(true);
  13878. detectChangesInView(lView, mode);
  13879. // We don't need or want to do any looping when in exhaustive checkNoChanges because we
  13880. // already traverse all the views and nothing should change so we shouldn't have to do
  13881. // another pass to pick up new changes.
  13882. if (ngDevMode && isExhaustiveCheckNoChanges()) {
  13883. return;
  13884. }
  13885. let retries = 0;
  13886. // If after running change detection, this view still needs to be refreshed or there are
  13887. // descendants views that need to be refreshed due to re-dirtying during the change detection
  13888. // run, detect changes on the view again. We run change detection in `Targeted` mode to only
  13889. // refresh views with the `RefreshView` flag.
  13890. while (requiresRefreshOrTraversal(lView)) {
  13891. if (retries === MAXIMUM_REFRESH_RERUNS$1) {
  13892. throw new RuntimeError(103 /* RuntimeErrorCode.INFINITE_CHANGE_DETECTION */, ngDevMode &&
  13893. 'Infinite change detection while trying to refresh views. ' +
  13894. 'There may be components which each cause the other to require a refresh, ' +
  13895. 'causing an infinite loop.');
  13896. }
  13897. retries++;
  13898. // Even if this view is detached, we still detect changes in targeted mode because this was
  13899. // the root of the change detection run.
  13900. detectChangesInView(lView, 1 /* ChangeDetectionMode.Targeted */);
  13901. }
  13902. }
  13903. finally {
  13904. // restore state to what it was before entering this change detection loop
  13905. setIsRefreshingViews(lastIsRefreshingViewsValue);
  13906. }
  13907. }
  13908. function checkNoChangesInternal(lView, mode, notifyErrorHandler = true) {
  13909. setIsInCheckNoChangesMode(mode);
  13910. try {
  13911. detectChangesInternal(lView, notifyErrorHandler);
  13912. }
  13913. finally {
  13914. setIsInCheckNoChangesMode(CheckNoChangesMode.Off);
  13915. }
  13916. }
  13917. /**
  13918. * Processes a view in update mode. This includes a number of steps in a specific order:
  13919. * - executing a template function in update mode;
  13920. * - executing hooks;
  13921. * - refreshing queries;
  13922. * - setting host bindings;
  13923. * - refreshing child (embedded and component) views.
  13924. */
  13925. function refreshView(tView, lView, templateFn, context) {
  13926. ngDevMode && assertEqual(isCreationMode(lView), false, 'Should be run in update mode');
  13927. if (isDestroyed(lView))
  13928. return;
  13929. const flags = lView[FLAGS];
  13930. // Check no changes mode is a dev only mode used to verify that bindings have not changed
  13931. // since they were assigned. We do not want to execute lifecycle hooks in that mode.
  13932. const isInCheckNoChangesPass = ngDevMode && isInCheckNoChangesMode();
  13933. const isInExhaustiveCheckNoChangesPass = ngDevMode && isExhaustiveCheckNoChanges();
  13934. // Start component reactive context
  13935. // - We might already be in a reactive context if this is an embedded view of the host.
  13936. // - We might be descending into a view that needs a consumer.
  13937. enterView(lView);
  13938. let returnConsumerToPool = true;
  13939. let prevConsumer = null;
  13940. let currentConsumer = null;
  13941. if (!isInCheckNoChangesPass) {
  13942. if (viewShouldHaveReactiveConsumer(tView)) {
  13943. currentConsumer = getOrBorrowReactiveLViewConsumer(lView);
  13944. prevConsumer = consumerBeforeComputation(currentConsumer);
  13945. }
  13946. else if (getActiveConsumer() === null) {
  13947. // If the current view should not have a reactive consumer but we don't have an active consumer,
  13948. // we still need to create a temporary consumer to track any signal reads in this template.
  13949. // This is a rare case that can happen with `viewContainerRef.createEmbeddedView(...).detectChanges()`.
  13950. // This temporary consumer marks the first parent that _should_ have a consumer for refresh.
  13951. // Once that refresh happens, the signals will be tracked in the parent consumer and we can destroy
  13952. // the temporary one.
  13953. returnConsumerToPool = false;
  13954. currentConsumer = getOrCreateTemporaryConsumer(lView);
  13955. prevConsumer = consumerBeforeComputation(currentConsumer);
  13956. }
  13957. else if (lView[REACTIVE_TEMPLATE_CONSUMER]) {
  13958. consumerDestroy(lView[REACTIVE_TEMPLATE_CONSUMER]);
  13959. lView[REACTIVE_TEMPLATE_CONSUMER] = null;
  13960. }
  13961. }
  13962. try {
  13963. resetPreOrderHookFlags(lView);
  13964. setBindingIndex(tView.bindingStartIndex);
  13965. if (templateFn !== null) {
  13966. executeTemplate(tView, lView, templateFn, 2 /* RenderFlags.Update */, context);
  13967. }
  13968. const hooksInitPhaseCompleted = (flags & 3 /* LViewFlags.InitPhaseStateMask */) === 3 /* InitPhaseState.InitPhaseCompleted */;
  13969. // execute pre-order hooks (OnInit, OnChanges, DoCheck)
  13970. // PERF WARNING: do NOT extract this to a separate function without running benchmarks
  13971. if (!isInCheckNoChangesPass) {
  13972. if (hooksInitPhaseCompleted) {
  13973. const preOrderCheckHooks = tView.preOrderCheckHooks;
  13974. if (preOrderCheckHooks !== null) {
  13975. executeCheckHooks(lView, preOrderCheckHooks, null);
  13976. }
  13977. }
  13978. else {
  13979. const preOrderHooks = tView.preOrderHooks;
  13980. if (preOrderHooks !== null) {
  13981. executeInitAndCheckHooks(lView, preOrderHooks, 0 /* InitPhaseState.OnInitHooksToBeRun */, null);
  13982. }
  13983. incrementInitPhaseFlags(lView, 0 /* InitPhaseState.OnInitHooksToBeRun */);
  13984. }
  13985. }
  13986. // We do not need to mark transplanted views for refresh when doing exhaustive checks
  13987. // because all views will be reached anyways during the traversal.
  13988. if (!isInExhaustiveCheckNoChangesPass) {
  13989. // First mark transplanted views that are declared in this lView as needing a refresh at their
  13990. // insertion points. This is needed to avoid the situation where the template is defined in this
  13991. // `LView` but its declaration appears after the insertion component.
  13992. markTransplantedViewsForRefresh(lView);
  13993. }
  13994. runEffectsInView(lView);
  13995. detectChangesInEmbeddedViews(lView, 0 /* ChangeDetectionMode.Global */);
  13996. // Content query results must be refreshed before content hooks are called.
  13997. if (tView.contentQueries !== null) {
  13998. refreshContentQueries(tView, lView);
  13999. }
  14000. // execute content hooks (AfterContentInit, AfterContentChecked)
  14001. // PERF WARNING: do NOT extract this to a separate function without running benchmarks
  14002. if (!isInCheckNoChangesPass) {
  14003. if (hooksInitPhaseCompleted) {
  14004. const contentCheckHooks = tView.contentCheckHooks;
  14005. if (contentCheckHooks !== null) {
  14006. executeCheckHooks(lView, contentCheckHooks);
  14007. }
  14008. }
  14009. else {
  14010. const contentHooks = tView.contentHooks;
  14011. if (contentHooks !== null) {
  14012. executeInitAndCheckHooks(lView, contentHooks, 1 /* InitPhaseState.AfterContentInitHooksToBeRun */);
  14013. }
  14014. incrementInitPhaseFlags(lView, 1 /* InitPhaseState.AfterContentInitHooksToBeRun */);
  14015. }
  14016. }
  14017. processHostBindingOpCodes(tView, lView);
  14018. // Refresh child component views.
  14019. const components = tView.components;
  14020. if (components !== null) {
  14021. detectChangesInChildComponents(lView, components, 0 /* ChangeDetectionMode.Global */);
  14022. }
  14023. // View queries must execute after refreshing child components because a template in this view
  14024. // could be inserted in a child component. If the view query executes before child component
  14025. // refresh, the template might not yet be inserted.
  14026. const viewQuery = tView.viewQuery;
  14027. if (viewQuery !== null) {
  14028. executeViewQueryFn(2 /* RenderFlags.Update */, viewQuery, context);
  14029. }
  14030. // execute view hooks (AfterViewInit, AfterViewChecked)
  14031. // PERF WARNING: do NOT extract this to a separate function without running benchmarks
  14032. if (!isInCheckNoChangesPass) {
  14033. if (hooksInitPhaseCompleted) {
  14034. const viewCheckHooks = tView.viewCheckHooks;
  14035. if (viewCheckHooks !== null) {
  14036. executeCheckHooks(lView, viewCheckHooks);
  14037. }
  14038. }
  14039. else {
  14040. const viewHooks = tView.viewHooks;
  14041. if (viewHooks !== null) {
  14042. executeInitAndCheckHooks(lView, viewHooks, 2 /* InitPhaseState.AfterViewInitHooksToBeRun */);
  14043. }
  14044. incrementInitPhaseFlags(lView, 2 /* InitPhaseState.AfterViewInitHooksToBeRun */);
  14045. }
  14046. }
  14047. if (tView.firstUpdatePass === true) {
  14048. // We need to make sure that we only flip the flag on successful `refreshView` only
  14049. // Don't do this in `finally` block.
  14050. // If we did this in `finally` block then an exception could block the execution of styling
  14051. // instructions which in turn would be unable to insert themselves into the styling linked
  14052. // list. The result of this would be that if the exception would not be throw on subsequent CD
  14053. // the styling would be unable to process it data and reflect to the DOM.
  14054. tView.firstUpdatePass = false;
  14055. }
  14056. // Schedule any effects that are waiting on the update pass of this view.
  14057. if (lView[EFFECTS_TO_SCHEDULE]) {
  14058. for (const notifyEffect of lView[EFFECTS_TO_SCHEDULE]) {
  14059. notifyEffect();
  14060. }
  14061. // Once they've been run, we can drop the array.
  14062. lView[EFFECTS_TO_SCHEDULE] = null;
  14063. }
  14064. // Do not reset the dirty state when running in check no changes mode. We don't want components
  14065. // to behave differently depending on whether check no changes is enabled or not. For example:
  14066. // Marking an OnPush component as dirty from within the `ngAfterViewInit` hook in order to
  14067. // refresh a `NgClass` binding should work. If we would reset the dirty state in the check
  14068. // no changes cycle, the component would be not be dirty for the next update pass. This would
  14069. // be different in production mode where the component dirty state is not reset.
  14070. if (!isInCheckNoChangesPass) {
  14071. addAfterRenderSequencesForView(lView);
  14072. lView[FLAGS] &= ~(64 /* LViewFlags.Dirty */ | 8 /* LViewFlags.FirstLViewPass */);
  14073. }
  14074. }
  14075. catch (e) {
  14076. if (!isInCheckNoChangesPass) {
  14077. // If refreshing a view causes an error, we need to remark the ancestors as needing traversal
  14078. // because the error might have caused a situation where views below the current location are
  14079. // dirty but will be unreachable because the "has dirty children" flag in the ancestors has been
  14080. // cleared during change detection and we failed to run to completion.
  14081. markAncestorsForTraversal(lView);
  14082. }
  14083. throw e;
  14084. }
  14085. finally {
  14086. if (currentConsumer !== null) {
  14087. consumerAfterComputation(currentConsumer, prevConsumer);
  14088. if (returnConsumerToPool) {
  14089. maybeReturnReactiveLViewConsumer(currentConsumer);
  14090. }
  14091. }
  14092. leaveView();
  14093. }
  14094. }
  14095. /**
  14096. * Goes over embedded views (ones created through ViewContainerRef APIs) and refreshes
  14097. * them by executing an associated template function.
  14098. */
  14099. function detectChangesInEmbeddedViews(lView, mode) {
  14100. for (let lContainer = getFirstLContainer(lView); lContainer !== null; lContainer = getNextLContainer(lContainer)) {
  14101. for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
  14102. const embeddedLView = lContainer[i];
  14103. detectChangesInViewIfAttached(embeddedLView, mode);
  14104. }
  14105. }
  14106. }
  14107. /**
  14108. * Mark transplanted views as needing to be refreshed at their attachment points.
  14109. *
  14110. * @param lView The `LView` that may have transplanted views.
  14111. */
  14112. function markTransplantedViewsForRefresh(lView) {
  14113. for (let lContainer = getFirstLContainer(lView); lContainer !== null; lContainer = getNextLContainer(lContainer)) {
  14114. if (!(lContainer[FLAGS] & 2 /* LContainerFlags.HasTransplantedViews */))
  14115. continue;
  14116. const movedViews = lContainer[MOVED_VIEWS];
  14117. ngDevMode && assertDefined(movedViews, 'Transplanted View flags set but missing MOVED_VIEWS');
  14118. for (let i = 0; i < movedViews.length; i++) {
  14119. const movedLView = movedViews[i];
  14120. markViewForRefresh(movedLView);
  14121. }
  14122. }
  14123. }
  14124. /**
  14125. * Detects changes in a component by entering the component view and processing its bindings,
  14126. * queries, etc. if it is CheckAlways, OnPush and Dirty, etc.
  14127. *
  14128. * @param componentHostIdx Element index in LView[] (adjusted for HEADER_OFFSET)
  14129. */
  14130. function detectChangesInComponent(hostLView, componentHostIdx, mode) {
  14131. ngDevMode && assertEqual(isCreationMode(hostLView), false, 'Should be run in update mode');
  14132. profiler(18 /* ProfilerEvent.ComponentStart */);
  14133. const componentView = getComponentLViewByIndex(componentHostIdx, hostLView);
  14134. detectChangesInViewIfAttached(componentView, mode);
  14135. profiler(19 /* ProfilerEvent.ComponentEnd */, componentView[CONTEXT]);
  14136. }
  14137. /**
  14138. * Visits a view as part of change detection traversal.
  14139. *
  14140. * If the view is detached, no additional traversal happens.
  14141. */
  14142. function detectChangesInViewIfAttached(lView, mode) {
  14143. if (!viewAttachedToChangeDetector(lView)) {
  14144. return;
  14145. }
  14146. detectChangesInView(lView, mode);
  14147. }
  14148. /**
  14149. * Visits a view as part of change detection traversal.
  14150. *
  14151. * The view is refreshed if:
  14152. * - If the view is CheckAlways or Dirty and ChangeDetectionMode is `Global`
  14153. * - If the view has the `RefreshView` flag
  14154. *
  14155. * The view is not refreshed, but descendants are traversed in `ChangeDetectionMode.Targeted` if the
  14156. * view HasChildViewsToRefresh flag is set.
  14157. */
  14158. function detectChangesInView(lView, mode) {
  14159. const isInCheckNoChangesPass = ngDevMode && isInCheckNoChangesMode();
  14160. const tView = lView[TVIEW];
  14161. const flags = lView[FLAGS];
  14162. const consumer = lView[REACTIVE_TEMPLATE_CONSUMER];
  14163. // Refresh CheckAlways views in Global mode.
  14164. let shouldRefreshView = !!(mode === 0 /* ChangeDetectionMode.Global */ && flags & 16 /* LViewFlags.CheckAlways */);
  14165. // Refresh Dirty views in Global mode, as long as we're not in checkNoChanges.
  14166. // CheckNoChanges never worked with `OnPush` components because the `Dirty` flag was
  14167. // cleared before checkNoChanges ran. Because there is now a loop for to check for
  14168. // backwards views, it gives an opportunity for `OnPush` components to be marked `Dirty`
  14169. // before the CheckNoChanges pass. We don't want existing errors that are hidden by the
  14170. // current CheckNoChanges bug to surface when making unrelated changes.
  14171. shouldRefreshView ||= !!(flags & 64 /* LViewFlags.Dirty */ &&
  14172. mode === 0 /* ChangeDetectionMode.Global */ &&
  14173. !isInCheckNoChangesPass);
  14174. // Always refresh views marked for refresh, regardless of mode.
  14175. shouldRefreshView ||= !!(flags & 1024 /* LViewFlags.RefreshView */);
  14176. // Refresh views when they have a dirty reactive consumer, regardless of mode.
  14177. shouldRefreshView ||= !!(consumer?.dirty && consumerPollProducersForChange(consumer));
  14178. shouldRefreshView ||= !!(ngDevMode && isExhaustiveCheckNoChanges());
  14179. // Mark the Flags and `ReactiveNode` as not dirty before refreshing the component, so that they
  14180. // can be re-dirtied during the refresh process.
  14181. if (consumer) {
  14182. consumer.dirty = false;
  14183. }
  14184. lView[FLAGS] &= -9217;
  14185. if (shouldRefreshView) {
  14186. refreshView(tView, lView, tView.template, lView[CONTEXT]);
  14187. }
  14188. else if (flags & 8192 /* LViewFlags.HasChildViewsToRefresh */) {
  14189. if (!isInCheckNoChangesPass) {
  14190. runEffectsInView(lView);
  14191. }
  14192. detectChangesInEmbeddedViews(lView, 1 /* ChangeDetectionMode.Targeted */);
  14193. const components = tView.components;
  14194. if (components !== null) {
  14195. detectChangesInChildComponents(lView, components, 1 /* ChangeDetectionMode.Targeted */);
  14196. }
  14197. if (!isInCheckNoChangesPass) {
  14198. addAfterRenderSequencesForView(lView);
  14199. }
  14200. }
  14201. }
  14202. /** Refreshes child components in the current view (update mode). */
  14203. function detectChangesInChildComponents(hostLView, components, mode) {
  14204. for (let i = 0; i < components.length; i++) {
  14205. detectChangesInComponent(hostLView, components[i], mode);
  14206. }
  14207. }
  14208. /**
  14209. * Invoke `HostBindingsFunction`s for view.
  14210. *
  14211. * This methods executes `TView.hostBindingOpCodes`. It is used to execute the
  14212. * `HostBindingsFunction`s associated with the current `LView`.
  14213. *
  14214. * @param tView Current `TView`.
  14215. * @param lView Current `LView`.
  14216. */
  14217. function processHostBindingOpCodes(tView, lView) {
  14218. const hostBindingOpCodes = tView.hostBindingOpCodes;
  14219. if (hostBindingOpCodes === null)
  14220. return;
  14221. try {
  14222. for (let i = 0; i < hostBindingOpCodes.length; i++) {
  14223. const opCode = hostBindingOpCodes[i];
  14224. if (opCode < 0) {
  14225. // Negative numbers are element indexes.
  14226. setSelectedIndex(~opCode);
  14227. }
  14228. else {
  14229. // Positive numbers are NumberTuple which store bindingRootIndex and directiveIndex.
  14230. const directiveIdx = opCode;
  14231. const bindingRootIndx = hostBindingOpCodes[++i];
  14232. const hostBindingFn = hostBindingOpCodes[++i];
  14233. setBindingRootForHostBindings(bindingRootIndx, directiveIdx);
  14234. const context = lView[directiveIdx];
  14235. profiler(24 /* ProfilerEvent.HostBindingsUpdateStart */, context);
  14236. hostBindingFn(2 /* RenderFlags.Update */, context);
  14237. profiler(25 /* ProfilerEvent.HostBindingsUpdateEnd */, context);
  14238. }
  14239. }
  14240. }
  14241. finally {
  14242. setSelectedIndex(-1);
  14243. }
  14244. }
  14245. /**
  14246. * Marks current view and all ancestors dirty.
  14247. *
  14248. * Returns the root view because it is found as a byproduct of marking the view tree
  14249. * dirty, and can be used by methods that consume markViewDirty() to easily schedule
  14250. * change detection. Otherwise, such methods would need to traverse up the view tree
  14251. * an additional time to get the root view and schedule a tick on it.
  14252. *
  14253. * @param lView The starting LView to mark dirty
  14254. * @returns the root LView
  14255. */
  14256. function markViewDirty(lView, source) {
  14257. const dirtyBitsToUse = isRefreshingViews()
  14258. ? // When we are actively refreshing views, we only use the `Dirty` bit to mark a view
  14259. 64 /* LViewFlags.Dirty */
  14260. : // When we are not actively refreshing a view tree, it is absolutely
  14261. // valid to update state and mark views dirty. We use the `RefreshView` flag in this
  14262. // case to allow synchronously rerunning change detection. This applies today to
  14263. // afterRender hooks as well as animation listeners which execute after detecting
  14264. // changes in a view when the render factory flushes.
  14265. 1024 /* LViewFlags.RefreshView */ | 64 /* LViewFlags.Dirty */;
  14266. lView[ENVIRONMENT].changeDetectionScheduler?.notify(source);
  14267. while (lView) {
  14268. lView[FLAGS] |= dirtyBitsToUse;
  14269. const parent = getLViewParent(lView);
  14270. // Stop traversing up as soon as you find a root view that wasn't attached to any container
  14271. if (isRootView(lView) && !parent) {
  14272. return lView;
  14273. }
  14274. // continue otherwise
  14275. lView = parent;
  14276. }
  14277. return null;
  14278. }
  14279. /**
  14280. * Creates a LContainer, either from a container instruction, or for a ViewContainerRef.
  14281. *
  14282. * @param hostNative The host element for the LContainer
  14283. * @param hostTNode The host TNode for the LContainer
  14284. * @param currentView The parent view of the LContainer
  14285. * @param native The native comment element
  14286. * @param isForViewContainerRef Optional a flag indicating the ViewContainerRef case
  14287. * @returns LContainer
  14288. */
  14289. function createLContainer(hostNative, currentView, native, tNode) {
  14290. ngDevMode && assertLView(currentView);
  14291. const lContainer = [
  14292. hostNative, // host native
  14293. true, // Boolean `true` in this position signifies that this is an `LContainer`
  14294. 0, // flags
  14295. currentView, // parent
  14296. null, // next
  14297. tNode, // t_host
  14298. null, // dehydrated views
  14299. native, // native,
  14300. null, // view refs
  14301. null, // moved views
  14302. ];
  14303. ngDevMode &&
  14304. assertEqual(lContainer.length, CONTAINER_HEADER_OFFSET, 'Should allocate correct number of slots for LContainer header.');
  14305. return lContainer;
  14306. }
  14307. function getLViewFromLContainer(lContainer, index) {
  14308. const adjustedIndex = CONTAINER_HEADER_OFFSET + index;
  14309. // avoid reading past the array boundaries
  14310. if (adjustedIndex < lContainer.length) {
  14311. const lView = lContainer[adjustedIndex];
  14312. ngDevMode && assertLView(lView);
  14313. return lView;
  14314. }
  14315. return undefined;
  14316. }
  14317. function addLViewToLContainer(lContainer, lView, index, addToDOM = true) {
  14318. const tView = lView[TVIEW];
  14319. // Insert into the view tree so the new view can be change-detected
  14320. insertView(tView, lView, lContainer, index);
  14321. // Insert elements that belong to this view into the DOM tree
  14322. if (addToDOM) {
  14323. const beforeNode = getBeforeNodeForView(index, lContainer);
  14324. const renderer = lView[RENDERER];
  14325. const parentRNode = renderer.parentNode(lContainer[NATIVE]);
  14326. if (parentRNode !== null) {
  14327. addViewToDOM(tView, lContainer[T_HOST], renderer, lView, parentRNode, beforeNode);
  14328. }
  14329. }
  14330. // When in hydration mode, reset the pointer to the first child in
  14331. // the dehydrated view. This indicates that the view was hydrated and
  14332. // further attaching/detaching should work with this view as normal.
  14333. const hydrationInfo = lView[HYDRATION];
  14334. if (hydrationInfo !== null && hydrationInfo.firstChild !== null) {
  14335. hydrationInfo.firstChild = null;
  14336. }
  14337. }
  14338. function removeLViewFromLContainer(lContainer, index) {
  14339. const lView = detachView(lContainer, index);
  14340. if (lView !== undefined) {
  14341. destroyLView(lView[TVIEW], lView);
  14342. }
  14343. return lView;
  14344. }
  14345. /**
  14346. * Detaches a view from a container.
  14347. *
  14348. * This method removes the view from the container's array of active views. It also
  14349. * removes the view's elements from the DOM.
  14350. *
  14351. * @param lContainer The container from which to detach a view
  14352. * @param removeIndex The index of the view to detach
  14353. * @returns Detached LView instance.
  14354. */
  14355. function detachView(lContainer, removeIndex) {
  14356. if (lContainer.length <= CONTAINER_HEADER_OFFSET)
  14357. return;
  14358. const indexInContainer = CONTAINER_HEADER_OFFSET + removeIndex;
  14359. const viewToDetach = lContainer[indexInContainer];
  14360. if (viewToDetach) {
  14361. const declarationLContainer = viewToDetach[DECLARATION_LCONTAINER];
  14362. if (declarationLContainer !== null && declarationLContainer !== lContainer) {
  14363. detachMovedView(declarationLContainer, viewToDetach);
  14364. }
  14365. if (removeIndex > 0) {
  14366. lContainer[indexInContainer - 1][NEXT] = viewToDetach[NEXT];
  14367. }
  14368. const removedLView = removeFromArray(lContainer, CONTAINER_HEADER_OFFSET + removeIndex);
  14369. removeViewFromDOM(viewToDetach[TVIEW], viewToDetach);
  14370. // notify query that a view has been removed
  14371. const lQueries = removedLView[QUERIES];
  14372. if (lQueries !== null) {
  14373. lQueries.detachView(removedLView[TVIEW]);
  14374. }
  14375. viewToDetach[PARENT] = null;
  14376. viewToDetach[NEXT] = null;
  14377. // Unsets the attached flag
  14378. viewToDetach[FLAGS] &= -129 /* LViewFlags.Attached */;
  14379. }
  14380. return viewToDetach;
  14381. }
  14382. /**
  14383. * Inserts a view into a container.
  14384. *
  14385. * This adds the view to the container's array of active views in the correct
  14386. * position. It also adds the view's elements to the DOM if the container isn't a
  14387. * root node of another view (in that case, the view's elements will be added when
  14388. * the container's parent view is added later).
  14389. *
  14390. * @param tView The `TView' of the `LView` to insert
  14391. * @param lView The view to insert
  14392. * @param lContainer The container into which the view should be inserted
  14393. * @param index Which index in the container to insert the child view into
  14394. */
  14395. function insertView(tView, lView, lContainer, index) {
  14396. ngDevMode && assertLView(lView);
  14397. ngDevMode && assertLContainer(lContainer);
  14398. const indexInContainer = CONTAINER_HEADER_OFFSET + index;
  14399. const containerLength = lContainer.length;
  14400. if (index > 0) {
  14401. // This is a new view, we need to add it to the children.
  14402. lContainer[indexInContainer - 1][NEXT] = lView;
  14403. }
  14404. if (index < containerLength - CONTAINER_HEADER_OFFSET) {
  14405. lView[NEXT] = lContainer[indexInContainer];
  14406. addToArray(lContainer, CONTAINER_HEADER_OFFSET + index, lView);
  14407. }
  14408. else {
  14409. lContainer.push(lView);
  14410. lView[NEXT] = null;
  14411. }
  14412. lView[PARENT] = lContainer;
  14413. // track views where declaration and insertion points are different
  14414. const declarationLContainer = lView[DECLARATION_LCONTAINER];
  14415. if (declarationLContainer !== null && lContainer !== declarationLContainer) {
  14416. trackMovedView(declarationLContainer, lView);
  14417. }
  14418. // notify query that a new view has been added
  14419. const lQueries = lView[QUERIES];
  14420. if (lQueries !== null) {
  14421. lQueries.insertView(tView);
  14422. }
  14423. updateAncestorTraversalFlagsOnAttach(lView);
  14424. // Sets the attached flag
  14425. lView[FLAGS] |= 128 /* LViewFlags.Attached */;
  14426. }
  14427. /**
  14428. * Track views created from the declaration container (TemplateRef) and inserted into a
  14429. * different LContainer or attached directly to ApplicationRef.
  14430. */
  14431. function trackMovedView(declarationContainer, lView) {
  14432. ngDevMode && assertDefined(lView, 'LView required');
  14433. ngDevMode && assertLContainer(declarationContainer);
  14434. const movedViews = declarationContainer[MOVED_VIEWS];
  14435. const parent = lView[PARENT];
  14436. ngDevMode && assertDefined(parent, 'missing parent');
  14437. if (isLView(parent)) {
  14438. declarationContainer[FLAGS] |= 2 /* LContainerFlags.HasTransplantedViews */;
  14439. }
  14440. else {
  14441. const insertedComponentLView = parent[PARENT][DECLARATION_COMPONENT_VIEW];
  14442. ngDevMode && assertDefined(insertedComponentLView, 'Missing insertedComponentLView');
  14443. const declaredComponentLView = lView[DECLARATION_COMPONENT_VIEW];
  14444. ngDevMode && assertDefined(declaredComponentLView, 'Missing declaredComponentLView');
  14445. if (declaredComponentLView !== insertedComponentLView) {
  14446. // At this point the declaration-component is not same as insertion-component; this means that
  14447. // this is a transplanted view. Mark the declared lView as having transplanted views so that
  14448. // those views can participate in CD.
  14449. declarationContainer[FLAGS] |= 2 /* LContainerFlags.HasTransplantedViews */;
  14450. }
  14451. }
  14452. if (movedViews === null) {
  14453. declarationContainer[MOVED_VIEWS] = [lView];
  14454. }
  14455. else {
  14456. movedViews.push(lView);
  14457. }
  14458. }
  14459. let ViewRef$1 = class ViewRef {
  14460. _lView;
  14461. _cdRefInjectingView;
  14462. notifyErrorHandler;
  14463. _appRef = null;
  14464. _attachedToViewContainer = false;
  14465. get rootNodes() {
  14466. const lView = this._lView;
  14467. const tView = lView[TVIEW];
  14468. return collectNativeNodes(tView, lView, tView.firstChild, []);
  14469. }
  14470. constructor(
  14471. /**
  14472. * This represents `LView` associated with the component when ViewRef is a ChangeDetectorRef.
  14473. *
  14474. * When ViewRef is created for a dynamic component, this also represents the `LView` for the
  14475. * component.
  14476. *
  14477. * For a "regular" ViewRef created for an embedded view, this is the `LView` for the embedded
  14478. * view.
  14479. *
  14480. * @internal
  14481. */
  14482. _lView,
  14483. /**
  14484. * This represents the `LView` associated with the point where `ChangeDetectorRef` was
  14485. * requested.
  14486. *
  14487. * This may be different from `_lView` if the `_cdRefInjectingView` is an embedded view.
  14488. */
  14489. _cdRefInjectingView, notifyErrorHandler = true) {
  14490. this._lView = _lView;
  14491. this._cdRefInjectingView = _cdRefInjectingView;
  14492. this.notifyErrorHandler = notifyErrorHandler;
  14493. }
  14494. get context() {
  14495. return this._lView[CONTEXT];
  14496. }
  14497. /**
  14498. * @deprecated Replacing the full context object is not supported. Modify the context
  14499. * directly, or consider using a `Proxy` if you need to replace the full object.
  14500. * // TODO(devversion): Remove this.
  14501. */
  14502. set context(value) {
  14503. if (ngDevMode) {
  14504. // Note: We have a warning message here because the `@deprecated` JSDoc will not be picked
  14505. // up for assignments on the setter. We want to let users know about the deprecated usage.
  14506. console.warn('Angular: Replacing the `context` object of an `EmbeddedViewRef` is deprecated.');
  14507. }
  14508. this._lView[CONTEXT] = value;
  14509. }
  14510. get destroyed() {
  14511. return isDestroyed(this._lView);
  14512. }
  14513. destroy() {
  14514. if (this._appRef) {
  14515. this._appRef.detachView(this);
  14516. }
  14517. else if (this._attachedToViewContainer) {
  14518. const parent = this._lView[PARENT];
  14519. if (isLContainer(parent)) {
  14520. const viewRefs = parent[VIEW_REFS];
  14521. const index = viewRefs ? viewRefs.indexOf(this) : -1;
  14522. if (index > -1) {
  14523. ngDevMode &&
  14524. 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.');
  14525. detachView(parent, index);
  14526. removeFromArray(viewRefs, index);
  14527. }
  14528. }
  14529. this._attachedToViewContainer = false;
  14530. }
  14531. destroyLView(this._lView[TVIEW], this._lView);
  14532. }
  14533. onDestroy(callback) {
  14534. storeLViewOnDestroy(this._lView, callback);
  14535. }
  14536. /**
  14537. * Marks a view and all of its ancestors dirty.
  14538. *
  14539. * This can be used to ensure an {@link ChangeDetectionStrategy#OnPush} component is
  14540. * checked when it needs to be re-rendered but the two normal triggers haven't marked it
  14541. * dirty (i.e. inputs haven't changed and events haven't fired in the view).
  14542. *
  14543. * <!-- TODO: Add a link to a chapter on OnPush components -->
  14544. *
  14545. * @usageNotes
  14546. * ### Example
  14547. *
  14548. * ```ts
  14549. * @Component({
  14550. * selector: 'app-root',
  14551. * template: `Number of ticks: {{numberOfTicks}}`
  14552. * changeDetection: ChangeDetectionStrategy.OnPush,
  14553. * })
  14554. * class AppComponent {
  14555. * numberOfTicks = 0;
  14556. *
  14557. * constructor(private ref: ChangeDetectorRef) {
  14558. * setInterval(() => {
  14559. * this.numberOfTicks++;
  14560. * // the following is required, otherwise the view will not be updated
  14561. * this.ref.markForCheck();
  14562. * }, 1000);
  14563. * }
  14564. * }
  14565. * ```
  14566. */
  14567. markForCheck() {
  14568. markViewDirty(this._cdRefInjectingView || this._lView, 4 /* NotificationSource.MarkForCheck */);
  14569. }
  14570. /**
  14571. * Detaches the view from the change detection tree.
  14572. *
  14573. * Detached views will not be checked during change detection runs until they are
  14574. * re-attached, even if they are dirty. `detach` can be used in combination with
  14575. * {@link ChangeDetectorRef#detectChanges} to implement local change
  14576. * detection checks.
  14577. *
  14578. * <!-- TODO: Add a link to a chapter on detach/reattach/local digest -->
  14579. * <!-- TODO: Add a live demo once ref.detectChanges is merged into master -->
  14580. *
  14581. * @usageNotes
  14582. * ### Example
  14583. *
  14584. * The following example defines a component with a large list of readonly data.
  14585. * Imagine the data changes constantly, many times per second. For performance reasons,
  14586. * we want to check and update the list every five seconds. We can do that by detaching
  14587. * the component's change detector and doing a local check every five seconds.
  14588. *
  14589. * ```ts
  14590. * class DataProvider {
  14591. * // in a real application the returned data will be different every time
  14592. * get data() {
  14593. * return [1,2,3,4,5];
  14594. * }
  14595. * }
  14596. *
  14597. * @Component({
  14598. * selector: 'giant-list',
  14599. * template: `
  14600. * <li *ngFor="let d of dataProvider.data">Data {{d}}</li>
  14601. * `,
  14602. * })
  14603. * class GiantList {
  14604. * constructor(private ref: ChangeDetectorRef, private dataProvider: DataProvider) {
  14605. * ref.detach();
  14606. * setInterval(() => {
  14607. * this.ref.detectChanges();
  14608. * }, 5000);
  14609. * }
  14610. * }
  14611. *
  14612. * @Component({
  14613. * selector: 'app',
  14614. * providers: [DataProvider],
  14615. * template: `
  14616. * <giant-list><giant-list>
  14617. * `,
  14618. * })
  14619. * class App {
  14620. * }
  14621. * ```
  14622. */
  14623. detach() {
  14624. this._lView[FLAGS] &= -129 /* LViewFlags.Attached */;
  14625. }
  14626. /**
  14627. * Re-attaches a view to the change detection tree.
  14628. *
  14629. * This can be used to re-attach views that were previously detached from the tree
  14630. * using {@link ChangeDetectorRef#detach}. Views are attached to the tree by default.
  14631. *
  14632. * <!-- TODO: Add a link to a chapter on detach/reattach/local digest -->
  14633. *
  14634. * @usageNotes
  14635. * ### Example
  14636. *
  14637. * The following example creates a component displaying `live` data. The component will detach
  14638. * its change detector from the main change detector tree when the component's live property
  14639. * is set to false.
  14640. *
  14641. * ```ts
  14642. * class DataProvider {
  14643. * data = 1;
  14644. *
  14645. * constructor() {
  14646. * setInterval(() => {
  14647. * this.data = this.data * 2;
  14648. * }, 500);
  14649. * }
  14650. * }
  14651. *
  14652. * @Component({
  14653. * selector: 'live-data',
  14654. * inputs: ['live'],
  14655. * template: 'Data: {{dataProvider.data}}'
  14656. * })
  14657. * class LiveData {
  14658. * constructor(private ref: ChangeDetectorRef, private dataProvider: DataProvider) {}
  14659. *
  14660. * set live(value) {
  14661. * if (value) {
  14662. * this.ref.reattach();
  14663. * } else {
  14664. * this.ref.detach();
  14665. * }
  14666. * }
  14667. * }
  14668. *
  14669. * @Component({
  14670. * selector: 'app-root',
  14671. * providers: [DataProvider],
  14672. * template: `
  14673. * Live Update: <input type="checkbox" [(ngModel)]="live">
  14674. * <live-data [live]="live"><live-data>
  14675. * `,
  14676. * })
  14677. * class AppComponent {
  14678. * live = true;
  14679. * }
  14680. * ```
  14681. */
  14682. reattach() {
  14683. updateAncestorTraversalFlagsOnAttach(this._lView);
  14684. this._lView[FLAGS] |= 128 /* LViewFlags.Attached */;
  14685. }
  14686. /**
  14687. * Checks the view and its children.
  14688. *
  14689. * This can also be used in combination with {@link ChangeDetectorRef#detach} to implement
  14690. * local change detection checks.
  14691. *
  14692. * <!-- TODO: Add a link to a chapter on detach/reattach/local digest -->
  14693. * <!-- TODO: Add a live demo once ref.detectChanges is merged into master -->
  14694. *
  14695. * @usageNotes
  14696. * ### Example
  14697. *
  14698. * The following example defines a component with a large list of readonly data.
  14699. * Imagine, the data changes constantly, many times per second. For performance reasons,
  14700. * we want to check and update the list every five seconds.
  14701. *
  14702. * We can do that by detaching the component's change detector and doing a local change detection
  14703. * check every five seconds.
  14704. *
  14705. * See {@link ChangeDetectorRef#detach} for more information.
  14706. */
  14707. detectChanges() {
  14708. // Add `RefreshView` flag to ensure this view is refreshed if not already dirty.
  14709. // `RefreshView` flag is used intentionally over `Dirty` because it gets cleared before
  14710. // executing any of the actual refresh code while the `Dirty` flag doesn't get cleared
  14711. // until the end of the refresh. Using `RefreshView` prevents creating a potential difference
  14712. // in the state of the LViewFlags during template execution.
  14713. this._lView[FLAGS] |= 1024 /* LViewFlags.RefreshView */;
  14714. detectChangesInternal(this._lView, this.notifyErrorHandler);
  14715. }
  14716. /**
  14717. * Checks the change detector and its children, and throws if any changes are detected.
  14718. *
  14719. * This is used in development mode to verify that running change detection doesn't
  14720. * introduce other changes.
  14721. */
  14722. checkNoChanges() {
  14723. if (ngDevMode) {
  14724. checkNoChangesInternal(this._lView, CheckNoChangesMode.OnlyDirtyViews, this.notifyErrorHandler);
  14725. }
  14726. }
  14727. attachToViewContainerRef() {
  14728. if (this._appRef) {
  14729. throw new RuntimeError(902 /* RuntimeErrorCode.VIEW_ALREADY_ATTACHED */, ngDevMode && 'This view is already attached directly to the ApplicationRef!');
  14730. }
  14731. this._attachedToViewContainer = true;
  14732. }
  14733. detachFromAppRef() {
  14734. this._appRef = null;
  14735. const isRoot = isRootView(this._lView);
  14736. const declarationContainer = this._lView[DECLARATION_LCONTAINER];
  14737. if (declarationContainer !== null && !isRoot) {
  14738. detachMovedView(declarationContainer, this._lView);
  14739. }
  14740. detachViewFromDOM(this._lView[TVIEW], this._lView);
  14741. }
  14742. attachToAppRef(appRef) {
  14743. if (this._attachedToViewContainer) {
  14744. throw new RuntimeError(902 /* RuntimeErrorCode.VIEW_ALREADY_ATTACHED */, ngDevMode && 'This view is already attached to a ViewContainer!');
  14745. }
  14746. this._appRef = appRef;
  14747. const isRoot = isRootView(this._lView);
  14748. const declarationContainer = this._lView[DECLARATION_LCONTAINER];
  14749. if (declarationContainer !== null && !isRoot) {
  14750. trackMovedView(declarationContainer, this._lView);
  14751. }
  14752. updateAncestorTraversalFlagsOnAttach(this._lView);
  14753. }
  14754. };
  14755. /**
  14756. * Reports whether the given view is considered dirty according to the different marking mechanisms.
  14757. */
  14758. function isViewDirty(view) {
  14759. return requiresRefreshOrTraversal(view._lView) || !!(view._lView[FLAGS] & 64 /* LViewFlags.Dirty */);
  14760. }
  14761. function markForRefresh(view) {
  14762. markViewForRefresh(view['_cdRefInjectingView'] || view._lView);
  14763. }
  14764. /**
  14765. * Represents an embedded template that can be used to instantiate embedded views.
  14766. * To instantiate embedded views based on a template, use the `ViewContainerRef`
  14767. * method `createEmbeddedView()`.
  14768. *
  14769. * Access a `TemplateRef` instance by placing a directive on an `<ng-template>`
  14770. * element (or directive prefixed with `*`). The `TemplateRef` for the embedded view
  14771. * is injected into the constructor of the directive,
  14772. * using the `TemplateRef` token.
  14773. *
  14774. * You can also use a `Query` to find a `TemplateRef` associated with
  14775. * a component or a directive.
  14776. *
  14777. * @see {@link ViewContainerRef}
  14778. *
  14779. * @publicApi
  14780. */
  14781. class TemplateRef {
  14782. /**
  14783. * @internal
  14784. * @nocollapse
  14785. */
  14786. static __NG_ELEMENT_ID__ = injectTemplateRef;
  14787. }
  14788. const ViewEngineTemplateRef = TemplateRef;
  14789. // TODO(alxhub): combine interface and implementation. Currently this is challenging since something
  14790. // in g3 depends on them being separate.
  14791. const R3TemplateRef = class TemplateRef extends ViewEngineTemplateRef {
  14792. _declarationLView;
  14793. _declarationTContainer;
  14794. elementRef;
  14795. constructor(_declarationLView, _declarationTContainer, elementRef) {
  14796. super();
  14797. this._declarationLView = _declarationLView;
  14798. this._declarationTContainer = _declarationTContainer;
  14799. this.elementRef = elementRef;
  14800. }
  14801. /**
  14802. * Returns an `ssrId` associated with a TView, which was used to
  14803. * create this instance of the `TemplateRef`.
  14804. *
  14805. * @internal
  14806. */
  14807. get ssrId() {
  14808. return this._declarationTContainer.tView?.ssrId || null;
  14809. }
  14810. createEmbeddedView(context, injector) {
  14811. return this.createEmbeddedViewImpl(context, injector);
  14812. }
  14813. /**
  14814. * @internal
  14815. */
  14816. createEmbeddedViewImpl(context, injector, dehydratedView) {
  14817. const embeddedLView = createAndRenderEmbeddedLView(this._declarationLView, this._declarationTContainer, context, { embeddedViewInjector: injector, dehydratedView });
  14818. return new ViewRef$1(embeddedLView);
  14819. }
  14820. };
  14821. /**
  14822. * Creates a TemplateRef given a node.
  14823. *
  14824. * @returns The TemplateRef instance to use
  14825. */
  14826. function injectTemplateRef() {
  14827. return createTemplateRef(getCurrentTNode(), getLView());
  14828. }
  14829. /**
  14830. * Creates a TemplateRef and stores it on the injector.
  14831. *
  14832. * @param hostTNode The node on which a TemplateRef is requested
  14833. * @param hostLView The `LView` to which the node belongs
  14834. * @returns The TemplateRef instance or null if we can't create a TemplateRef on a given node type
  14835. */
  14836. function createTemplateRef(hostTNode, hostLView) {
  14837. if (hostTNode.type & 4 /* TNodeType.Container */) {
  14838. ngDevMode && assertDefined(hostTNode.tView, 'TView must be allocated');
  14839. return new R3TemplateRef(hostLView, hostTNode, createElementRef(hostTNode, hostLView));
  14840. }
  14841. return null;
  14842. }
  14843. const AT_THIS_LOCATION = '<-- AT THIS LOCATION';
  14844. /**
  14845. * Retrieves a user friendly string for a given TNodeType for use in
  14846. * friendly error messages
  14847. *
  14848. * @param tNodeType
  14849. * @returns
  14850. */
  14851. function getFriendlyStringFromTNodeType(tNodeType) {
  14852. switch (tNodeType) {
  14853. case 4 /* TNodeType.Container */:
  14854. return 'view container';
  14855. case 2 /* TNodeType.Element */:
  14856. return 'element';
  14857. case 8 /* TNodeType.ElementContainer */:
  14858. return 'ng-container';
  14859. case 32 /* TNodeType.Icu */:
  14860. return 'icu';
  14861. case 64 /* TNodeType.Placeholder */:
  14862. return 'i18n';
  14863. case 16 /* TNodeType.Projection */:
  14864. return 'projection';
  14865. case 1 /* TNodeType.Text */:
  14866. return 'text';
  14867. case 128 /* TNodeType.LetDeclaration */:
  14868. return '@let';
  14869. default:
  14870. // This should not happen as we cover all possible TNode types above.
  14871. return '<unknown>';
  14872. }
  14873. }
  14874. /**
  14875. * Validates that provided nodes match during the hydration process.
  14876. */
  14877. function validateMatchingNode(node, nodeType, tagName, lView, tNode, isViewContainerAnchor = false) {
  14878. if (!node ||
  14879. node.nodeType !== nodeType ||
  14880. (node.nodeType === Node.ELEMENT_NODE &&
  14881. node.tagName.toLowerCase() !== tagName?.toLowerCase())) {
  14882. const expectedNode = shortRNodeDescription(nodeType, tagName, null);
  14883. let header = `During hydration Angular expected ${expectedNode} but `;
  14884. const hostComponentDef = getDeclarationComponentDef(lView);
  14885. const componentClassName = hostComponentDef?.type?.name;
  14886. const expectedDom = describeExpectedDom(lView, tNode, isViewContainerAnchor);
  14887. const expected = `Angular expected this DOM:\n\n${expectedDom}\n\n`;
  14888. let actual = '';
  14889. const componentHostElement = unwrapRNode(lView[HOST]);
  14890. if (!node) {
  14891. // No node found during hydration.
  14892. header += `the node was not found.\n\n`;
  14893. // Since the node is missing, we use the closest node to attach the error to
  14894. markRNodeAsHavingHydrationMismatch(componentHostElement, expectedDom);
  14895. }
  14896. else {
  14897. const actualNode = shortRNodeDescription(node.nodeType, node.tagName ?? null, node.textContent ?? null);
  14898. header += `found ${actualNode}.\n\n`;
  14899. const actualDom = describeDomFromNode(node);
  14900. actual = `Actual DOM is:\n\n${actualDom}\n\n`;
  14901. // DevTools only report hydration issues on the component level, so we attach extra debug
  14902. // info to a component host element to make it available to DevTools.
  14903. markRNodeAsHavingHydrationMismatch(componentHostElement, expectedDom, actualDom);
  14904. }
  14905. const footer = getHydrationErrorFooter(componentClassName);
  14906. const message = header + expected + actual + getHydrationAttributeNote() + footer;
  14907. throw new RuntimeError(-500 /* RuntimeErrorCode.HYDRATION_NODE_MISMATCH */, message);
  14908. }
  14909. }
  14910. /**
  14911. * Validates that a given node has sibling nodes
  14912. */
  14913. function validateSiblingNodeExists(node) {
  14914. validateNodeExists(node);
  14915. if (!node.nextSibling) {
  14916. const header = 'During hydration Angular expected more sibling nodes to be present.\n\n';
  14917. const actual = `Actual DOM is:\n\n${describeDomFromNode(node)}\n\n`;
  14918. const footer = getHydrationErrorFooter();
  14919. const message = header + actual + footer;
  14920. markRNodeAsHavingHydrationMismatch(node, '', actual);
  14921. throw new RuntimeError(-501 /* RuntimeErrorCode.HYDRATION_MISSING_SIBLINGS */, message);
  14922. }
  14923. }
  14924. /**
  14925. * Validates that a node exists or throws
  14926. */
  14927. function validateNodeExists(node, lView = null, tNode = null) {
  14928. if (!node) {
  14929. const header = 'During hydration, Angular expected an element to be present at this location.\n\n';
  14930. let expected = '';
  14931. let footer = '';
  14932. if (lView !== null && tNode !== null) {
  14933. expected = describeExpectedDom(lView, tNode, false);
  14934. footer = getHydrationErrorFooter();
  14935. // Since the node is missing, we use the closest node to attach the error to
  14936. markRNodeAsHavingHydrationMismatch(unwrapRNode(lView[HOST]), expected, '');
  14937. }
  14938. throw new RuntimeError(-502 /* RuntimeErrorCode.HYDRATION_MISSING_NODE */, `${header}${expected}\n\n${footer}`);
  14939. }
  14940. }
  14941. /**
  14942. * Builds the hydration error message when a node is not found
  14943. *
  14944. * @param lView the LView where the node exists
  14945. * @param tNode the TNode
  14946. */
  14947. function nodeNotFoundError(lView, tNode) {
  14948. const header = 'During serialization, Angular was unable to find an element in the DOM:\n\n';
  14949. const expected = `${describeExpectedDom(lView, tNode, false)}\n\n`;
  14950. const footer = getHydrationErrorFooter();
  14951. throw new RuntimeError(-502 /* RuntimeErrorCode.HYDRATION_MISSING_NODE */, header + expected + footer);
  14952. }
  14953. /**
  14954. * Builds a hydration error message when a node is not found at a path location
  14955. *
  14956. * @param host the Host Node
  14957. * @param path the path to the node
  14958. */
  14959. function nodeNotFoundAtPathError(host, path) {
  14960. const header = `During hydration Angular was unable to locate a node ` +
  14961. `using the "${path}" path, starting from the ${describeRNode(host)} node.\n\n`;
  14962. const footer = getHydrationErrorFooter();
  14963. markRNodeAsHavingHydrationMismatch(host);
  14964. throw new RuntimeError(-502 /* RuntimeErrorCode.HYDRATION_MISSING_NODE */, header + footer);
  14965. }
  14966. /**
  14967. * Builds the hydration error message in the case that dom nodes are created outside of
  14968. * the Angular context and are being used as projected nodes
  14969. *
  14970. * @param lView the LView
  14971. * @param tNode the TNode
  14972. * @returns an error
  14973. */
  14974. function unsupportedProjectionOfDomNodes(rNode) {
  14975. const header = 'During serialization, Angular detected DOM nodes ' +
  14976. 'that were created outside of Angular context and provided as projectable nodes ' +
  14977. '(likely via `ViewContainerRef.createComponent` or `createComponent` APIs). ' +
  14978. 'Hydration is not supported for such cases, consider refactoring the code to avoid ' +
  14979. 'this pattern or using `ngSkipHydration` on the host element of the component.\n\n';
  14980. const actual = `${describeDomFromNode(rNode)}\n\n`;
  14981. const message = header + actual + getHydrationAttributeNote();
  14982. return new RuntimeError(-503 /* RuntimeErrorCode.UNSUPPORTED_PROJECTION_DOM_NODES */, message);
  14983. }
  14984. /**
  14985. * Builds the hydration error message in the case that ngSkipHydration was used on a
  14986. * node that is not a component host element or host binding
  14987. *
  14988. * @param rNode the HTML Element
  14989. * @returns an error
  14990. */
  14991. function invalidSkipHydrationHost(rNode) {
  14992. const header = 'The `ngSkipHydration` flag is applied on a node ' +
  14993. "that doesn't act as a component host. Hydration can be " +
  14994. 'skipped only on per-component basis.\n\n';
  14995. const actual = `${describeDomFromNode(rNode)}\n\n`;
  14996. const footer = 'Please move the `ngSkipHydration` attribute to the component host element.\n\n';
  14997. const message = header + actual + footer;
  14998. return new RuntimeError(-504 /* RuntimeErrorCode.INVALID_SKIP_HYDRATION_HOST */, message);
  14999. }
  15000. // Stringification methods
  15001. /**
  15002. * Stringifies a given TNode's attributes
  15003. *
  15004. * @param tNode a provided TNode
  15005. * @returns string
  15006. */
  15007. function stringifyTNodeAttrs(tNode) {
  15008. const results = [];
  15009. if (tNode.attrs) {
  15010. for (let i = 0; i < tNode.attrs.length;) {
  15011. const attrName = tNode.attrs[i++];
  15012. // Once we reach the first flag, we know that the list of
  15013. // attributes is over.
  15014. if (typeof attrName == 'number') {
  15015. break;
  15016. }
  15017. const attrValue = tNode.attrs[i++];
  15018. results.push(`${attrName}="${shorten(attrValue)}"`);
  15019. }
  15020. }
  15021. return results.join(' ');
  15022. }
  15023. /**
  15024. * The list of internal attributes that should be filtered out while
  15025. * producing an error message.
  15026. */
  15027. const internalAttrs = new Set(['ngh', 'ng-version', 'ng-server-context']);
  15028. /**
  15029. * Stringifies an HTML Element's attributes
  15030. *
  15031. * @param rNode an HTML Element
  15032. * @returns string
  15033. */
  15034. function stringifyRNodeAttrs(rNode) {
  15035. const results = [];
  15036. for (let i = 0; i < rNode.attributes.length; i++) {
  15037. const attr = rNode.attributes[i];
  15038. if (internalAttrs.has(attr.name))
  15039. continue;
  15040. results.push(`${attr.name}="${shorten(attr.value)}"`);
  15041. }
  15042. return results.join(' ');
  15043. }
  15044. // Methods for Describing the DOM
  15045. /**
  15046. * Converts a tNode to a helpful readable string value for use in error messages
  15047. *
  15048. * @param tNode a given TNode
  15049. * @param innerContent the content of the node
  15050. * @returns string
  15051. */
  15052. function describeTNode(tNode, innerContent = '…') {
  15053. switch (tNode.type) {
  15054. case 1 /* TNodeType.Text */:
  15055. const content = tNode.value ? `(${tNode.value})` : '';
  15056. return `#text${content}`;
  15057. case 2 /* TNodeType.Element */:
  15058. const attrs = stringifyTNodeAttrs(tNode);
  15059. const tag = tNode.value.toLowerCase();
  15060. return `<${tag}${attrs ? ' ' + attrs : ''}>${innerContent}</${tag}>`;
  15061. case 8 /* TNodeType.ElementContainer */:
  15062. return '<!-- ng-container -->';
  15063. case 4 /* TNodeType.Container */:
  15064. return '<!-- container -->';
  15065. default:
  15066. const typeAsString = getFriendlyStringFromTNodeType(tNode.type);
  15067. return `#node(${typeAsString})`;
  15068. }
  15069. }
  15070. /**
  15071. * Converts an RNode to a helpful readable string value for use in error messages
  15072. *
  15073. * @param rNode a given RNode
  15074. * @param innerContent the content of the node
  15075. * @returns string
  15076. */
  15077. function describeRNode(rNode, innerContent = '…') {
  15078. const node = rNode;
  15079. switch (node.nodeType) {
  15080. case Node.ELEMENT_NODE:
  15081. const tag = node.tagName.toLowerCase();
  15082. const attrs = stringifyRNodeAttrs(node);
  15083. return `<${tag}${attrs ? ' ' + attrs : ''}>${innerContent}</${tag}>`;
  15084. case Node.TEXT_NODE:
  15085. const content = node.textContent ? shorten(node.textContent) : '';
  15086. return `#text${content ? `(${content})` : ''}`;
  15087. case Node.COMMENT_NODE:
  15088. return `<!-- ${shorten(node.textContent ?? '')} -->`;
  15089. default:
  15090. return `#node(${node.nodeType})`;
  15091. }
  15092. }
  15093. /**
  15094. * Builds the string containing the expected DOM present given the LView and TNode
  15095. * values for a readable error message
  15096. *
  15097. * @param lView the lView containing the DOM
  15098. * @param tNode the tNode
  15099. * @param isViewContainerAnchor boolean
  15100. * @returns string
  15101. */
  15102. function describeExpectedDom(lView, tNode, isViewContainerAnchor) {
  15103. const spacer = ' ';
  15104. let content = '';
  15105. if (tNode.prev) {
  15106. content += spacer + '…\n';
  15107. content += spacer + describeTNode(tNode.prev) + '\n';
  15108. }
  15109. else if (tNode.type && tNode.type & 12 /* TNodeType.AnyContainer */) {
  15110. content += spacer + '…\n';
  15111. }
  15112. if (isViewContainerAnchor) {
  15113. content += spacer + describeTNode(tNode) + '\n';
  15114. content += spacer + `<!-- container --> ${AT_THIS_LOCATION}\n`;
  15115. }
  15116. else {
  15117. content += spacer + describeTNode(tNode) + ` ${AT_THIS_LOCATION}\n`;
  15118. }
  15119. content += spacer + '…\n';
  15120. const parentRNode = tNode.type ? getParentRElement(lView[TVIEW], tNode, lView) : null;
  15121. if (parentRNode) {
  15122. content = describeRNode(parentRNode, '\n' + content);
  15123. }
  15124. return content;
  15125. }
  15126. /**
  15127. * Builds the string containing the DOM present around a given RNode for a
  15128. * readable error message
  15129. *
  15130. * @param node the RNode
  15131. * @returns string
  15132. */
  15133. function describeDomFromNode(node) {
  15134. const spacer = ' ';
  15135. let content = '';
  15136. const currentNode = node;
  15137. if (currentNode.previousSibling) {
  15138. content += spacer + '…\n';
  15139. content += spacer + describeRNode(currentNode.previousSibling) + '\n';
  15140. }
  15141. content += spacer + describeRNode(currentNode) + ` ${AT_THIS_LOCATION}\n`;
  15142. if (node.nextSibling) {
  15143. content += spacer + '…\n';
  15144. }
  15145. if (node.parentNode) {
  15146. content = describeRNode(currentNode.parentNode, '\n' + content);
  15147. }
  15148. return content;
  15149. }
  15150. /**
  15151. * Shortens the description of a given RNode by its type for readability
  15152. *
  15153. * @param nodeType the type of node
  15154. * @param tagName the node tag name
  15155. * @param textContent the text content in the node
  15156. * @returns string
  15157. */
  15158. function shortRNodeDescription(nodeType, tagName, textContent) {
  15159. switch (nodeType) {
  15160. case Node.ELEMENT_NODE:
  15161. return `<${tagName.toLowerCase()}>`;
  15162. case Node.TEXT_NODE:
  15163. const content = textContent ? ` (with the "${shorten(textContent)}" content)` : '';
  15164. return `a text node${content}`;
  15165. case Node.COMMENT_NODE:
  15166. return 'a comment node';
  15167. default:
  15168. return `#node(nodeType=${nodeType})`;
  15169. }
  15170. }
  15171. /**
  15172. * Builds the footer hydration error message
  15173. *
  15174. * @param componentClassName the name of the component class
  15175. * @returns string
  15176. */
  15177. function getHydrationErrorFooter(componentClassName) {
  15178. const componentInfo = componentClassName ? `the "${componentClassName}"` : 'corresponding';
  15179. return (`To fix this problem:\n` +
  15180. ` * check ${componentInfo} component for hydration-related issues\n` +
  15181. ` * check to see if your template has valid HTML structure\n` +
  15182. ` * or skip hydration by adding the \`ngSkipHydration\` attribute ` +
  15183. `to its host node in a template\n\n`);
  15184. }
  15185. /**
  15186. * An attribute related note for hydration errors
  15187. */
  15188. function getHydrationAttributeNote() {
  15189. return ('Note: attributes are only displayed to better represent the DOM' +
  15190. ' but have no effect on hydration mismatches.\n\n');
  15191. }
  15192. // Node string utility functions
  15193. /**
  15194. * Strips all newlines out of a given string
  15195. *
  15196. * @param input a string to be cleared of new line characters
  15197. * @returns
  15198. */
  15199. function stripNewlines(input) {
  15200. return input.replace(/\s+/gm, '');
  15201. }
  15202. /**
  15203. * Reduces a string down to a maximum length of characters with ellipsis for readability
  15204. *
  15205. * @param input a string input
  15206. * @param maxLength a maximum length in characters
  15207. * @returns string
  15208. */
  15209. function shorten(input, maxLength = 50) {
  15210. if (!input) {
  15211. return '';
  15212. }
  15213. input = stripNewlines(input);
  15214. return input.length > maxLength ? `${input.substring(0, maxLength - 1)}…` : input;
  15215. }
  15216. /**
  15217. * Find a node in front of which `currentTNode` should be inserted (takes i18n into account).
  15218. *
  15219. * This method determines the `RNode` in front of which we should insert the `currentRNode`. This
  15220. * takes `TNode.insertBeforeIndex` into account.
  15221. *
  15222. * @param parentTNode parent `TNode`
  15223. * @param currentTNode current `TNode` (The node which we would like to insert into the DOM)
  15224. * @param lView current `LView`
  15225. */
  15226. function getInsertInFrontOfRNodeWithI18n(parentTNode, currentTNode, lView) {
  15227. const tNodeInsertBeforeIndex = currentTNode.insertBeforeIndex;
  15228. const insertBeforeIndex = Array.isArray(tNodeInsertBeforeIndex)
  15229. ? tNodeInsertBeforeIndex[0]
  15230. : tNodeInsertBeforeIndex;
  15231. if (insertBeforeIndex === null) {
  15232. return getInsertInFrontOfRNodeWithNoI18n(parentTNode, currentTNode, lView);
  15233. }
  15234. else {
  15235. ngDevMode && assertIndexInRange(lView, insertBeforeIndex);
  15236. return unwrapRNode(lView[insertBeforeIndex]);
  15237. }
  15238. }
  15239. /**
  15240. * Process `TNode.insertBeforeIndex` by adding i18n text nodes.
  15241. *
  15242. * See `TNode.insertBeforeIndex`
  15243. */
  15244. function processI18nInsertBefore(renderer, childTNode, lView, childRNode, parentRElement) {
  15245. const tNodeInsertBeforeIndex = childTNode.insertBeforeIndex;
  15246. if (Array.isArray(tNodeInsertBeforeIndex)) {
  15247. // An array indicates that there are i18n nodes that need to be added as children of this
  15248. // `childRNode`. These i18n nodes were created before this `childRNode` was available and so
  15249. // only now can be added. The first element of the array is the normal index where we should
  15250. // insert the `childRNode`. Additional elements are the extra nodes to be added as children of
  15251. // `childRNode`.
  15252. ngDevMode && assertDomNode(childRNode);
  15253. let i18nParent = childRNode;
  15254. let anchorRNode = null;
  15255. if (!(childTNode.type & 3 /* TNodeType.AnyRNode */)) {
  15256. anchorRNode = i18nParent;
  15257. i18nParent = parentRElement;
  15258. }
  15259. if (i18nParent !== null && childTNode.componentOffset === -1) {
  15260. for (let i = 1; i < tNodeInsertBeforeIndex.length; i++) {
  15261. // No need to `unwrapRNode` because all of the indexes point to i18n text nodes.
  15262. // see `assertDomNode` below.
  15263. const i18nChild = lView[tNodeInsertBeforeIndex[i]];
  15264. nativeInsertBefore(renderer, i18nParent, i18nChild, anchorRNode, false);
  15265. }
  15266. }
  15267. }
  15268. }
  15269. function getOrCreateTNode(tView, index, type, name, attrs) {
  15270. ngDevMode &&
  15271. index !== 0 && // 0 are bogus nodes and they are OK. See `createContainerRef` in
  15272. // `view_engine_compatibility` for additional context.
  15273. assertGreaterThanOrEqual(index, HEADER_OFFSET, "TNodes can't be in the LView header.");
  15274. // Keep this function short, so that the VM will inline it.
  15275. ngDevMode && assertPureTNodeType(type);
  15276. let tNode = tView.data[index];
  15277. if (tNode === null) {
  15278. tNode = createTNodeAtIndex(tView, index, type, name, attrs);
  15279. if (isInI18nBlock()) {
  15280. // If we are in i18n block then all elements should be pre declared through `Placeholder`
  15281. // See `TNodeType.Placeholder` and `LFrame.inI18n` for more context.
  15282. // If the `TNode` was not pre-declared than it means it was not mentioned which means it was
  15283. // removed, so we mark it as detached.
  15284. tNode.flags |= 32 /* TNodeFlags.isDetached */;
  15285. }
  15286. }
  15287. else if (tNode.type & 64 /* TNodeType.Placeholder */) {
  15288. tNode.type = type;
  15289. tNode.value = name;
  15290. tNode.attrs = attrs;
  15291. const parent = getCurrentParentTNode();
  15292. tNode.injectorIndex = parent === null ? -1 : parent.injectorIndex;
  15293. ngDevMode && assertTNodeForTView(tNode, tView);
  15294. ngDevMode && assertEqual(index, tNode.index, 'Expecting same index');
  15295. }
  15296. setCurrentTNode(tNode, true);
  15297. return tNode;
  15298. }
  15299. function createTNodeAtIndex(tView, index, type, name, attrs) {
  15300. const currentTNode = getCurrentTNodePlaceholderOk();
  15301. const isParent = isCurrentTNodeParent();
  15302. const parent = isParent ? currentTNode : currentTNode && currentTNode.parent;
  15303. // Parents cannot cross component boundaries because components will be used in multiple places.
  15304. const tNode = (tView.data[index] = createTNode(tView, parent, type, index, name, attrs));
  15305. // Assign a pointer to the first child node of a given view. The first node is not always the one
  15306. // at index 0, in case of i18n, index 0 can be the instruction `i18nStart` and the first node has
  15307. // the index 1 or more, so we can't just check node index.
  15308. linkTNodeInTView(tView, tNode, currentTNode, isParent);
  15309. return tNode;
  15310. }
  15311. function linkTNodeInTView(tView, tNode, currentTNode, isParent) {
  15312. if (tView.firstChild === null) {
  15313. tView.firstChild = tNode;
  15314. }
  15315. if (currentTNode !== null) {
  15316. if (isParent) {
  15317. // FIXME(misko): This logic looks unnecessarily complicated. Could we simplify?
  15318. if (currentTNode.child == null && tNode.parent !== null) {
  15319. // We are in the same view, which means we are adding content node to the parent view.
  15320. currentTNode.child = tNode;
  15321. }
  15322. }
  15323. else {
  15324. if (currentTNode.next === null) {
  15325. // In the case of i18n the `currentTNode` may already be linked, in which case we don't want
  15326. // to break the links which i18n created.
  15327. currentTNode.next = tNode;
  15328. tNode.prev = currentTNode;
  15329. }
  15330. }
  15331. }
  15332. }
  15333. function createTNode(tView, tParent, type, index, value, attrs) {
  15334. ngDevMode &&
  15335. index !== 0 && // 0 are bogus nodes and they are OK. See `createContainerRef` in
  15336. // `view_engine_compatibility` for additional context.
  15337. assertGreaterThanOrEqual(index, HEADER_OFFSET, "TNodes can't be in the LView header.");
  15338. ngDevMode && assertNotSame(attrs, undefined, "'undefined' is not valid value for 'attrs'");
  15339. ngDevMode && ngDevMode.tNode++;
  15340. ngDevMode && tParent && assertTNodeForTView(tParent, tView);
  15341. let injectorIndex = tParent ? tParent.injectorIndex : -1;
  15342. let flags = 0;
  15343. if (isInSkipHydrationBlock$1()) {
  15344. flags |= 128 /* TNodeFlags.inSkipHydrationBlock */;
  15345. }
  15346. // TODO: would it be helpful to use a prototypal inheritance here, similar to the way we do so with signals?
  15347. const tNode = {
  15348. type,
  15349. index,
  15350. insertBeforeIndex: null,
  15351. injectorIndex,
  15352. directiveStart: -1,
  15353. directiveEnd: -1,
  15354. directiveStylingLast: -1,
  15355. componentOffset: -1,
  15356. propertyBindings: null,
  15357. flags,
  15358. providerIndexes: 0,
  15359. value: value,
  15360. attrs: attrs,
  15361. mergedAttrs: null,
  15362. localNames: null,
  15363. initialInputs: null,
  15364. inputs: null,
  15365. hostDirectiveInputs: null,
  15366. outputs: null,
  15367. hostDirectiveOutputs: null,
  15368. directiveToIndex: null,
  15369. tView: null,
  15370. next: null,
  15371. prev: null,
  15372. projectionNext: null,
  15373. child: null,
  15374. parent: tParent,
  15375. projection: null,
  15376. styles: null,
  15377. stylesWithoutHost: null,
  15378. residualStyles: undefined,
  15379. classes: null,
  15380. classesWithoutHost: null,
  15381. residualClasses: undefined,
  15382. classBindings: 0,
  15383. styleBindings: 0,
  15384. };
  15385. if (ngDevMode) {
  15386. // For performance reasons it is important that the tNode retains the same shape during runtime.
  15387. // (To make sure that all of the code is monomorphic.) For this reason we seal the object to
  15388. // prevent class transitions.
  15389. Object.seal(tNode);
  15390. }
  15391. return tNode;
  15392. }
  15393. /**
  15394. * Add `tNode` to `previousTNodes` list and update relevant `TNode`s in `previousTNodes` list
  15395. * `tNode.insertBeforeIndex`.
  15396. *
  15397. * Things to keep in mind:
  15398. * 1. All i18n text nodes are encoded as `TNodeType.Element` and are created eagerly by the
  15399. * `ɵɵi18nStart` instruction.
  15400. * 2. All `TNodeType.Placeholder` `TNodes` are elements which will be created later by
  15401. * `ɵɵelementStart` instruction.
  15402. * 3. `ɵɵelementStart` instruction will create `TNode`s in the ascending `TNode.index` order. (So a
  15403. * smaller index `TNode` is guaranteed to be created before a larger one)
  15404. *
  15405. * We use the above three invariants to determine `TNode.insertBeforeIndex`.
  15406. *
  15407. * In an ideal world `TNode.insertBeforeIndex` would always be `TNode.next.index`. However,
  15408. * this will not work because `TNode.next.index` may be larger than `TNode.index` which means that
  15409. * the next node is not yet created and therefore we can't insert in front of it.
  15410. *
  15411. * Rule1: `TNode.insertBeforeIndex = null` if `TNode.next === null` (Initial condition, as we don't
  15412. * know if there will be further `TNode`s inserted after.)
  15413. * Rule2: If `previousTNode` is created after the `tNode` being inserted, then
  15414. * `previousTNode.insertBeforeNode = tNode.index` (So when a new `tNode` is added we check
  15415. * previous to see if we can update its `insertBeforeTNode`)
  15416. *
  15417. * See `TNode.insertBeforeIndex` for more context.
  15418. *
  15419. * @param previousTNodes A list of previous TNodes so that we can easily traverse `TNode`s in
  15420. * reverse order. (If `TNode` would have `previous` this would not be necessary.)
  15421. * @param newTNode A TNode to add to the `previousTNodes` list.
  15422. */
  15423. function addTNodeAndUpdateInsertBeforeIndex(previousTNodes, newTNode) {
  15424. // Start with Rule1
  15425. ngDevMode &&
  15426. assertEqual(newTNode.insertBeforeIndex, null, 'We expect that insertBeforeIndex is not set');
  15427. previousTNodes.push(newTNode);
  15428. if (previousTNodes.length > 1) {
  15429. for (let i = previousTNodes.length - 2; i >= 0; i--) {
  15430. const existingTNode = previousTNodes[i];
  15431. // Text nodes are created eagerly and so they don't need their `indexBeforeIndex` updated.
  15432. // It is safe to ignore them.
  15433. if (!isI18nText(existingTNode)) {
  15434. if (isNewTNodeCreatedBefore(existingTNode, newTNode) &&
  15435. getInsertBeforeIndex(existingTNode) === null) {
  15436. // If it was created before us in time, (and it does not yet have `insertBeforeIndex`)
  15437. // then add the `insertBeforeIndex`.
  15438. setInsertBeforeIndex(existingTNode, newTNode.index);
  15439. }
  15440. }
  15441. }
  15442. }
  15443. }
  15444. function isI18nText(tNode) {
  15445. return !(tNode.type & 64 /* TNodeType.Placeholder */);
  15446. }
  15447. function isNewTNodeCreatedBefore(existingTNode, newTNode) {
  15448. return isI18nText(newTNode) || existingTNode.index > newTNode.index;
  15449. }
  15450. function getInsertBeforeIndex(tNode) {
  15451. const index = tNode.insertBeforeIndex;
  15452. return Array.isArray(index) ? index[0] : index;
  15453. }
  15454. function setInsertBeforeIndex(tNode, value) {
  15455. const index = tNode.insertBeforeIndex;
  15456. if (Array.isArray(index)) {
  15457. // Array is stored if we have to insert child nodes. See `TNode.insertBeforeIndex`
  15458. index[0] = value;
  15459. }
  15460. else {
  15461. setI18nHandling(getInsertInFrontOfRNodeWithI18n, processI18nInsertBefore);
  15462. tNode.insertBeforeIndex = value;
  15463. }
  15464. }
  15465. /**
  15466. * Retrieve `TIcu` at a given `index`.
  15467. *
  15468. * The `TIcu` can be stored either directly (if it is nested ICU) OR
  15469. * it is stored inside tho `TIcuContainer` if it is top level ICU.
  15470. *
  15471. * The reason for this is that the top level ICU need a `TNode` so that they are part of the render
  15472. * tree, but nested ICU's have no TNode, because we don't know ahead of time if the nested ICU is
  15473. * expressed (parent ICU may have selected a case which does not contain it.)
  15474. *
  15475. * @param tView Current `TView`.
  15476. * @param index Index where the value should be read from.
  15477. */
  15478. function getTIcu(tView, index) {
  15479. const value = tView.data[index];
  15480. if (value === null || typeof value === 'string')
  15481. return null;
  15482. if (ngDevMode &&
  15483. !(value.hasOwnProperty('tView') || value.hasOwnProperty('currentCaseLViewIndex'))) {
  15484. throwError("We expect to get 'null'|'TIcu'|'TIcuContainer', but got: " + value);
  15485. }
  15486. // Here the `value.hasOwnProperty('currentCaseLViewIndex')` is a polymorphic read as it can be
  15487. // either TIcu or TIcuContainerNode. This is not ideal, but we still think it is OK because it
  15488. // will be just two cases which fits into the browser inline cache (inline cache can take up to
  15489. // 4)
  15490. const tIcu = value.hasOwnProperty('currentCaseLViewIndex')
  15491. ? value
  15492. : value.value;
  15493. ngDevMode && assertTIcu(tIcu);
  15494. return tIcu;
  15495. }
  15496. /**
  15497. * Store `TIcu` at a give `index`.
  15498. *
  15499. * The `TIcu` can be stored either directly (if it is nested ICU) OR
  15500. * it is stored inside tho `TIcuContainer` if it is top level ICU.
  15501. *
  15502. * The reason for this is that the top level ICU need a `TNode` so that they are part of the render
  15503. * tree, but nested ICU's have no TNode, because we don't know ahead of time if the nested ICU is
  15504. * expressed (parent ICU may have selected a case which does not contain it.)
  15505. *
  15506. * @param tView Current `TView`.
  15507. * @param index Index where the value should be stored at in `Tview.data`
  15508. * @param tIcu The TIcu to store.
  15509. */
  15510. function setTIcu(tView, index, tIcu) {
  15511. const tNode = tView.data[index];
  15512. ngDevMode &&
  15513. assertEqual(tNode === null || tNode.hasOwnProperty('tView'), true, "We expect to get 'null'|'TIcuContainer'");
  15514. if (tNode === null) {
  15515. tView.data[index] = tIcu;
  15516. }
  15517. else {
  15518. ngDevMode && assertTNodeType(tNode, 32 /* TNodeType.Icu */);
  15519. tNode.value = tIcu;
  15520. }
  15521. }
  15522. /**
  15523. * Set `TNode.insertBeforeIndex` taking the `Array` into account.
  15524. *
  15525. * See `TNode.insertBeforeIndex`
  15526. */
  15527. function setTNodeInsertBeforeIndex(tNode, index) {
  15528. ngDevMode && assertTNode(tNode);
  15529. let insertBeforeIndex = tNode.insertBeforeIndex;
  15530. if (insertBeforeIndex === null) {
  15531. setI18nHandling(getInsertInFrontOfRNodeWithI18n, processI18nInsertBefore);
  15532. insertBeforeIndex = tNode.insertBeforeIndex = [
  15533. null /* may be updated to number later */,
  15534. index,
  15535. ];
  15536. }
  15537. else {
  15538. assertEqual(Array.isArray(insertBeforeIndex), true, 'Expecting array here');
  15539. insertBeforeIndex.push(index);
  15540. }
  15541. }
  15542. /**
  15543. * Create `TNode.type=TNodeType.Placeholder` node.
  15544. *
  15545. * See `TNodeType.Placeholder` for more information.
  15546. */
  15547. function createTNodePlaceholder(tView, previousTNodes, index) {
  15548. const tNode = createTNodeAtIndex(tView, index, 64 /* TNodeType.Placeholder */, null, null);
  15549. addTNodeAndUpdateInsertBeforeIndex(previousTNodes, tNode);
  15550. return tNode;
  15551. }
  15552. /**
  15553. * Returns current ICU case.
  15554. *
  15555. * ICU cases are stored as index into the `TIcu.cases`.
  15556. * At times it is necessary to communicate that the ICU case just switched and that next ICU update
  15557. * should update all bindings regardless of the mask. In such a case the we store negative numbers
  15558. * for cases which have just been switched. This function removes the negative flag.
  15559. */
  15560. function getCurrentICUCaseIndex(tIcu, lView) {
  15561. const currentCase = lView[tIcu.currentCaseLViewIndex];
  15562. return currentCase === null ? currentCase : currentCase < 0 ? ~currentCase : currentCase;
  15563. }
  15564. function getParentFromIcuCreateOpCode(mergedCode) {
  15565. return mergedCode >>> 17 /* IcuCreateOpCode.SHIFT_PARENT */;
  15566. }
  15567. function getRefFromIcuCreateOpCode(mergedCode) {
  15568. return (mergedCode & 131070 /* IcuCreateOpCode.MASK_REF */) >>> 1 /* IcuCreateOpCode.SHIFT_REF */;
  15569. }
  15570. function getInstructionFromIcuCreateOpCode(mergedCode) {
  15571. return mergedCode & 1 /* IcuCreateOpCode.MASK_INSTRUCTION */;
  15572. }
  15573. function icuCreateOpCode(opCode, parentIdx, refIdx) {
  15574. ngDevMode && assertGreaterThanOrEqual(parentIdx, 0, 'Missing parent index');
  15575. ngDevMode && assertGreaterThan(refIdx, 0, 'Missing ref index');
  15576. return (opCode | (parentIdx << 17 /* IcuCreateOpCode.SHIFT_PARENT */) | (refIdx << 1 /* IcuCreateOpCode.SHIFT_REF */));
  15577. }
  15578. // Returns whether the given value corresponds to a root template message,
  15579. // or a sub-template.
  15580. function isRootTemplateMessage(subTemplateIndex) {
  15581. return subTemplateIndex === -1;
  15582. }
  15583. function enterIcu(state, tIcu, lView) {
  15584. state.index = 0;
  15585. const currentCase = getCurrentICUCaseIndex(tIcu, lView);
  15586. if (currentCase !== null) {
  15587. ngDevMode && assertNumberInRange(currentCase, 0, tIcu.cases.length - 1);
  15588. state.removes = tIcu.remove[currentCase];
  15589. }
  15590. else {
  15591. state.removes = EMPTY_ARRAY;
  15592. }
  15593. }
  15594. function icuContainerIteratorNext(state) {
  15595. if (state.index < state.removes.length) {
  15596. const removeOpCode = state.removes[state.index++];
  15597. ngDevMode && assertNumber(removeOpCode, 'Expecting OpCode number');
  15598. if (removeOpCode > 0) {
  15599. const rNode = state.lView[removeOpCode];
  15600. ngDevMode && assertDomNode(rNode);
  15601. return rNode;
  15602. }
  15603. else {
  15604. state.stack.push(state.index, state.removes);
  15605. // ICUs are represented by negative indices
  15606. const tIcuIndex = ~removeOpCode;
  15607. const tIcu = state.lView[TVIEW].data[tIcuIndex];
  15608. ngDevMode && assertTIcu(tIcu);
  15609. enterIcu(state, tIcu, state.lView);
  15610. return icuContainerIteratorNext(state);
  15611. }
  15612. }
  15613. else {
  15614. if (state.stack.length === 0) {
  15615. return null;
  15616. }
  15617. else {
  15618. state.removes = state.stack.pop();
  15619. state.index = state.stack.pop();
  15620. return icuContainerIteratorNext(state);
  15621. }
  15622. }
  15623. }
  15624. function loadIcuContainerVisitor() {
  15625. const _state = {
  15626. stack: [],
  15627. index: -1,
  15628. };
  15629. /**
  15630. * Retrieves a set of root nodes from `TIcu.remove`. Used by `TNodeType.ICUContainer`
  15631. * to determine which root belong to the ICU.
  15632. *
  15633. * Example of usage.
  15634. * ```ts
  15635. * const nextRNode = icuContainerIteratorStart(tIcuContainerNode, lView);
  15636. * let rNode: RNode|null;
  15637. * while(rNode = nextRNode()) {
  15638. * console.log(rNode);
  15639. * }
  15640. * ```
  15641. *
  15642. * @param tIcuContainerNode Current `TIcuContainerNode`
  15643. * @param lView `LView` where the `RNode`s should be looked up.
  15644. */
  15645. function icuContainerIteratorStart(tIcuContainerNode, lView) {
  15646. _state.lView = lView;
  15647. while (_state.stack.length)
  15648. _state.stack.pop();
  15649. ngDevMode && assertTNodeForLView(tIcuContainerNode, lView);
  15650. enterIcu(_state, tIcuContainerNode.value, lView);
  15651. return icuContainerIteratorNext.bind(null, _state);
  15652. }
  15653. return icuContainerIteratorStart;
  15654. }
  15655. function createIcuIterator(tIcu, lView) {
  15656. const state = {
  15657. stack: [],
  15658. index: -1,
  15659. lView,
  15660. };
  15661. ngDevMode && assertTIcu(tIcu);
  15662. enterIcu(state, tIcu, lView);
  15663. return icuContainerIteratorNext.bind(null, state);
  15664. }
  15665. /**
  15666. * Regexp that extracts a reference node information from the compressed node location.
  15667. * The reference node is represented as either:
  15668. * - a number which points to an LView slot
  15669. * - the `b` char which indicates that the lookup should start from the `document.body`
  15670. * - the `h` char to start lookup from the component host node (`lView[HOST]`)
  15671. */
  15672. const REF_EXTRACTOR_REGEXP = /* @__PURE__ */ new RegExp(`^(\\d+)*(${REFERENCE_NODE_BODY}|${REFERENCE_NODE_HOST})*(.*)`);
  15673. /**
  15674. * Helper function that takes a reference node location and a set of navigation steps
  15675. * (from the reference node) to a target node and outputs a string that represents
  15676. * a location.
  15677. *
  15678. * For example, given: referenceNode = 'b' (body) and path = ['firstChild', 'firstChild',
  15679. * 'nextSibling'], the function returns: `bf2n`.
  15680. */
  15681. function compressNodeLocation(referenceNode, path) {
  15682. const result = [referenceNode];
  15683. for (const segment of path) {
  15684. const lastIdx = result.length - 1;
  15685. if (lastIdx > 0 && result[lastIdx - 1] === segment) {
  15686. // An empty string in a count slot represents 1 occurrence of an instruction.
  15687. const value = (result[lastIdx] || 1);
  15688. result[lastIdx] = value + 1;
  15689. }
  15690. else {
  15691. // Adding a new segment to the path.
  15692. // Using an empty string in a counter field to avoid encoding `1`s
  15693. // into the path, since they are implicit (e.g. `f1n1` vs `fn`), so
  15694. // it's enough to have a single char in this case.
  15695. result.push(segment, '');
  15696. }
  15697. }
  15698. return result.join('');
  15699. }
  15700. /**
  15701. * Helper function that reverts the `compressNodeLocation` and transforms a given
  15702. * string into an array where at 0th position there is a reference node info and
  15703. * after that it contains information (in pairs) about a navigation step and the
  15704. * number of repetitions.
  15705. *
  15706. * For example, the path like 'bf2n' will be transformed to:
  15707. * ['b', 'firstChild', 2, 'nextSibling', 1].
  15708. *
  15709. * This information is later consumed by the code that navigates the DOM to find
  15710. * a given node by its location.
  15711. */
  15712. function decompressNodeLocation(path) {
  15713. const matches = path.match(REF_EXTRACTOR_REGEXP);
  15714. const [_, refNodeId, refNodeName, rest] = matches;
  15715. // If a reference node is represented by an index, transform it to a number.
  15716. const ref = refNodeId ? parseInt(refNodeId, 10) : refNodeName;
  15717. const steps = [];
  15718. // Match all segments in a path.
  15719. for (const [_, step, count] of rest.matchAll(/(f|n)(\d*)/g)) {
  15720. const repeat = parseInt(count, 10) || 1;
  15721. steps.push(step, repeat);
  15722. }
  15723. return [ref, ...steps];
  15724. }
  15725. /** Whether current TNode is a first node in an <ng-container>. */
  15726. function isFirstElementInNgContainer(tNode) {
  15727. return !tNode.prev && tNode.parent?.type === 8 /* TNodeType.ElementContainer */;
  15728. }
  15729. /** Returns an instruction index (subtracting HEADER_OFFSET). */
  15730. function getNoOffsetIndex(tNode) {
  15731. return tNode.index - HEADER_OFFSET;
  15732. }
  15733. /**
  15734. * Check whether a given node exists, but is disconnected from the DOM.
  15735. */
  15736. function isDisconnectedNode(tNode, lView) {
  15737. return (!(tNode.type & (16 /* TNodeType.Projection */ | 128 /* TNodeType.LetDeclaration */)) &&
  15738. !!lView[tNode.index] &&
  15739. isDisconnectedRNode(unwrapRNode(lView[tNode.index])));
  15740. }
  15741. /**
  15742. * Check whether the given node exists, but is disconnected from the DOM.
  15743. *
  15744. * Note: we leverage the fact that we have this information available in the DOM emulation
  15745. * layer (in Domino) for now. Longer-term solution should not rely on the DOM emulation and
  15746. * only use internal data structures and state to compute this information.
  15747. */
  15748. function isDisconnectedRNode(rNode) {
  15749. return !!rNode && !rNode.isConnected;
  15750. }
  15751. /**
  15752. * Locate a node in an i18n tree that corresponds to a given instruction index.
  15753. *
  15754. * @param hydrationInfo The hydration annotation data
  15755. * @param noOffsetIndex the instruction index
  15756. * @returns an RNode that corresponds to the instruction index
  15757. */
  15758. function locateI18nRNodeByIndex(hydrationInfo, noOffsetIndex) {
  15759. const i18nNodes = hydrationInfo.i18nNodes;
  15760. if (i18nNodes) {
  15761. return i18nNodes.get(noOffsetIndex);
  15762. }
  15763. return undefined;
  15764. }
  15765. /**
  15766. * Attempt to locate an RNode by a path, if it exists.
  15767. *
  15768. * @param hydrationInfo The hydration annotation data
  15769. * @param lView the current lView
  15770. * @param noOffsetIndex the instruction index
  15771. * @returns an RNode that corresponds to the instruction index or null if no path exists
  15772. */
  15773. function tryLocateRNodeByPath(hydrationInfo, lView, noOffsetIndex) {
  15774. const nodes = hydrationInfo.data[NODES];
  15775. const path = nodes?.[noOffsetIndex];
  15776. return path ? locateRNodeByPath(path, lView) : null;
  15777. }
  15778. /**
  15779. * Locate a node in DOM tree that corresponds to a given TNode.
  15780. *
  15781. * @param hydrationInfo The hydration annotation data
  15782. * @param tView the current tView
  15783. * @param lView the current lView
  15784. * @param tNode the current tNode
  15785. * @returns an RNode that represents a given tNode
  15786. */
  15787. function locateNextRNode(hydrationInfo, tView, lView, tNode) {
  15788. const noOffsetIndex = getNoOffsetIndex(tNode);
  15789. let native = locateI18nRNodeByIndex(hydrationInfo, noOffsetIndex);
  15790. if (native === undefined) {
  15791. const nodes = hydrationInfo.data[NODES];
  15792. if (nodes?.[noOffsetIndex]) {
  15793. // We know the exact location of the node.
  15794. native = locateRNodeByPath(nodes[noOffsetIndex], lView);
  15795. }
  15796. else if (tView.firstChild === tNode) {
  15797. // We create a first node in this view, so we use a reference
  15798. // to the first child in this DOM segment.
  15799. native = hydrationInfo.firstChild;
  15800. }
  15801. else {
  15802. // Locate a node based on a previous sibling or a parent node.
  15803. const previousTNodeParent = tNode.prev === null;
  15804. const previousTNode = (tNode.prev ?? tNode.parent);
  15805. ngDevMode &&
  15806. assertDefined(previousTNode, 'Unexpected state: current TNode does not have a connection ' +
  15807. 'to the previous node or a parent node.');
  15808. if (isFirstElementInNgContainer(tNode)) {
  15809. const noOffsetParentIndex = getNoOffsetIndex(tNode.parent);
  15810. native = getSegmentHead(hydrationInfo, noOffsetParentIndex);
  15811. }
  15812. else {
  15813. let previousRElement = getNativeByTNode(previousTNode, lView);
  15814. if (previousTNodeParent) {
  15815. native = previousRElement.firstChild;
  15816. }
  15817. else {
  15818. // If the previous node is an element, but it also has container info,
  15819. // this means that we are processing a node like `<div #vcrTarget>`, which is
  15820. // represented in the DOM as `<div></div>...<!--container-->`.
  15821. // In this case, there are nodes *after* this element and we need to skip
  15822. // all of them to reach an element that we are looking for.
  15823. const noOffsetPrevSiblingIndex = getNoOffsetIndex(previousTNode);
  15824. const segmentHead = getSegmentHead(hydrationInfo, noOffsetPrevSiblingIndex);
  15825. if (previousTNode.type === 2 /* TNodeType.Element */ && segmentHead) {
  15826. const numRootNodesToSkip = calcSerializedContainerSize(hydrationInfo, noOffsetPrevSiblingIndex);
  15827. // `+1` stands for an anchor comment node after all the views in this container.
  15828. const nodesToSkip = numRootNodesToSkip + 1;
  15829. // First node after this segment.
  15830. native = siblingAfter(nodesToSkip, segmentHead);
  15831. }
  15832. else {
  15833. native = previousRElement.nextSibling;
  15834. }
  15835. }
  15836. }
  15837. }
  15838. }
  15839. return native;
  15840. }
  15841. /**
  15842. * Skips over a specified number of nodes and returns the next sibling node after that.
  15843. */
  15844. function siblingAfter(skip, from) {
  15845. let currentNode = from;
  15846. for (let i = 0; i < skip; i++) {
  15847. ngDevMode && validateSiblingNodeExists(currentNode);
  15848. currentNode = currentNode.nextSibling;
  15849. }
  15850. return currentNode;
  15851. }
  15852. /**
  15853. * Helper function to produce a string representation of the navigation steps
  15854. * (in terms of `nextSibling` and `firstChild` navigations). Used in error
  15855. * messages in dev mode.
  15856. */
  15857. function stringifyNavigationInstructions(instructions) {
  15858. const container = [];
  15859. for (let i = 0; i < instructions.length; i += 2) {
  15860. const step = instructions[i];
  15861. const repeat = instructions[i + 1];
  15862. for (let r = 0; r < repeat; r++) {
  15863. container.push(step === NODE_NAVIGATION_STEP_FIRST_CHILD ? 'firstChild' : 'nextSibling');
  15864. }
  15865. }
  15866. return container.join('.');
  15867. }
  15868. /**
  15869. * Helper function that navigates from a starting point node (the `from` node)
  15870. * using provided set of navigation instructions (within `path` argument).
  15871. */
  15872. function navigateToNode(from, instructions) {
  15873. let node = from;
  15874. for (let i = 0; i < instructions.length; i += 2) {
  15875. const step = instructions[i];
  15876. const repeat = instructions[i + 1];
  15877. for (let r = 0; r < repeat; r++) {
  15878. if (ngDevMode && !node) {
  15879. throw nodeNotFoundAtPathError(from, stringifyNavigationInstructions(instructions));
  15880. }
  15881. switch (step) {
  15882. case NODE_NAVIGATION_STEP_FIRST_CHILD:
  15883. node = node.firstChild;
  15884. break;
  15885. case NODE_NAVIGATION_STEP_NEXT_SIBLING:
  15886. node = node.nextSibling;
  15887. break;
  15888. }
  15889. }
  15890. }
  15891. if (ngDevMode && !node) {
  15892. throw nodeNotFoundAtPathError(from, stringifyNavigationInstructions(instructions));
  15893. }
  15894. return node;
  15895. }
  15896. /**
  15897. * Locates an RNode given a set of navigation instructions (which also contains
  15898. * a starting point node info).
  15899. */
  15900. function locateRNodeByPath(path, lView) {
  15901. const [referenceNode, ...navigationInstructions] = decompressNodeLocation(path);
  15902. let ref;
  15903. if (referenceNode === REFERENCE_NODE_HOST) {
  15904. ref = lView[DECLARATION_COMPONENT_VIEW][HOST];
  15905. }
  15906. else if (referenceNode === REFERENCE_NODE_BODY) {
  15907. ref = ɵɵresolveBody(lView[DECLARATION_COMPONENT_VIEW][HOST]);
  15908. }
  15909. else {
  15910. const parentElementId = Number(referenceNode);
  15911. ref = unwrapRNode(lView[parentElementId + HEADER_OFFSET]);
  15912. }
  15913. return navigateToNode(ref, navigationInstructions);
  15914. }
  15915. /**
  15916. * Generate a list of DOM navigation operations to get from node `start` to node `finish`.
  15917. *
  15918. * Note: assumes that node `start` occurs before node `finish` in an in-order traversal of the DOM
  15919. * tree. That is, we should be able to get from `start` to `finish` purely by using `.firstChild`
  15920. * and `.nextSibling` operations.
  15921. */
  15922. function navigateBetween(start, finish) {
  15923. if (start === finish) {
  15924. return [];
  15925. }
  15926. else if (start.parentElement == null || finish.parentElement == null) {
  15927. return null;
  15928. }
  15929. else if (start.parentElement === finish.parentElement) {
  15930. return navigateBetweenSiblings(start, finish);
  15931. }
  15932. else {
  15933. // `finish` is a child of its parent, so the parent will always have a child.
  15934. const parent = finish.parentElement;
  15935. const parentPath = navigateBetween(start, parent);
  15936. const childPath = navigateBetween(parent.firstChild, finish);
  15937. if (!parentPath || !childPath)
  15938. return null;
  15939. return [
  15940. // First navigate to `finish`'s parent
  15941. ...parentPath,
  15942. // Then to its first child.
  15943. NODE_NAVIGATION_STEP_FIRST_CHILD,
  15944. // And finally from that node to `finish` (maybe a no-op if we're already there).
  15945. ...childPath,
  15946. ];
  15947. }
  15948. }
  15949. /**
  15950. * Calculates a path between 2 sibling nodes (generates a number of `NextSibling` navigations).
  15951. * Returns `null` if no such path exists between the given nodes.
  15952. */
  15953. function navigateBetweenSiblings(start, finish) {
  15954. const nav = [];
  15955. let node = null;
  15956. for (node = start; node != null && node !== finish; node = node.nextSibling) {
  15957. nav.push(NODE_NAVIGATION_STEP_NEXT_SIBLING);
  15958. }
  15959. // If the `node` becomes `null` or `undefined` at the end, that means that we
  15960. // didn't find the `end` node, thus return `null` (which would trigger serialization
  15961. // error to be produced).
  15962. return node == null ? null : nav;
  15963. }
  15964. /**
  15965. * Calculates a path between 2 nodes in terms of `nextSibling` and `firstChild`
  15966. * navigations:
  15967. * - the `from` node is a known node, used as an starting point for the lookup
  15968. * (the `fromNodeName` argument is a string representation of the node).
  15969. * - the `to` node is a node that the runtime logic would be looking up,
  15970. * using the path generated by this function.
  15971. */
  15972. function calcPathBetween(from, to, fromNodeName) {
  15973. const path = navigateBetween(from, to);
  15974. return path === null ? null : compressNodeLocation(fromNodeName, path);
  15975. }
  15976. /**
  15977. * Invoked at serialization time (on the server) when a set of navigation
  15978. * instructions needs to be generated for a TNode.
  15979. */
  15980. function calcPathForNode(tNode, lView, excludedParentNodes) {
  15981. let parentTNode = tNode.parent;
  15982. let parentIndex;
  15983. let parentRNode;
  15984. let referenceNodeName;
  15985. // Skip over all parent nodes that are disconnected from the DOM, such nodes
  15986. // can not be used as anchors.
  15987. //
  15988. // This might happen in certain content projection-based use-cases, where
  15989. // a content of an element is projected and used, when a parent element
  15990. // itself remains detached from DOM. In this scenario we try to find a parent
  15991. // element that is attached to DOM and can act as an anchor instead.
  15992. //
  15993. // It can also happen that the parent node should be excluded, for example,
  15994. // because it belongs to an i18n block, which requires paths which aren't
  15995. // relative to other views in an i18n block.
  15996. while (parentTNode !== null &&
  15997. (isDisconnectedNode(parentTNode, lView) || excludedParentNodes?.has(parentTNode.index))) {
  15998. parentTNode = parentTNode.parent;
  15999. }
  16000. if (parentTNode === null || !(parentTNode.type & 3 /* TNodeType.AnyRNode */)) {
  16001. // If there is no parent TNode or a parent TNode does not represent an RNode
  16002. // (i.e. not a DOM node), use component host element as a reference node.
  16003. parentIndex = referenceNodeName = REFERENCE_NODE_HOST;
  16004. parentRNode = lView[DECLARATION_COMPONENT_VIEW][HOST];
  16005. }
  16006. else {
  16007. // Use parent TNode as a reference node.
  16008. parentIndex = parentTNode.index;
  16009. parentRNode = unwrapRNode(lView[parentIndex]);
  16010. referenceNodeName = renderStringify(parentIndex - HEADER_OFFSET);
  16011. }
  16012. let rNode = unwrapRNode(lView[tNode.index]);
  16013. if (tNode.type & (12 /* TNodeType.AnyContainer */ | 32 /* TNodeType.Icu */)) {
  16014. // For <ng-container> nodes, instead of serializing a reference
  16015. // to the anchor comment node, serialize a location of the first
  16016. // DOM element. Paired with the container size (serialized as a part
  16017. // of `ngh.containers`), it should give enough information for runtime
  16018. // to hydrate nodes in this container.
  16019. const firstRNode = getFirstNativeNode(lView, tNode);
  16020. // If container is not empty, use a reference to the first element,
  16021. // otherwise, rNode would point to an anchor comment node.
  16022. if (firstRNode) {
  16023. rNode = firstRNode;
  16024. }
  16025. }
  16026. let path = calcPathBetween(parentRNode, rNode, referenceNodeName);
  16027. if (path === null && parentRNode !== rNode) {
  16028. // Searching for a path between elements within a host node failed.
  16029. // Trying to find a path to an element starting from the `document.body` instead.
  16030. //
  16031. // Important note: this type of reference is relatively unstable, since Angular
  16032. // may not be able to control parts of the page that the runtime logic navigates
  16033. // through. This is mostly needed to cover "portals" use-case (like menus, dialog boxes,
  16034. // etc), where nodes are content-projected (including direct DOM manipulations) outside
  16035. // of the host node. The better solution is to provide APIs to work with "portals",
  16036. // at which point this code path would not be needed.
  16037. const body = parentRNode.ownerDocument.body;
  16038. path = calcPathBetween(body, rNode, REFERENCE_NODE_BODY);
  16039. if (path === null) {
  16040. // If the path is still empty, it's likely that this node is detached and
  16041. // won't be found during hydration.
  16042. throw nodeNotFoundError(lView, tNode);
  16043. }
  16044. }
  16045. return path;
  16046. }
  16047. /**
  16048. * Retrieves all comments nodes that contain ngh comments referring to a defer block
  16049. */
  16050. function gatherDeferBlocksCommentNodes(doc, node) {
  16051. const commentNodesIterator = doc.createNodeIterator(node, NodeFilter.SHOW_COMMENT, { acceptNode });
  16052. let currentNode;
  16053. const nodesByBlockId = new Map();
  16054. while ((currentNode = commentNodesIterator.nextNode())) {
  16055. const nghPattern = 'ngh=';
  16056. const content = currentNode?.textContent;
  16057. const nghIdx = content?.indexOf(nghPattern) ?? -1;
  16058. if (nghIdx > -1) {
  16059. const nghValue = content.substring(nghIdx + nghPattern.length).trim();
  16060. // Make sure the value has an expected format.
  16061. ngDevMode &&
  16062. assertEqual(nghValue.startsWith('d'), true, 'Invalid defer block id found in a comment node.');
  16063. nodesByBlockId.set(nghValue, currentNode);
  16064. }
  16065. }
  16066. return nodesByBlockId;
  16067. }
  16068. function acceptNode(node) {
  16069. return node.textContent?.trimStart().startsWith('ngh=')
  16070. ? NodeFilter.FILTER_ACCEPT
  16071. : NodeFilter.FILTER_REJECT;
  16072. }
  16073. let _isI18nHydrationSupportEnabled = false;
  16074. let _prepareI18nBlockForHydrationImpl = () => {
  16075. // noop unless `enablePrepareI18nBlockForHydrationImpl` is invoked.
  16076. };
  16077. function setIsI18nHydrationSupportEnabled(enabled) {
  16078. _isI18nHydrationSupportEnabled = enabled;
  16079. }
  16080. function isI18nHydrationSupportEnabled() {
  16081. return _isI18nHydrationSupportEnabled;
  16082. }
  16083. /**
  16084. * Prepares an i18n block and its children, located at the given
  16085. * view and instruction index, for hydration.
  16086. *
  16087. * @param lView lView with the i18n block
  16088. * @param index index of the i18n block in the lView
  16089. * @param parentTNode TNode of the parent of the i18n block
  16090. * @param subTemplateIndex sub-template index, or -1 for the main template
  16091. */
  16092. function prepareI18nBlockForHydration(lView, index, parentTNode, subTemplateIndex) {
  16093. _prepareI18nBlockForHydrationImpl(lView, index, parentTNode, subTemplateIndex);
  16094. }
  16095. function enablePrepareI18nBlockForHydrationImpl() {
  16096. _prepareI18nBlockForHydrationImpl = prepareI18nBlockForHydrationImpl;
  16097. }
  16098. function isI18nHydrationEnabled(injector) {
  16099. injector = injector ?? inject(Injector);
  16100. return injector.get(IS_I18N_HYDRATION_ENABLED, false);
  16101. }
  16102. /**
  16103. * Collects, if not already cached, all of the indices in the
  16104. * given TView which are children of an i18n block.
  16105. *
  16106. * Since i18n blocks don't introduce a parent TNode, this is necessary
  16107. * in order to determine which indices in a LView are translated.
  16108. */
  16109. function getOrComputeI18nChildren(tView, context) {
  16110. let i18nChildren = context.i18nChildren.get(tView);
  16111. if (i18nChildren === undefined) {
  16112. i18nChildren = collectI18nChildren(tView);
  16113. context.i18nChildren.set(tView, i18nChildren);
  16114. }
  16115. return i18nChildren;
  16116. }
  16117. function collectI18nChildren(tView) {
  16118. const children = new Set();
  16119. function collectI18nViews(node) {
  16120. children.add(node.index);
  16121. switch (node.kind) {
  16122. case 1 /* I18nNodeKind.ELEMENT */:
  16123. case 2 /* I18nNodeKind.PLACEHOLDER */: {
  16124. for (const childNode of node.children) {
  16125. collectI18nViews(childNode);
  16126. }
  16127. break;
  16128. }
  16129. case 3 /* I18nNodeKind.ICU */: {
  16130. for (const caseNodes of node.cases) {
  16131. for (const caseNode of caseNodes) {
  16132. collectI18nViews(caseNode);
  16133. }
  16134. }
  16135. break;
  16136. }
  16137. }
  16138. }
  16139. // Traverse through the AST of each i18n block in the LView,
  16140. // and collect every instruction index.
  16141. for (let i = HEADER_OFFSET; i < tView.bindingStartIndex; i++) {
  16142. const tI18n = tView.data[i];
  16143. if (!tI18n || !tI18n.ast) {
  16144. continue;
  16145. }
  16146. for (const node of tI18n.ast) {
  16147. collectI18nViews(node);
  16148. }
  16149. }
  16150. return children.size === 0 ? null : children;
  16151. }
  16152. /**
  16153. * Attempts to serialize i18n data for an i18n block, located at
  16154. * the given view and instruction index.
  16155. *
  16156. * @param lView lView with the i18n block
  16157. * @param index index of the i18n block in the lView
  16158. * @param context the hydration context
  16159. * @returns the i18n data, or null if there is no relevant data
  16160. */
  16161. function trySerializeI18nBlock(lView, index, context) {
  16162. if (!context.isI18nHydrationEnabled) {
  16163. return null;
  16164. }
  16165. const tView = lView[TVIEW];
  16166. const tI18n = tView.data[index];
  16167. if (!tI18n || !tI18n.ast) {
  16168. return null;
  16169. }
  16170. const parentTNode = tView.data[tI18n.parentTNodeIndex];
  16171. if (parentTNode && isI18nInSkipHydrationBlock(parentTNode)) {
  16172. return null;
  16173. }
  16174. const serializedI18nBlock = {
  16175. caseQueue: [],
  16176. disconnectedNodes: new Set(),
  16177. disjointNodes: new Set(),
  16178. };
  16179. serializeI18nBlock(lView, serializedI18nBlock, context, tI18n.ast);
  16180. return serializedI18nBlock.caseQueue.length === 0 &&
  16181. serializedI18nBlock.disconnectedNodes.size === 0 &&
  16182. serializedI18nBlock.disjointNodes.size === 0
  16183. ? null
  16184. : serializedI18nBlock;
  16185. }
  16186. function serializeI18nBlock(lView, serializedI18nBlock, context, nodes) {
  16187. let prevRNode = null;
  16188. for (const node of nodes) {
  16189. const nextRNode = serializeI18nNode(lView, serializedI18nBlock, context, node);
  16190. if (nextRNode) {
  16191. if (isDisjointNode(prevRNode, nextRNode)) {
  16192. serializedI18nBlock.disjointNodes.add(node.index - HEADER_OFFSET);
  16193. }
  16194. prevRNode = nextRNode;
  16195. }
  16196. }
  16197. return prevRNode;
  16198. }
  16199. /**
  16200. * Helper to determine whether the given nodes are "disjoint".
  16201. *
  16202. * The i18n hydration process walks through the DOM and i18n nodes
  16203. * at the same time. It expects the sibling DOM node of the previous
  16204. * i18n node to be the first node of the next i18n node.
  16205. *
  16206. * In cases of content projection, this won't always be the case. So
  16207. * when we detect that, we mark the node as "disjoint", ensuring that
  16208. * we will serialize the path to the node. This way, when we hydrate the
  16209. * i18n node, we will be able to find the correct place to start.
  16210. */
  16211. function isDisjointNode(prevNode, nextNode) {
  16212. return prevNode && prevNode.nextSibling !== nextNode;
  16213. }
  16214. /**
  16215. * Process the given i18n node for serialization.
  16216. * Returns the first RNode for the i18n node to begin hydration.
  16217. */
  16218. function serializeI18nNode(lView, serializedI18nBlock, context, node) {
  16219. const maybeRNode = unwrapRNode(lView[node.index]);
  16220. if (!maybeRNode || isDisconnectedRNode(maybeRNode)) {
  16221. serializedI18nBlock.disconnectedNodes.add(node.index - HEADER_OFFSET);
  16222. return null;
  16223. }
  16224. const rNode = maybeRNode;
  16225. switch (node.kind) {
  16226. case 0 /* I18nNodeKind.TEXT */: {
  16227. processTextNodeBeforeSerialization(context, rNode);
  16228. break;
  16229. }
  16230. case 1 /* I18nNodeKind.ELEMENT */:
  16231. case 2 /* I18nNodeKind.PLACEHOLDER */: {
  16232. serializeI18nBlock(lView, serializedI18nBlock, context, node.children);
  16233. break;
  16234. }
  16235. case 3 /* I18nNodeKind.ICU */: {
  16236. const currentCase = lView[node.currentCaseLViewIndex];
  16237. if (currentCase != null) {
  16238. // i18n uses a negative value to signal a change to a new case, so we
  16239. // need to invert it to get the proper value.
  16240. const caseIdx = currentCase < 0 ? ~currentCase : currentCase;
  16241. serializedI18nBlock.caseQueue.push(caseIdx);
  16242. serializeI18nBlock(lView, serializedI18nBlock, context, node.cases[caseIdx]);
  16243. }
  16244. break;
  16245. }
  16246. }
  16247. return getFirstNativeNodeForI18nNode(lView, node);
  16248. }
  16249. /**
  16250. * Helper function to get the first native node to begin hydrating
  16251. * the given i18n node.
  16252. */
  16253. function getFirstNativeNodeForI18nNode(lView, node) {
  16254. const tView = lView[TVIEW];
  16255. const maybeTNode = tView.data[node.index];
  16256. if (isTNodeShape(maybeTNode)) {
  16257. // If the node is backed by an actual TNode, we can simply delegate.
  16258. return getFirstNativeNode(lView, maybeTNode);
  16259. }
  16260. else if (node.kind === 3 /* I18nNodeKind.ICU */) {
  16261. // A nested ICU container won't have an actual TNode. In that case, we can use
  16262. // an iterator to find the first child.
  16263. const icuIterator = createIcuIterator(maybeTNode, lView);
  16264. let rNode = icuIterator();
  16265. // If the ICU container has no nodes, then we use the ICU anchor as the node.
  16266. return rNode ?? unwrapRNode(lView[node.index]);
  16267. }
  16268. else {
  16269. // Otherwise, the node is a text or trivial element in an ICU container,
  16270. // and we can just use the RNode directly.
  16271. return unwrapRNode(lView[node.index]) ?? null;
  16272. }
  16273. }
  16274. function setCurrentNode(state, node) {
  16275. state.currentNode = node;
  16276. }
  16277. /**
  16278. * Marks the current RNode as the hydration root for the given
  16279. * AST node.
  16280. */
  16281. function appendI18nNodeToCollection(context, state, astNode) {
  16282. const noOffsetIndex = astNode.index - HEADER_OFFSET;
  16283. const { disconnectedNodes } = context;
  16284. const currentNode = state.currentNode;
  16285. if (state.isConnected) {
  16286. context.i18nNodes.set(noOffsetIndex, currentNode);
  16287. // We expect the node to be connected, so ensure that it
  16288. // is not in the set, regardless of whether we found it,
  16289. // so that the downstream error handling can provide the
  16290. // proper context.
  16291. disconnectedNodes.delete(noOffsetIndex);
  16292. }
  16293. else {
  16294. disconnectedNodes.add(noOffsetIndex);
  16295. }
  16296. return currentNode;
  16297. }
  16298. /**
  16299. * Skip over some sibling nodes during hydration.
  16300. *
  16301. * Note: we use this instead of `siblingAfter` as it's expected that
  16302. * sometimes we might encounter null nodes. In those cases, we want to
  16303. * defer to downstream error handling to provide proper context.
  16304. */
  16305. function skipSiblingNodes(state, skip) {
  16306. let currentNode = state.currentNode;
  16307. for (let i = 0; i < skip; i++) {
  16308. if (!currentNode) {
  16309. break;
  16310. }
  16311. currentNode = currentNode?.nextSibling ?? null;
  16312. }
  16313. return currentNode;
  16314. }
  16315. /**
  16316. * Fork the given state into a new state for hydrating children.
  16317. */
  16318. function forkHydrationState(state, nextNode) {
  16319. return { currentNode: nextNode, isConnected: state.isConnected };
  16320. }
  16321. function prepareI18nBlockForHydrationImpl(lView, index, parentTNode, subTemplateIndex) {
  16322. const hydrationInfo = lView[HYDRATION];
  16323. if (!hydrationInfo) {
  16324. return;
  16325. }
  16326. if (!isI18nHydrationSupportEnabled() ||
  16327. (parentTNode &&
  16328. (isI18nInSkipHydrationBlock(parentTNode) ||
  16329. isDisconnectedNode$1(hydrationInfo, parentTNode.index - HEADER_OFFSET)))) {
  16330. return;
  16331. }
  16332. const tView = lView[TVIEW];
  16333. const tI18n = tView.data[index];
  16334. ngDevMode &&
  16335. assertDefined(tI18n, 'Expected i18n data to be present in a given TView slot during hydration');
  16336. function findHydrationRoot() {
  16337. if (isRootTemplateMessage(subTemplateIndex)) {
  16338. // This is the root of an i18n block. In this case, our hydration root will
  16339. // depend on where our parent TNode (i.e. the block with i18n applied) is
  16340. // in the DOM.
  16341. ngDevMode && assertDefined(parentTNode, 'Expected parent TNode while hydrating i18n root');
  16342. const rootNode = locateNextRNode(hydrationInfo, tView, lView, parentTNode);
  16343. // If this i18n block is attached to an <ng-container>, then we want to begin
  16344. // hydrating directly with the RNode. Otherwise, for a TNode with a physical DOM
  16345. // element, we want to recurse into the first child and begin there.
  16346. return parentTNode.type & 8 /* TNodeType.ElementContainer */ ? rootNode : rootNode.firstChild;
  16347. }
  16348. // This is a nested template in an i18n block. In this case, the entire view
  16349. // is translated, and part of a dehydrated view in a container. This means that
  16350. // we can simply begin hydration with the first dehydrated child.
  16351. return hydrationInfo?.firstChild;
  16352. }
  16353. const currentNode = findHydrationRoot();
  16354. ngDevMode && assertDefined(currentNode, 'Expected root i18n node during hydration');
  16355. const disconnectedNodes = initDisconnectedNodes(hydrationInfo) ?? new Set();
  16356. const i18nNodes = (hydrationInfo.i18nNodes ??= new Map());
  16357. const caseQueue = hydrationInfo.data[I18N_DATA]?.[index - HEADER_OFFSET] ?? [];
  16358. const dehydratedIcuData = (hydrationInfo.dehydratedIcuData ??= new Map());
  16359. collectI18nNodesFromDom({ hydrationInfo, lView, i18nNodes, disconnectedNodes, caseQueue, dehydratedIcuData }, { currentNode, isConnected: true }, tI18n.ast);
  16360. // Nodes from inactive ICU cases should be considered disconnected. We track them above
  16361. // because they aren't (and shouldn't be) serialized. Since we may mutate or create a
  16362. // new set, we need to be sure to write the expected value back to the DehydratedView.
  16363. hydrationInfo.disconnectedNodes = disconnectedNodes.size === 0 ? null : disconnectedNodes;
  16364. }
  16365. function collectI18nNodesFromDom(context, state, nodeOrNodes) {
  16366. if (Array.isArray(nodeOrNodes)) {
  16367. let nextState = state;
  16368. for (const node of nodeOrNodes) {
  16369. // Whenever a node doesn't directly follow the previous RNode, it
  16370. // is given a path. We need to resume collecting nodes from that location
  16371. // until and unless we find another disjoint node.
  16372. const targetNode = tryLocateRNodeByPath(context.hydrationInfo, context.lView, node.index - HEADER_OFFSET);
  16373. if (targetNode) {
  16374. nextState = forkHydrationState(state, targetNode);
  16375. }
  16376. collectI18nNodesFromDom(context, nextState, node);
  16377. }
  16378. }
  16379. else {
  16380. if (context.disconnectedNodes.has(nodeOrNodes.index - HEADER_OFFSET)) {
  16381. // i18n nodes can be considered disconnected if e.g. they were projected.
  16382. // In that case, we have to make sure to skip over them.
  16383. return;
  16384. }
  16385. switch (nodeOrNodes.kind) {
  16386. case 0 /* I18nNodeKind.TEXT */: {
  16387. // Claim a text node for hydration
  16388. const currentNode = appendI18nNodeToCollection(context, state, nodeOrNodes);
  16389. setCurrentNode(state, currentNode?.nextSibling ?? null);
  16390. break;
  16391. }
  16392. case 1 /* I18nNodeKind.ELEMENT */: {
  16393. // Recurse into the current element's children...
  16394. collectI18nNodesFromDom(context, forkHydrationState(state, state.currentNode?.firstChild ?? null), nodeOrNodes.children);
  16395. // And claim the parent element itself.
  16396. const currentNode = appendI18nNodeToCollection(context, state, nodeOrNodes);
  16397. setCurrentNode(state, currentNode?.nextSibling ?? null);
  16398. break;
  16399. }
  16400. case 2 /* I18nNodeKind.PLACEHOLDER */: {
  16401. const noOffsetIndex = nodeOrNodes.index - HEADER_OFFSET;
  16402. const { hydrationInfo } = context;
  16403. const containerSize = getNgContainerSize(hydrationInfo, noOffsetIndex);
  16404. switch (nodeOrNodes.type) {
  16405. case 0 /* I18nPlaceholderType.ELEMENT */: {
  16406. // Hydration expects to find the head of the element.
  16407. const currentNode = appendI18nNodeToCollection(context, state, nodeOrNodes);
  16408. // A TNode for the node may not yet if we're hydrating during the first pass,
  16409. // so use the serialized data to determine if this is an <ng-container>.
  16410. if (isSerializedElementContainer(hydrationInfo, noOffsetIndex)) {
  16411. // An <ng-container> doesn't have a physical DOM node, so we need to
  16412. // continue hydrating from siblings.
  16413. collectI18nNodesFromDom(context, state, nodeOrNodes.children);
  16414. // Skip over the anchor element. It will be claimed by the
  16415. // downstream container hydration.
  16416. const nextNode = skipSiblingNodes(state, 1);
  16417. setCurrentNode(state, nextNode);
  16418. }
  16419. else {
  16420. // Non-container elements represent an actual node in the DOM, so we
  16421. // need to continue hydration with the children, and claim the node.
  16422. collectI18nNodesFromDom(context, forkHydrationState(state, state.currentNode?.firstChild ?? null), nodeOrNodes.children);
  16423. setCurrentNode(state, currentNode?.nextSibling ?? null);
  16424. // Elements can also be the anchor of a view container, so there may
  16425. // be elements after this node that we need to skip.
  16426. if (containerSize !== null) {
  16427. // `+1` stands for an anchor node after all of the views in the container.
  16428. const nextNode = skipSiblingNodes(state, containerSize + 1);
  16429. setCurrentNode(state, nextNode);
  16430. }
  16431. }
  16432. break;
  16433. }
  16434. case 1 /* I18nPlaceholderType.SUBTEMPLATE */: {
  16435. ngDevMode &&
  16436. assertNotEqual(containerSize, null, 'Expected a container size while hydrating i18n subtemplate');
  16437. // Hydration expects to find the head of the template.
  16438. appendI18nNodeToCollection(context, state, nodeOrNodes);
  16439. // Skip over all of the template children, as well as the anchor
  16440. // node, since the template itself will handle them instead.
  16441. const nextNode = skipSiblingNodes(state, containerSize + 1);
  16442. setCurrentNode(state, nextNode);
  16443. break;
  16444. }
  16445. }
  16446. break;
  16447. }
  16448. case 3 /* I18nNodeKind.ICU */: {
  16449. // If the current node is connected, we need to pop the next case from the
  16450. // queue, so that the active case is also considered connected.
  16451. const selectedCase = state.isConnected ? context.caseQueue.shift() : null;
  16452. const childState = { currentNode: null, isConnected: false };
  16453. // We traverse through each case, even if it's not active,
  16454. // so that we correctly populate disconnected nodes.
  16455. for (let i = 0; i < nodeOrNodes.cases.length; i++) {
  16456. collectI18nNodesFromDom(context, i === selectedCase ? state : childState, nodeOrNodes.cases[i]);
  16457. }
  16458. if (selectedCase !== null) {
  16459. // ICUs represent a branching state, and the selected case could be different
  16460. // than what it was on the server. In that case, we need to be able to clean
  16461. // up the nodes from the original case. To do that, we store the selected case.
  16462. context.dehydratedIcuData.set(nodeOrNodes.index, { case: selectedCase, node: nodeOrNodes });
  16463. }
  16464. // Hydration expects to find the ICU anchor element.
  16465. const currentNode = appendI18nNodeToCollection(context, state, nodeOrNodes);
  16466. setCurrentNode(state, currentNode?.nextSibling ?? null);
  16467. break;
  16468. }
  16469. }
  16470. }
  16471. }
  16472. let _claimDehydratedIcuCaseImpl = () => {
  16473. // noop unless `enableClaimDehydratedIcuCaseImpl` is invoked
  16474. };
  16475. /**
  16476. * Mark the case for the ICU node at the given index in the view as claimed,
  16477. * allowing its nodes to be hydrated and not cleaned up.
  16478. */
  16479. function claimDehydratedIcuCase(lView, icuIndex, caseIndex) {
  16480. _claimDehydratedIcuCaseImpl(lView, icuIndex, caseIndex);
  16481. }
  16482. function enableClaimDehydratedIcuCaseImpl() {
  16483. _claimDehydratedIcuCaseImpl = claimDehydratedIcuCaseImpl;
  16484. }
  16485. function claimDehydratedIcuCaseImpl(lView, icuIndex, caseIndex) {
  16486. const dehydratedIcuDataMap = lView[HYDRATION]?.dehydratedIcuData;
  16487. if (dehydratedIcuDataMap) {
  16488. const dehydratedIcuData = dehydratedIcuDataMap.get(icuIndex);
  16489. if (dehydratedIcuData?.case === caseIndex) {
  16490. // If the case we're attempting to claim matches the dehydrated one,
  16491. // we remove it from the map to mark it as "claimed."
  16492. dehydratedIcuDataMap.delete(icuIndex);
  16493. }
  16494. }
  16495. }
  16496. /**
  16497. * Clean up all i18n hydration data associated with the given view.
  16498. */
  16499. function cleanupI18nHydrationData(lView) {
  16500. const hydrationInfo = lView[HYDRATION];
  16501. if (hydrationInfo) {
  16502. const { i18nNodes, dehydratedIcuData: dehydratedIcuDataMap } = hydrationInfo;
  16503. if (i18nNodes && dehydratedIcuDataMap) {
  16504. const renderer = lView[RENDERER];
  16505. for (const dehydratedIcuData of dehydratedIcuDataMap.values()) {
  16506. cleanupDehydratedIcuData(renderer, i18nNodes, dehydratedIcuData);
  16507. }
  16508. }
  16509. hydrationInfo.i18nNodes = undefined;
  16510. hydrationInfo.dehydratedIcuData = undefined;
  16511. }
  16512. }
  16513. function cleanupDehydratedIcuData(renderer, i18nNodes, dehydratedIcuData) {
  16514. for (const node of dehydratedIcuData.node.cases[dehydratedIcuData.case]) {
  16515. const rNode = i18nNodes.get(node.index - HEADER_OFFSET);
  16516. if (rNode) {
  16517. nativeRemoveNode(renderer, rNode, false);
  16518. }
  16519. }
  16520. }
  16521. /**
  16522. * Removes all dehydrated views from a given LContainer:
  16523. * both in internal data structure, as well as removing
  16524. * corresponding DOM nodes that belong to that dehydrated view.
  16525. */
  16526. function removeDehydratedViews(lContainer) {
  16527. const views = lContainer[DEHYDRATED_VIEWS] ?? [];
  16528. const parentLView = lContainer[PARENT];
  16529. const renderer = parentLView[RENDERER];
  16530. const retainedViews = [];
  16531. for (const view of views) {
  16532. // Do not clean up contents of `@defer` blocks.
  16533. // The cleanup for this content would happen once a given block
  16534. // is triggered and hydrated.
  16535. if (view.data[DEFER_BLOCK_ID] !== undefined) {
  16536. retainedViews.push(view);
  16537. }
  16538. else {
  16539. removeDehydratedView(view, renderer);
  16540. ngDevMode && ngDevMode.dehydratedViewsRemoved++;
  16541. }
  16542. }
  16543. // Reset the value to an array to indicate that no
  16544. // further processing of dehydrated views is needed for
  16545. // this view container (i.e. do not trigger the lookup process
  16546. // once again in case a `ViewContainerRef` is created later).
  16547. lContainer[DEHYDRATED_VIEWS] = retainedViews;
  16548. }
  16549. function removeDehydratedViewList(deferBlock) {
  16550. const { lContainer } = deferBlock;
  16551. const dehydratedViews = lContainer[DEHYDRATED_VIEWS];
  16552. if (dehydratedViews === null)
  16553. return;
  16554. const parentLView = lContainer[PARENT];
  16555. const renderer = parentLView[RENDERER];
  16556. for (const view of dehydratedViews) {
  16557. removeDehydratedView(view, renderer);
  16558. ngDevMode && ngDevMode.dehydratedViewsRemoved++;
  16559. }
  16560. }
  16561. /**
  16562. * Helper function to remove all nodes from a dehydrated view.
  16563. */
  16564. function removeDehydratedView(dehydratedView, renderer) {
  16565. let nodesRemoved = 0;
  16566. let currentRNode = dehydratedView.firstChild;
  16567. if (currentRNode) {
  16568. const numNodes = dehydratedView.data[NUM_ROOT_NODES];
  16569. while (nodesRemoved < numNodes) {
  16570. ngDevMode && validateSiblingNodeExists(currentRNode);
  16571. const nextSibling = currentRNode.nextSibling;
  16572. nativeRemoveNode(renderer, currentRNode, false);
  16573. currentRNode = nextSibling;
  16574. nodesRemoved++;
  16575. }
  16576. }
  16577. }
  16578. /**
  16579. * Walks over all views within this LContainer invokes dehydrated views
  16580. * cleanup function for each one.
  16581. */
  16582. function cleanupLContainer(lContainer) {
  16583. removeDehydratedViews(lContainer);
  16584. // The host could be an LView if this container is on a component node.
  16585. // In this case, descend into host LView for further cleanup. See also
  16586. // LContainer[HOST] docs for additional information.
  16587. const hostLView = lContainer[HOST];
  16588. if (isLView(hostLView)) {
  16589. cleanupLView(hostLView);
  16590. }
  16591. for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
  16592. cleanupLView(lContainer[i]);
  16593. }
  16594. }
  16595. /**
  16596. * Walks over `LContainer`s and components registered within
  16597. * this LView and invokes dehydrated views cleanup function for each one.
  16598. */
  16599. function cleanupLView(lView) {
  16600. cleanupI18nHydrationData(lView);
  16601. const tView = lView[TVIEW];
  16602. for (let i = HEADER_OFFSET; i < tView.bindingStartIndex; i++) {
  16603. if (isLContainer(lView[i])) {
  16604. const lContainer = lView[i];
  16605. cleanupLContainer(lContainer);
  16606. }
  16607. else if (isLView(lView[i])) {
  16608. // This is a component, enter the `cleanupLView` recursively.
  16609. cleanupLView(lView[i]);
  16610. }
  16611. }
  16612. }
  16613. /**
  16614. * Walks over all views registered within the ApplicationRef and removes
  16615. * all dehydrated views from all `LContainer`s along the way.
  16616. */
  16617. function cleanupDehydratedViews(appRef) {
  16618. const viewRefs = appRef._views;
  16619. for (const viewRef of viewRefs) {
  16620. const lNode = getLNodeForHydration(viewRef);
  16621. // An `lView` might be `null` if a `ViewRef` represents
  16622. // an embedded view (not a component view).
  16623. if (lNode !== null && lNode[HOST] !== null) {
  16624. if (isLView(lNode)) {
  16625. cleanupLView(lNode);
  16626. }
  16627. else {
  16628. // Cleanup in all views within this view container
  16629. cleanupLContainer(lNode);
  16630. }
  16631. ngDevMode && ngDevMode.dehydratedViewsCleanupRuns++;
  16632. }
  16633. }
  16634. }
  16635. /**
  16636. * post hydration cleanup handling for defer blocks that were incrementally
  16637. * hydrated. This removes all the jsaction attributes, timers, observers,
  16638. * dehydrated views and containers
  16639. */
  16640. function cleanupHydratedDeferBlocks(deferBlock, hydratedBlocks, registry, appRef) {
  16641. if (deferBlock !== null) {
  16642. registry.cleanup(hydratedBlocks);
  16643. cleanupLContainer(deferBlock.lContainer);
  16644. cleanupDehydratedViews(appRef);
  16645. }
  16646. }
  16647. /**
  16648. * Given a current DOM node and a serialized information about the views
  16649. * in a container, walks over the DOM structure, collecting the list of
  16650. * dehydrated views.
  16651. */
  16652. function locateDehydratedViewsInContainer(currentRNode, serializedViews) {
  16653. const dehydratedViews = [];
  16654. for (const serializedView of serializedViews) {
  16655. // Repeats a view multiple times as needed, based on the serialized information
  16656. // (for example, for *ngFor-produced views).
  16657. for (let i = 0; i < (serializedView[MULTIPLIER] ?? 1); i++) {
  16658. const view = {
  16659. data: serializedView,
  16660. firstChild: null,
  16661. };
  16662. if (serializedView[NUM_ROOT_NODES] > 0) {
  16663. // Keep reference to the first node in this view,
  16664. // so it can be accessed while invoking template instructions.
  16665. view.firstChild = currentRNode;
  16666. // Move over to the next node after this view, which can
  16667. // either be a first node of the next view or an anchor comment
  16668. // node after the last view in a container.
  16669. currentRNode = siblingAfter(serializedView[NUM_ROOT_NODES], currentRNode);
  16670. }
  16671. dehydratedViews.push(view);
  16672. }
  16673. }
  16674. return [currentRNode, dehydratedViews];
  16675. }
  16676. /**
  16677. * Reference to a function that searches for a matching dehydrated views
  16678. * stored on a given lContainer.
  16679. * Returns `null` by default, when hydration is not enabled.
  16680. */
  16681. let _findMatchingDehydratedViewImpl = () => null;
  16682. /**
  16683. * Retrieves the next dehydrated view from the LContainer and verifies that
  16684. * it matches a given template id (from the TView that was used to create this
  16685. * instance of a view). If the id doesn't match, that means that we are in an
  16686. * unexpected state and can not complete the reconciliation process. Thus,
  16687. * all dehydrated views from this LContainer are removed (including corresponding
  16688. * DOM nodes) and the rendering is performed as if there were no dehydrated views
  16689. * in this container.
  16690. */
  16691. function findMatchingDehydratedViewImpl(lContainer, template) {
  16692. const views = lContainer[DEHYDRATED_VIEWS];
  16693. if (!template || views === null || views.length === 0) {
  16694. return null;
  16695. }
  16696. const view = views[0];
  16697. // Verify whether the first dehydrated view in the container matches
  16698. // the template id passed to this function (that originated from a TView
  16699. // that was used to create an instance of an embedded or component views.
  16700. if (view.data[TEMPLATE_ID] === template) {
  16701. // If the template id matches - extract the first view and return it.
  16702. return views.shift();
  16703. }
  16704. else {
  16705. // Otherwise, we are at the state when reconciliation can not be completed,
  16706. // thus we remove all dehydrated views within this container (remove them
  16707. // from internal data structures as well as delete associated elements from
  16708. // the DOM tree).
  16709. removeDehydratedViews(lContainer);
  16710. return null;
  16711. }
  16712. }
  16713. function enableFindMatchingDehydratedViewImpl() {
  16714. _findMatchingDehydratedViewImpl = findMatchingDehydratedViewImpl;
  16715. }
  16716. function findMatchingDehydratedView(lContainer, template) {
  16717. return _findMatchingDehydratedViewImpl(lContainer, template);
  16718. }
  16719. /**
  16720. * Represents a component created by a `ComponentFactory`.
  16721. * Provides access to the component instance and related objects,
  16722. * and provides the means of destroying the instance.
  16723. *
  16724. * @publicApi
  16725. */
  16726. let ComponentRef$1 = class ComponentRef {
  16727. };
  16728. /**
  16729. * Base class for a factory that can create a component dynamically.
  16730. * Instantiate a factory for a given type of component with `resolveComponentFactory()`.
  16731. * Use the resulting `ComponentFactory.create()` method to create a component of that type.
  16732. *
  16733. * @publicApi
  16734. *
  16735. * @deprecated Angular no longer requires Component factories. Please use other APIs where
  16736. * Component class can be used directly.
  16737. */
  16738. let ComponentFactory$1 = class ComponentFactory {
  16739. };
  16740. class _NullComponentFactoryResolver {
  16741. resolveComponentFactory(component) {
  16742. throw Error(`No component factory found for ${stringify(component)}.`);
  16743. }
  16744. }
  16745. /**
  16746. * A simple registry that maps `Components` to generated `ComponentFactory` classes
  16747. * that can be used to create instances of components.
  16748. * Use to obtain the factory for a given component type,
  16749. * then use the factory's `create()` method to create a component of that type.
  16750. *
  16751. * Note: since v13, dynamic component creation via
  16752. * [`ViewContainerRef.createComponent`](api/core/ViewContainerRef#createComponent)
  16753. * does **not** require resolving component factory: component class can be used directly.
  16754. *
  16755. * @publicApi
  16756. *
  16757. * @deprecated Angular no longer requires Component factories. Please use other APIs where
  16758. * Component class can be used directly.
  16759. */
  16760. let ComponentFactoryResolver$1 = class ComponentFactoryResolver {
  16761. static NULL = new _NullComponentFactoryResolver();
  16762. };
  16763. /**
  16764. * Creates and initializes a custom renderer that implements the `Renderer2` base class.
  16765. *
  16766. * @publicApi
  16767. */
  16768. class RendererFactory2 {
  16769. }
  16770. /**
  16771. * Extend this base class to implement custom rendering. By default, Angular
  16772. * renders a template into DOM. You can use custom rendering to intercept
  16773. * rendering calls, or to render to something other than DOM.
  16774. *
  16775. * <div class="docs-alert docs-alert-important">
  16776. * <p>
  16777. * Please be aware that usage of `Renderer2`, in context of accessing DOM elements, provides no
  16778. * extra security which makes it equivalent to
  16779. * {@link /best-practices/security#direct-use-of-the-dom-apis-and-explicit-sanitization-calls Security vulnerabilities}.
  16780. * </p>
  16781. * </div>
  16782. *
  16783. * Create your custom renderer using `RendererFactory2`.
  16784. *
  16785. * Use a custom renderer to bypass Angular's templating and
  16786. * make custom UI changes that can't be expressed declaratively.
  16787. * For example if you need to set a property or an attribute whose name is
  16788. * not statically known, use the `setProperty()` or
  16789. * `setAttribute()` method.
  16790. *
  16791. * @publicApi
  16792. */
  16793. class Renderer2 {
  16794. /**
  16795. * If null or undefined, the view engine won't call it.
  16796. * This is used as a performance optimization for production mode.
  16797. */
  16798. destroyNode = null;
  16799. /**
  16800. * @internal
  16801. * @nocollapse
  16802. */
  16803. static __NG_ELEMENT_ID__ = () => injectRenderer2();
  16804. }
  16805. /** Injects a Renderer2 for the current component. */
  16806. function injectRenderer2() {
  16807. // We need the Renderer to be based on the component that it's being injected into, however since
  16808. // DI happens before we've entered its view, `getLView` will return the parent view instead.
  16809. const lView = getLView();
  16810. const tNode = getCurrentTNode();
  16811. const nodeAtIndex = getComponentLViewByIndex(tNode.index, lView);
  16812. return (isLView(nodeAtIndex) ? nodeAtIndex : lView)[RENDERER];
  16813. }
  16814. /**
  16815. * Sanitizer is used by the views to sanitize potentially dangerous values.
  16816. *
  16817. * @publicApi
  16818. */
  16819. class Sanitizer {
  16820. /** @nocollapse */
  16821. static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
  16822. token: Sanitizer,
  16823. providedIn: 'root',
  16824. factory: () => null,
  16825. });
  16826. }
  16827. function isModuleWithProviders(value) {
  16828. return value.ngModule !== undefined;
  16829. }
  16830. function isNgModule(value) {
  16831. return !!getNgModuleDef(value);
  16832. }
  16833. function isPipe(value) {
  16834. return !!getPipeDef$1(value);
  16835. }
  16836. function isDirective(value) {
  16837. return !!getDirectiveDef(value);
  16838. }
  16839. function isComponent(value) {
  16840. return !!getComponentDef(value);
  16841. }
  16842. function getDependencyTypeForError(type) {
  16843. if (getComponentDef(type))
  16844. return 'component';
  16845. if (getDirectiveDef(type))
  16846. return 'directive';
  16847. if (getPipeDef$1(type))
  16848. return 'pipe';
  16849. return 'type';
  16850. }
  16851. function verifyStandaloneImport(depType, importingType) {
  16852. if (isForwardRef(depType)) {
  16853. depType = resolveForwardRef(depType);
  16854. if (!depType) {
  16855. throw new Error(`Expected forwardRef function, imported from "${stringifyForError(importingType)}", to return a standalone entity or NgModule but got "${stringifyForError(depType) || depType}".`);
  16856. }
  16857. }
  16858. if (getNgModuleDef(depType) == null) {
  16859. const def = getComponentDef(depType) || getDirectiveDef(depType) || getPipeDef$1(depType);
  16860. if (def != null) {
  16861. // if a component, directive or pipe is imported make sure that it is standalone
  16862. if (!def.standalone) {
  16863. throw new Error(`The "${stringifyForError(depType)}" ${getDependencyTypeForError(depType)}, imported from "${stringifyForError(importingType)}", is not standalone. Did you forget to add the standalone: true flag?`);
  16864. }
  16865. }
  16866. else {
  16867. // it can be either a module with provider or an unknown (not annotated) type
  16868. if (isModuleWithProviders(depType)) {
  16869. throw new Error(`A module with providers was imported from "${stringifyForError(importingType)}". Modules with providers are not supported in standalone components imports.`);
  16870. }
  16871. else {
  16872. 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?`);
  16873. }
  16874. }
  16875. }
  16876. }
  16877. /**
  16878. * Indicates whether to use the runtime dependency tracker for scope calculation in JIT compilation.
  16879. * The value "false" means the old code path based on patching scope info into the types will be
  16880. * used.
  16881. *
  16882. * @deprecated For migration purposes only, to be removed soon.
  16883. */
  16884. const USE_RUNTIME_DEPS_TRACKER_FOR_JIT = true;
  16885. /**
  16886. * An implementation of DepsTrackerApi which will be used for JIT and local compilation.
  16887. */
  16888. class DepsTracker {
  16889. ownerNgModule = new Map();
  16890. ngModulesWithSomeUnresolvedDecls = new Set();
  16891. ngModulesScopeCache = new Map();
  16892. standaloneComponentsScopeCache = new Map();
  16893. /**
  16894. * Attempts to resolve ng module's forward ref declarations as much as possible and add them to
  16895. * the `ownerNgModule` map. This method normally should be called after the initial parsing when
  16896. * all the forward refs are resolved (e.g., when trying to render a component)
  16897. */
  16898. resolveNgModulesDecls() {
  16899. if (this.ngModulesWithSomeUnresolvedDecls.size === 0) {
  16900. return;
  16901. }
  16902. for (const moduleType of this.ngModulesWithSomeUnresolvedDecls) {
  16903. const def = getNgModuleDef(moduleType);
  16904. if (def?.declarations) {
  16905. for (const decl of maybeUnwrapFn(def.declarations)) {
  16906. if (isComponent(decl)) {
  16907. this.ownerNgModule.set(decl, moduleType);
  16908. }
  16909. }
  16910. }
  16911. }
  16912. this.ngModulesWithSomeUnresolvedDecls.clear();
  16913. }
  16914. /** @override */
  16915. getComponentDependencies(type, rawImports) {
  16916. this.resolveNgModulesDecls();
  16917. const def = getComponentDef(type);
  16918. if (def === null) {
  16919. throw new Error(`Attempting to get component dependencies for a type that is not a component: ${type}`);
  16920. }
  16921. if (def.standalone) {
  16922. const scope = this.getStandaloneComponentScope(type, rawImports);
  16923. if (scope.compilation.isPoisoned) {
  16924. return { dependencies: [] };
  16925. }
  16926. return {
  16927. dependencies: [
  16928. ...scope.compilation.directives,
  16929. ...scope.compilation.pipes,
  16930. ...scope.compilation.ngModules,
  16931. ],
  16932. };
  16933. }
  16934. else {
  16935. if (!this.ownerNgModule.has(type)) {
  16936. // This component is orphan! No need to handle the error since the component rendering
  16937. // pipeline (e.g., view_container_ref) will check for this error based on configs.
  16938. return { dependencies: [] };
  16939. }
  16940. const scope = this.getNgModuleScope(this.ownerNgModule.get(type));
  16941. if (scope.compilation.isPoisoned) {
  16942. return { dependencies: [] };
  16943. }
  16944. return {
  16945. dependencies: [...scope.compilation.directives, ...scope.compilation.pipes],
  16946. };
  16947. }
  16948. }
  16949. /**
  16950. * @override
  16951. * This implementation does not make use of param scopeInfo since it assumes the scope info is
  16952. * already added to the type itself through methods like {@link ɵɵsetNgModuleScope}
  16953. */
  16954. registerNgModule(type, scopeInfo) {
  16955. if (!isNgModule(type)) {
  16956. throw new Error(`Attempting to register a Type which is not NgModule as NgModule: ${type}`);
  16957. }
  16958. // Lazily process the NgModules later when needed.
  16959. this.ngModulesWithSomeUnresolvedDecls.add(type);
  16960. }
  16961. /** @override */
  16962. clearScopeCacheFor(type) {
  16963. this.ngModulesScopeCache.delete(type);
  16964. this.standaloneComponentsScopeCache.delete(type);
  16965. }
  16966. /** @override */
  16967. getNgModuleScope(type) {
  16968. if (this.ngModulesScopeCache.has(type)) {
  16969. return this.ngModulesScopeCache.get(type);
  16970. }
  16971. const scope = this.computeNgModuleScope(type);
  16972. this.ngModulesScopeCache.set(type, scope);
  16973. return scope;
  16974. }
  16975. /** Compute NgModule scope afresh. */
  16976. computeNgModuleScope(type) {
  16977. const def = getNgModuleDef(type, true);
  16978. const scope = {
  16979. exported: { directives: new Set(), pipes: new Set() },
  16980. compilation: { directives: new Set(), pipes: new Set() },
  16981. };
  16982. // Analyzing imports
  16983. for (const imported of maybeUnwrapFn(def.imports)) {
  16984. if (isNgModule(imported)) {
  16985. const importedScope = this.getNgModuleScope(imported);
  16986. // When this module imports another, the imported module's exported directives and pipes
  16987. // are added to the compilation scope of this module.
  16988. addSet(importedScope.exported.directives, scope.compilation.directives);
  16989. addSet(importedScope.exported.pipes, scope.compilation.pipes);
  16990. }
  16991. else if (isStandalone(imported)) {
  16992. if (isDirective(imported) || isComponent(imported)) {
  16993. scope.compilation.directives.add(imported);
  16994. }
  16995. else if (isPipe(imported)) {
  16996. scope.compilation.pipes.add(imported);
  16997. }
  16998. else {
  16999. // The standalone thing is neither a component nor a directive nor a pipe ... (what?)
  17000. throw new RuntimeError(980 /* RuntimeErrorCode.RUNTIME_DEPS_INVALID_IMPORTED_TYPE */, 'The standalone imported type is neither a component nor a directive nor a pipe');
  17001. }
  17002. }
  17003. else {
  17004. // The import is neither a module nor a module-with-providers nor a standalone thing. This
  17005. // is going to be an error. So we short circuit.
  17006. scope.compilation.isPoisoned = true;
  17007. break;
  17008. }
  17009. }
  17010. // Analyzing declarations
  17011. if (!scope.compilation.isPoisoned) {
  17012. for (const decl of maybeUnwrapFn(def.declarations)) {
  17013. // Cannot declare another NgModule or a standalone thing
  17014. if (isNgModule(decl) || isStandalone(decl)) {
  17015. scope.compilation.isPoisoned = true;
  17016. break;
  17017. }
  17018. if (isPipe(decl)) {
  17019. scope.compilation.pipes.add(decl);
  17020. }
  17021. else {
  17022. // decl is either a directive or a component. The component may not yet have the ɵcmp due
  17023. // to async compilation.
  17024. scope.compilation.directives.add(decl);
  17025. }
  17026. }
  17027. }
  17028. // Analyzing exports
  17029. for (const exported of maybeUnwrapFn(def.exports)) {
  17030. if (isNgModule(exported)) {
  17031. // When this module exports another, the exported module's exported directives and pipes
  17032. // are added to both the compilation and exported scopes of this module.
  17033. const exportedScope = this.getNgModuleScope(exported);
  17034. // Based on the current logic there is no way to have poisoned exported scope. So no need to
  17035. // check for it.
  17036. addSet(exportedScope.exported.directives, scope.exported.directives);
  17037. addSet(exportedScope.exported.pipes, scope.exported.pipes);
  17038. // Some test toolings which run in JIT mode depend on this behavior that the exported scope
  17039. // should also be present in the compilation scope, even though AoT does not support this
  17040. // and it is also in odds with NgModule metadata definitions. Without this some tests in
  17041. // Google will fail.
  17042. addSet(exportedScope.exported.directives, scope.compilation.directives);
  17043. addSet(exportedScope.exported.pipes, scope.compilation.pipes);
  17044. }
  17045. else if (isPipe(exported)) {
  17046. scope.exported.pipes.add(exported);
  17047. }
  17048. else {
  17049. scope.exported.directives.add(exported);
  17050. }
  17051. }
  17052. return scope;
  17053. }
  17054. /** @override */
  17055. getStandaloneComponentScope(type, rawImports) {
  17056. if (this.standaloneComponentsScopeCache.has(type)) {
  17057. return this.standaloneComponentsScopeCache.get(type);
  17058. }
  17059. const ans = this.computeStandaloneComponentScope(type, rawImports);
  17060. this.standaloneComponentsScopeCache.set(type, ans);
  17061. return ans;
  17062. }
  17063. computeStandaloneComponentScope(type, rawImports) {
  17064. const ans = {
  17065. compilation: {
  17066. // Standalone components are always able to self-reference.
  17067. directives: new Set([type]),
  17068. pipes: new Set(),
  17069. ngModules: new Set(),
  17070. },
  17071. };
  17072. for (const rawImport of flatten(rawImports ?? [])) {
  17073. const imported = resolveForwardRef(rawImport);
  17074. try {
  17075. verifyStandaloneImport(imported, type);
  17076. }
  17077. catch (e) {
  17078. // Short-circuit if an import is not valid
  17079. ans.compilation.isPoisoned = true;
  17080. return ans;
  17081. }
  17082. if (isNgModule(imported)) {
  17083. ans.compilation.ngModules.add(imported);
  17084. const importedScope = this.getNgModuleScope(imported);
  17085. // Short-circuit if an imported NgModule has corrupted exported scope.
  17086. if (importedScope.exported.isPoisoned) {
  17087. ans.compilation.isPoisoned = true;
  17088. return ans;
  17089. }
  17090. addSet(importedScope.exported.directives, ans.compilation.directives);
  17091. addSet(importedScope.exported.pipes, ans.compilation.pipes);
  17092. }
  17093. else if (isPipe(imported)) {
  17094. ans.compilation.pipes.add(imported);
  17095. }
  17096. else if (isDirective(imported) || isComponent(imported)) {
  17097. ans.compilation.directives.add(imported);
  17098. }
  17099. else {
  17100. // The imported thing is not module/pipe/directive/component, so we error and short-circuit
  17101. // here
  17102. ans.compilation.isPoisoned = true;
  17103. return ans;
  17104. }
  17105. }
  17106. return ans;
  17107. }
  17108. /** @override */
  17109. isOrphanComponent(cmp) {
  17110. const def = getComponentDef(cmp);
  17111. if (!def || def.standalone) {
  17112. return false;
  17113. }
  17114. this.resolveNgModulesDecls();
  17115. return !this.ownerNgModule.has(cmp);
  17116. }
  17117. }
  17118. function addSet(sourceSet, targetSet) {
  17119. for (const m of sourceSet) {
  17120. targetSet.add(m);
  17121. }
  17122. }
  17123. /** The deps tracker to be used in the current Angular app in dev mode. */
  17124. const depsTracker = new DepsTracker();
  17125. // This default value is when checking the hierarchy for a token.
  17126. //
  17127. // It means both:
  17128. // - the token is not provided by the current injector,
  17129. // - only the element injectors should be checked (ie do not check module injectors
  17130. //
  17131. // mod1
  17132. // /
  17133. // el1 mod2
  17134. // \ /
  17135. // el2
  17136. //
  17137. // When requesting el2.injector.get(token), we should check in the following order and return the
  17138. // first found value:
  17139. // - el2.injector.get(token, default)
  17140. // - el1.injector.get(token, NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR) -> do not check the module
  17141. // - mod2.injector.get(token, default)
  17142. const NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR = {};
  17143. /**
  17144. * Injector that looks up a value using a specific injector, before falling back to the module
  17145. * injector. Used primarily when creating components or embedded views dynamically.
  17146. */
  17147. class ChainedInjector {
  17148. injector;
  17149. parentInjector;
  17150. constructor(injector, parentInjector) {
  17151. this.injector = injector;
  17152. this.parentInjector = parentInjector;
  17153. }
  17154. get(token, notFoundValue, flags) {
  17155. flags = convertToBitFlags(flags);
  17156. const value = this.injector.get(token, NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR, flags);
  17157. if (value !== NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR ||
  17158. notFoundValue === NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR) {
  17159. // Return the value from the root element injector when
  17160. // - it provides it
  17161. // (value !== NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR)
  17162. // - the module injector should not be checked
  17163. // (notFoundValue === NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR)
  17164. return value;
  17165. }
  17166. return this.parentInjector.get(token, notFoundValue, flags);
  17167. }
  17168. }
  17169. /**
  17170. * Compute the static styling (class/style) from `TAttributes`.
  17171. *
  17172. * This function should be called during `firstCreatePass` only.
  17173. *
  17174. * @param tNode The `TNode` into which the styling information should be loaded.
  17175. * @param attrs `TAttributes` containing the styling information.
  17176. * @param writeToHost Where should the resulting static styles be written?
  17177. * - `false` Write to `TNode.stylesWithoutHost` / `TNode.classesWithoutHost`
  17178. * - `true` Write to `TNode.styles` / `TNode.classes`
  17179. */
  17180. function computeStaticStyling(tNode, attrs, writeToHost) {
  17181. ngDevMode &&
  17182. assertFirstCreatePass(getTView(), 'Expecting to be called in first template pass only');
  17183. let styles = writeToHost ? tNode.styles : null;
  17184. let classes = writeToHost ? tNode.classes : null;
  17185. let mode = 0;
  17186. if (attrs !== null) {
  17187. for (let i = 0; i < attrs.length; i++) {
  17188. const value = attrs[i];
  17189. if (typeof value === 'number') {
  17190. mode = value;
  17191. }
  17192. else if (mode == 1 /* AttributeMarker.Classes */) {
  17193. classes = concatStringsWithSpace(classes, value);
  17194. }
  17195. else if (mode == 2 /* AttributeMarker.Styles */) {
  17196. const style = value;
  17197. const styleValue = attrs[++i];
  17198. styles = concatStringsWithSpace(styles, style + ': ' + styleValue + ';');
  17199. }
  17200. }
  17201. }
  17202. writeToHost ? (tNode.styles = styles) : (tNode.stylesWithoutHost = styles);
  17203. writeToHost ? (tNode.classes = classes) : (tNode.classesWithoutHost = classes);
  17204. }
  17205. function ɵɵdirectiveInject(token, flags = InjectFlags.Default) {
  17206. const lView = getLView();
  17207. // Fall back to inject() if view hasn't been created. This situation can happen in tests
  17208. // if inject utilities are used before bootstrapping.
  17209. if (lView === null) {
  17210. // Verify that we will not get into infinite loop.
  17211. ngDevMode && assertInjectImplementationNotEqual(ɵɵdirectiveInject);
  17212. return ɵɵinject(token, flags);
  17213. }
  17214. const tNode = getCurrentTNode();
  17215. const value = getOrCreateInjectable(tNode, lView, resolveForwardRef(token), flags);
  17216. ngDevMode && emitInjectEvent(token, value, flags);
  17217. return value;
  17218. }
  17219. /**
  17220. * Throws an error indicating that a factory function could not be generated by the compiler for a
  17221. * particular class.
  17222. *
  17223. * This instruction allows the actual error message to be optimized away when ngDevMode is turned
  17224. * off, saving bytes of generated code while still providing a good experience in dev mode.
  17225. *
  17226. * The name of the class is not mentioned here, but will be in the generated factory function name
  17227. * and thus in the stack trace.
  17228. *
  17229. * @codeGenApi
  17230. */
  17231. function ɵɵinvalidFactory() {
  17232. const msg = ngDevMode
  17233. ? `This constructor was not compatible with Dependency Injection.`
  17234. : 'invalid';
  17235. throw new Error(msg);
  17236. }
  17237. /**
  17238. * Resolve the matched directives on a node.
  17239. */
  17240. function resolveDirectives(tView, lView, tNode, localRefs, directiveMatcher) {
  17241. // Please make sure to have explicit type for `exportsMap`. Inferred type triggers bug in tsickle.
  17242. ngDevMode && assertFirstCreatePass(tView);
  17243. const exportsMap = localRefs === null ? null : { '': -1 };
  17244. const matchedDirectiveDefs = directiveMatcher(tView, tNode);
  17245. if (matchedDirectiveDefs !== null) {
  17246. let directiveDefs;
  17247. let hostDirectiveDefs = null;
  17248. let hostDirectiveRanges = null;
  17249. const hostDirectiveResolution = resolveHostDirectives(matchedDirectiveDefs);
  17250. if (hostDirectiveResolution === null) {
  17251. directiveDefs = matchedDirectiveDefs;
  17252. }
  17253. else {
  17254. [directiveDefs, hostDirectiveDefs, hostDirectiveRanges] = hostDirectiveResolution;
  17255. }
  17256. initializeDirectives(tView, lView, tNode, directiveDefs, exportsMap, hostDirectiveDefs, hostDirectiveRanges);
  17257. }
  17258. if (exportsMap !== null && localRefs !== null) {
  17259. cacheMatchingLocalNames(tNode, localRefs, exportsMap);
  17260. }
  17261. }
  17262. /** Caches local names and their matching directive indices for query and template lookups. */
  17263. function cacheMatchingLocalNames(tNode, localRefs, exportsMap) {
  17264. const localNames = (tNode.localNames = []);
  17265. // Local names must be stored in tNode in the same order that localRefs are defined
  17266. // in the template to ensure the data is loaded in the same slots as their refs
  17267. // in the template (for template queries).
  17268. for (let i = 0; i < localRefs.length; i += 2) {
  17269. const index = exportsMap[localRefs[i + 1]];
  17270. if (index == null)
  17271. throw new RuntimeError(-301 /* RuntimeErrorCode.EXPORT_NOT_FOUND */, ngDevMode && `Export of name '${localRefs[i + 1]}' not found!`);
  17272. localNames.push(localRefs[i], index);
  17273. }
  17274. }
  17275. function resolveHostDirectives(matches) {
  17276. let componentDef = null;
  17277. let hasHostDirectives = false;
  17278. for (let i = 0; i < matches.length; i++) {
  17279. const def = matches[i];
  17280. if (i === 0 && isComponentDef(def)) {
  17281. componentDef = def;
  17282. }
  17283. if (def.findHostDirectiveDefs !== null) {
  17284. hasHostDirectives = true;
  17285. break;
  17286. }
  17287. }
  17288. if (!hasHostDirectives) {
  17289. return null;
  17290. }
  17291. let allDirectiveDefs = null;
  17292. let hostDirectiveDefs = null;
  17293. let hostDirectiveRanges = null;
  17294. // Components are inserted at the front of the matches array so that their lifecycle
  17295. // hooks run before any directive lifecycle hooks. This appears to be for ViewEngine
  17296. // compatibility. This logic doesn't make sense with host directives, because it
  17297. // would allow the host directives to undo any overrides the host may have made.
  17298. // To handle this case, the host directives of components are inserted at the beginning
  17299. // of the array, followed by the component. As such, the insertion order is as follows:
  17300. // 1. Host directives belonging to the selector-matched component.
  17301. // 2. Selector-matched component.
  17302. // 3. Host directives belonging to selector-matched directives.
  17303. // 4. Selector-matched dir
  17304. for (const def of matches) {
  17305. if (def.findHostDirectiveDefs !== null) {
  17306. allDirectiveDefs ??= [];
  17307. hostDirectiveDefs ??= new Map();
  17308. hostDirectiveRanges ??= new Map();
  17309. resolveHostDirectivesForDef(def, allDirectiveDefs, hostDirectiveRanges, hostDirectiveDefs);
  17310. }
  17311. // Component definition needs to be pushed early to maintain the correct ordering.
  17312. if (def === componentDef) {
  17313. allDirectiveDefs ??= [];
  17314. allDirectiveDefs.push(def);
  17315. }
  17316. }
  17317. if (allDirectiveDefs !== null) {
  17318. allDirectiveDefs.push(...(componentDef === null ? matches : matches.slice(1)));
  17319. ngDevMode && assertNoDuplicateDirectives(allDirectiveDefs);
  17320. return [allDirectiveDefs, hostDirectiveDefs, hostDirectiveRanges];
  17321. }
  17322. return null;
  17323. }
  17324. function resolveHostDirectivesForDef(def, allDirectiveDefs, hostDirectiveRanges, hostDirectiveDefs) {
  17325. ngDevMode && assertDefined(def.findHostDirectiveDefs, 'Expected host directive resolve function');
  17326. const start = allDirectiveDefs.length;
  17327. // TODO(pk): probably could return matches instead of taking in an array to fill in?
  17328. def.findHostDirectiveDefs(def, allDirectiveDefs, hostDirectiveDefs);
  17329. // Note that these indexes are within the offset by `directiveStart`. We can't do the
  17330. // offsetting here, because `directiveStart` hasn't been initialized on the TNode yet.
  17331. hostDirectiveRanges.set(def, [start, allDirectiveDefs.length - 1]);
  17332. }
  17333. /**
  17334. * Marks a given TNode as a component's host. This consists of:
  17335. * - setting the component offset on the TNode.
  17336. * - storing index of component's host element so it will be queued for view refresh during CD.
  17337. */
  17338. function markAsComponentHost(tView, hostTNode, componentOffset) {
  17339. ngDevMode && assertFirstCreatePass(tView);
  17340. ngDevMode && assertGreaterThan(componentOffset, -1, 'componentOffset must be great than -1');
  17341. hostTNode.componentOffset = componentOffset;
  17342. (tView.components ??= []).push(hostTNode.index);
  17343. }
  17344. /** Initializes the data structures necessary for a list of directives to be instantiated. */
  17345. function initializeDirectives(tView, lView, tNode, directives, exportsMap, hostDirectiveDefs, hostDirectiveRanges) {
  17346. ngDevMode && assertFirstCreatePass(tView);
  17347. const directivesLength = directives.length;
  17348. let hasSeenComponent = false;
  17349. // Publishes the directive types to DI so they can be injected. Needs to
  17350. // happen in a separate pass before the TNode flags have been initialized.
  17351. for (let i = 0; i < directivesLength; i++) {
  17352. const def = directives[i];
  17353. if (!hasSeenComponent && isComponentDef(def)) {
  17354. hasSeenComponent = true;
  17355. markAsComponentHost(tView, tNode, i);
  17356. }
  17357. diPublicInInjector(getOrCreateNodeInjectorForNode(tNode, lView), tView, def.type);
  17358. }
  17359. initTNodeFlags(tNode, tView.data.length, directivesLength);
  17360. // When the same token is provided by several directives on the same node, some rules apply in
  17361. // the viewEngine:
  17362. // - viewProviders have priority over providers
  17363. // - the last directive in NgModule.declarations has priority over the previous one
  17364. // So to match these rules, the order in which providers are added in the arrays is very
  17365. // important.
  17366. for (let i = 0; i < directivesLength; i++) {
  17367. const def = directives[i];
  17368. if (def.providersResolver)
  17369. def.providersResolver(def);
  17370. }
  17371. let preOrderHooksFound = false;
  17372. let preOrderCheckHooksFound = false;
  17373. let directiveIdx = allocExpando(tView, lView, directivesLength, null);
  17374. ngDevMode &&
  17375. assertSame(directiveIdx, tNode.directiveStart, 'TNode.directiveStart should point to just allocated space');
  17376. // If there's at least one directive, we'll have to track it so initialize the map.
  17377. if (directivesLength > 0) {
  17378. tNode.directiveToIndex = new Map();
  17379. }
  17380. for (let i = 0; i < directivesLength; i++) {
  17381. const def = directives[i];
  17382. // Merge the attrs in the order of matches. This assumes that the first directive is the
  17383. // component itself, so that the component has the least priority.
  17384. tNode.mergedAttrs = mergeHostAttrs(tNode.mergedAttrs, def.hostAttrs);
  17385. configureViewWithDirective(tView, tNode, lView, directiveIdx, def);
  17386. saveNameToExportMap(directiveIdx, def, exportsMap);
  17387. // If a directive has host directives, we need to track both its index and the range within
  17388. // the host directives are declared. Host directives are not tracked, but should be resolved
  17389. // by looking up the host and getting its indexes from there.
  17390. if (hostDirectiveRanges !== null && hostDirectiveRanges.has(def)) {
  17391. const [start, end] = hostDirectiveRanges.get(def);
  17392. tNode.directiveToIndex.set(def.type, [
  17393. directiveIdx,
  17394. start + tNode.directiveStart,
  17395. end + tNode.directiveStart,
  17396. ]);
  17397. }
  17398. else if (hostDirectiveDefs === null || !hostDirectiveDefs.has(def)) {
  17399. tNode.directiveToIndex.set(def.type, directiveIdx);
  17400. }
  17401. if (def.contentQueries !== null)
  17402. tNode.flags |= 4 /* TNodeFlags.hasContentQuery */;
  17403. if (def.hostBindings !== null || def.hostAttrs !== null || def.hostVars !== 0)
  17404. tNode.flags |= 64 /* TNodeFlags.hasHostBindings */;
  17405. const lifeCycleHooks = def.type.prototype;
  17406. // Only push a node index into the preOrderHooks array if this is the first
  17407. // pre-order hook found on this node.
  17408. if (!preOrderHooksFound &&
  17409. (lifeCycleHooks.ngOnChanges || lifeCycleHooks.ngOnInit || lifeCycleHooks.ngDoCheck)) {
  17410. // We will push the actual hook function into this array later during dir instantiation.
  17411. // We cannot do it now because we must ensure hooks are registered in the same
  17412. // order that directives are created (i.e. injection order).
  17413. (tView.preOrderHooks ??= []).push(tNode.index);
  17414. preOrderHooksFound = true;
  17415. }
  17416. if (!preOrderCheckHooksFound && (lifeCycleHooks.ngOnChanges || lifeCycleHooks.ngDoCheck)) {
  17417. (tView.preOrderCheckHooks ??= []).push(tNode.index);
  17418. preOrderCheckHooksFound = true;
  17419. }
  17420. directiveIdx++;
  17421. }
  17422. initializeInputAndOutputAliases(tView, tNode, hostDirectiveDefs);
  17423. }
  17424. /**
  17425. * Initializes data structures required to work with directive inputs and outputs.
  17426. * Initialization is done for all directives matched on a given TNode.
  17427. */
  17428. function initializeInputAndOutputAliases(tView, tNode, hostDirectiveDefs) {
  17429. ngDevMode && assertFirstCreatePass(tView);
  17430. for (let index = tNode.directiveStart; index < tNode.directiveEnd; index++) {
  17431. const directiveDef = tView.data[index];
  17432. if (hostDirectiveDefs === null || !hostDirectiveDefs.has(directiveDef)) {
  17433. setupSelectorMatchedInputsOrOutputs(0 /* BindingType.Inputs */, tNode, directiveDef, index);
  17434. setupSelectorMatchedInputsOrOutputs(1 /* BindingType.Outputs */, tNode, directiveDef, index);
  17435. setupInitialInputs(tNode, index, false);
  17436. }
  17437. else {
  17438. const hostDirectiveDef = hostDirectiveDefs.get(directiveDef);
  17439. setupHostDirectiveInputsOrOutputs(0 /* BindingType.Inputs */, tNode, hostDirectiveDef, index);
  17440. setupHostDirectiveInputsOrOutputs(1 /* BindingType.Outputs */, tNode, hostDirectiveDef, index);
  17441. setupInitialInputs(tNode, index, true);
  17442. }
  17443. }
  17444. }
  17445. /**
  17446. * Sets up the input/output bindings for a directive that was matched in the template through its
  17447. * selector. This method is called repeatedly to build up all of the available inputs on a node.
  17448. *
  17449. * @param mode Whether inputs or outputs are being contructed.
  17450. * @param tNode Node on which the bindings are being set up.
  17451. * @param def Directive definition for which the bindings are being set up.
  17452. * @param directiveIndex Index at which the directive instance will be stored in the LView.
  17453. */
  17454. function setupSelectorMatchedInputsOrOutputs(mode, tNode, def, directiveIndex) {
  17455. const aliasMap = mode === 0 /* BindingType.Inputs */ ? def.inputs : def.outputs;
  17456. for (const publicName in aliasMap) {
  17457. if (aliasMap.hasOwnProperty(publicName)) {
  17458. let bindings;
  17459. if (mode === 0 /* BindingType.Inputs */) {
  17460. bindings = tNode.inputs ??= {};
  17461. }
  17462. else {
  17463. bindings = tNode.outputs ??= {};
  17464. }
  17465. bindings[publicName] ??= [];
  17466. bindings[publicName].push(directiveIndex);
  17467. setShadowStylingInputFlags(tNode, publicName);
  17468. }
  17469. }
  17470. }
  17471. /**
  17472. * Sets up input/output bindings that were defined through host directives on a specific node.
  17473. * @param mode Whether inputs or outputs are being contructed.
  17474. * @param tNode Node on which the bindings are being set up.
  17475. * @param config Host directive definition that is being set up.
  17476. * @param directiveIndex Index at which the directive instance will be stored in the LView.
  17477. */
  17478. function setupHostDirectiveInputsOrOutputs(mode, tNode, config, directiveIndex) {
  17479. const aliasMap = mode === 0 /* BindingType.Inputs */ ? config.inputs : config.outputs;
  17480. for (const initialName in aliasMap) {
  17481. if (aliasMap.hasOwnProperty(initialName)) {
  17482. const publicName = aliasMap[initialName];
  17483. let bindings;
  17484. if (mode === 0 /* BindingType.Inputs */) {
  17485. bindings = tNode.hostDirectiveInputs ??= {};
  17486. }
  17487. else {
  17488. bindings = tNode.hostDirectiveOutputs ??= {};
  17489. }
  17490. bindings[publicName] ??= [];
  17491. bindings[publicName].push(directiveIndex, initialName);
  17492. setShadowStylingInputFlags(tNode, publicName);
  17493. }
  17494. }
  17495. }
  17496. function setShadowStylingInputFlags(tNode, publicName) {
  17497. if (publicName === 'class') {
  17498. tNode.flags |= 8 /* TNodeFlags.hasClassInput */;
  17499. }
  17500. else if (publicName === 'style') {
  17501. tNode.flags |= 16 /* TNodeFlags.hasStyleInput */;
  17502. }
  17503. }
  17504. /**
  17505. * Sets up the initialInputData for a node and stores it in the template's static storage
  17506. * so subsequent template invocations don't have to recalculate it.
  17507. *
  17508. * initialInputData is an array containing values that need to be set as input properties
  17509. * for directives on this node, but only once on creation. We need this array to support
  17510. * the case where you set an @Input property of a directive using attribute-like syntax.
  17511. * e.g. if you have a `name` @Input, you can set it once like this:
  17512. *
  17513. * <my-component name="Bess"></my-component>
  17514. *
  17515. * @param tNode TNode on which to set up the initial inputs.
  17516. * @param directiveIndex Index of the directive that is currently being processed.
  17517. */
  17518. function setupInitialInputs(tNode, directiveIndex, isHostDirective) {
  17519. const { attrs, inputs, hostDirectiveInputs } = tNode;
  17520. if (attrs === null ||
  17521. (!isHostDirective && inputs === null) ||
  17522. (isHostDirective && hostDirectiveInputs === null) ||
  17523. // Do not use unbound attributes as inputs to structural directives, since structural
  17524. // directive inputs can only be set using microsyntax (e.g. `<div *dir="exp">`).
  17525. isInlineTemplate(tNode)) {
  17526. tNode.initialInputs ??= [];
  17527. tNode.initialInputs.push(null);
  17528. return;
  17529. }
  17530. let inputsToStore = null;
  17531. let i = 0;
  17532. while (i < attrs.length) {
  17533. const attrName = attrs[i];
  17534. if (attrName === 0 /* AttributeMarker.NamespaceURI */) {
  17535. // We do not allow inputs on namespaced attributes.
  17536. i += 4;
  17537. continue;
  17538. }
  17539. else if (attrName === 5 /* AttributeMarker.ProjectAs */) {
  17540. // Skip over the `ngProjectAs` value.
  17541. i += 2;
  17542. continue;
  17543. }
  17544. else if (typeof attrName === 'number') {
  17545. // If we hit any other attribute markers, we're done anyway. None of those are valid inputs.
  17546. break;
  17547. }
  17548. if (!isHostDirective && inputs.hasOwnProperty(attrName)) {
  17549. // Find the input's public name from the input store. Note that we can be found easier
  17550. // through the directive def, but we want to do it using the inputs store so that it can
  17551. // account for host directive aliases.
  17552. const inputConfig = inputs[attrName];
  17553. for (const index of inputConfig) {
  17554. if (index === directiveIndex) {
  17555. inputsToStore ??= [];
  17556. inputsToStore.push(attrName, attrs[i + 1]);
  17557. // A directive can't have multiple inputs with the same name so we can break here.
  17558. break;
  17559. }
  17560. }
  17561. }
  17562. else if (isHostDirective && hostDirectiveInputs.hasOwnProperty(attrName)) {
  17563. const config = hostDirectiveInputs[attrName];
  17564. for (let j = 0; j < config.length; j += 2) {
  17565. if (config[j] === directiveIndex) {
  17566. inputsToStore ??= [];
  17567. inputsToStore.push(config[j + 1], attrs[i + 1]);
  17568. break;
  17569. }
  17570. }
  17571. }
  17572. i += 2;
  17573. }
  17574. tNode.initialInputs ??= [];
  17575. tNode.initialInputs.push(inputsToStore);
  17576. }
  17577. /**
  17578. * Setup directive for instantiation.
  17579. *
  17580. * We need to create a `NodeInjectorFactory` which is then inserted in both the `Blueprint` as well
  17581. * as `LView`. `TView` gets the `DirectiveDef`.
  17582. *
  17583. * @param tView `TView`
  17584. * @param tNode `TNode`
  17585. * @param lView `LView`
  17586. * @param directiveIndex Index where the directive will be stored in the Expando.
  17587. * @param def `DirectiveDef`
  17588. */
  17589. function configureViewWithDirective(tView, tNode, lView, directiveIndex, def) {
  17590. ngDevMode &&
  17591. assertGreaterThanOrEqual(directiveIndex, HEADER_OFFSET, 'Must be in Expando section');
  17592. tView.data[directiveIndex] = def;
  17593. const directiveFactory = def.factory || (def.factory = getFactoryDef(def.type, true));
  17594. // Even though `directiveFactory` will already be using `ɵɵdirectiveInject` in its generated code,
  17595. // we also want to support `inject()` directly from the directive constructor context so we set
  17596. // `ɵɵdirectiveInject` as the inject implementation here too.
  17597. const nodeInjectorFactory = new NodeInjectorFactory(directiveFactory, isComponentDef(def), ɵɵdirectiveInject);
  17598. tView.blueprint[directiveIndex] = nodeInjectorFactory;
  17599. lView[directiveIndex] = nodeInjectorFactory;
  17600. registerHostBindingOpCodes(tView, tNode, directiveIndex, allocExpando(tView, lView, def.hostVars, NO_CHANGE), def);
  17601. }
  17602. /**
  17603. * Add `hostBindings` to the `TView.hostBindingOpCodes`.
  17604. *
  17605. * @param tView `TView` to which the `hostBindings` should be added.
  17606. * @param tNode `TNode` the element which contains the directive
  17607. * @param directiveIdx Directive index in view.
  17608. * @param directiveVarsIdx Where will the directive's vars be stored
  17609. * @param def `ComponentDef`/`DirectiveDef`, which contains the `hostVars`/`hostBindings` to add.
  17610. */
  17611. function registerHostBindingOpCodes(tView, tNode, directiveIdx, directiveVarsIdx, def) {
  17612. ngDevMode && assertFirstCreatePass(tView);
  17613. const hostBindings = def.hostBindings;
  17614. if (hostBindings) {
  17615. let hostBindingOpCodes = tView.hostBindingOpCodes;
  17616. if (hostBindingOpCodes === null) {
  17617. hostBindingOpCodes = tView.hostBindingOpCodes = [];
  17618. }
  17619. const elementIndx = ~tNode.index;
  17620. if (lastSelectedElementIdx(hostBindingOpCodes) != elementIndx) {
  17621. // Conditionally add select element so that we are more efficient in execution.
  17622. // NOTE: this is strictly not necessary and it trades code size for runtime perf.
  17623. // (We could just always add it.)
  17624. hostBindingOpCodes.push(elementIndx);
  17625. }
  17626. hostBindingOpCodes.push(directiveIdx, directiveVarsIdx, hostBindings);
  17627. }
  17628. }
  17629. /**
  17630. * Returns the last selected element index in the `HostBindingOpCodes`
  17631. *
  17632. * For perf reasons we don't need to update the selected element index in `HostBindingOpCodes` only
  17633. * if it changes. This method returns the last index (or '0' if not found.)
  17634. *
  17635. * Selected element index are only the ones which are negative.
  17636. */
  17637. function lastSelectedElementIdx(hostBindingOpCodes) {
  17638. let i = hostBindingOpCodes.length;
  17639. while (i > 0) {
  17640. const value = hostBindingOpCodes[--i];
  17641. if (typeof value === 'number' && value < 0) {
  17642. return value;
  17643. }
  17644. }
  17645. return 0;
  17646. }
  17647. /**
  17648. * Builds up an export map as directives are created, so local refs can be quickly mapped
  17649. * to their directive instances.
  17650. */
  17651. function saveNameToExportMap(directiveIdx, def, exportsMap) {
  17652. if (exportsMap) {
  17653. if (def.exportAs) {
  17654. for (let i = 0; i < def.exportAs.length; i++) {
  17655. exportsMap[def.exportAs[i]] = directiveIdx;
  17656. }
  17657. }
  17658. if (isComponentDef(def))
  17659. exportsMap[''] = directiveIdx;
  17660. }
  17661. }
  17662. /**
  17663. * Initializes the flags on the current node, setting all indices to the initial index,
  17664. * the directive count to 0, and adding the isComponent flag.
  17665. * @param index the initial index
  17666. */
  17667. function initTNodeFlags(tNode, index, numberOfDirectives) {
  17668. ngDevMode &&
  17669. assertNotEqual(numberOfDirectives, tNode.directiveEnd - tNode.directiveStart, 'Reached the max number of directives');
  17670. tNode.flags |= 1 /* TNodeFlags.isDirectiveHost */;
  17671. // When the first directive is created on a node, save the index
  17672. tNode.directiveStart = index;
  17673. tNode.directiveEnd = index + numberOfDirectives;
  17674. tNode.providerIndexes = index;
  17675. }
  17676. function assertNoDuplicateDirectives(directives) {
  17677. // The array needs at least two elements in order to have duplicates.
  17678. if (directives.length < 2) {
  17679. return;
  17680. }
  17681. const seenDirectives = new Set();
  17682. for (const current of directives) {
  17683. if (seenDirectives.has(current)) {
  17684. throw new RuntimeError(309 /* RuntimeErrorCode.DUPLICATE_DIRECTIVE */, `Directive ${current.type.name} matches multiple times on the same element. ` +
  17685. `Directives can only match an element once.`);
  17686. }
  17687. seenDirectives.add(current);
  17688. }
  17689. }
  17690. function elementStartFirstCreatePass(index, tView, lView, name, directiveMatcher, bindingsEnabled, attrsIndex, localRefsIndex) {
  17691. ngDevMode && assertFirstCreatePass(tView);
  17692. ngDevMode && ngDevMode.firstCreatePass++;
  17693. const tViewConsts = tView.consts;
  17694. const attrs = getConstant(tViewConsts, attrsIndex);
  17695. const tNode = getOrCreateTNode(tView, index, 2 /* TNodeType.Element */, name, attrs);
  17696. if (bindingsEnabled) {
  17697. resolveDirectives(tView, lView, tNode, getConstant(tViewConsts, localRefsIndex), directiveMatcher);
  17698. }
  17699. // Merge the template attrs last so that they have the highest priority.
  17700. tNode.mergedAttrs = mergeHostAttrs(tNode.mergedAttrs, tNode.attrs);
  17701. if (tNode.attrs !== null) {
  17702. computeStaticStyling(tNode, tNode.attrs, false);
  17703. }
  17704. if (tNode.mergedAttrs !== null) {
  17705. computeStaticStyling(tNode, tNode.mergedAttrs, true);
  17706. }
  17707. if (tView.queries !== null) {
  17708. tView.queries.elementStart(tView, tNode);
  17709. }
  17710. return tNode;
  17711. }
  17712. function elementEndFirstCreatePass(tView, tNode) {
  17713. ngDevMode && assertFirstCreatePass(tView);
  17714. registerPostOrderHooks(tView, tNode);
  17715. if (isContentQueryHost(tNode)) {
  17716. tView.queries.elementEnd(tNode);
  17717. }
  17718. }
  17719. class ComponentFactoryResolver extends ComponentFactoryResolver$1 {
  17720. ngModule;
  17721. /**
  17722. * @param ngModule The NgModuleRef to which all resolved factories are bound.
  17723. */
  17724. constructor(ngModule) {
  17725. super();
  17726. this.ngModule = ngModule;
  17727. }
  17728. resolveComponentFactory(component) {
  17729. ngDevMode && assertComponentType(component);
  17730. const componentDef = getComponentDef(component);
  17731. return new ComponentFactory(componentDef, this.ngModule);
  17732. }
  17733. }
  17734. function toInputRefArray(map) {
  17735. return Object.keys(map).map((name) => {
  17736. const [propName, flags, transform] = map[name];
  17737. const inputData = {
  17738. propName: propName,
  17739. templateName: name,
  17740. isSignal: (flags & InputFlags.SignalBased) !== 0,
  17741. };
  17742. if (transform) {
  17743. inputData.transform = transform;
  17744. }
  17745. return inputData;
  17746. });
  17747. }
  17748. function toOutputRefArray(map) {
  17749. return Object.keys(map).map((name) => ({ propName: map[name], templateName: name }));
  17750. }
  17751. function verifyNotAnOrphanComponent(componentDef) {
  17752. // TODO(pk): create assert that verifies ngDevMode
  17753. if ((typeof ngJitMode === 'undefined' || ngJitMode) &&
  17754. componentDef.debugInfo?.forbidOrphanRendering) {
  17755. if (depsTracker.isOrphanComponent(componentDef.type)) {
  17756. 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.`);
  17757. }
  17758. }
  17759. }
  17760. function createRootViewInjector(componentDef, environmentInjector, injector) {
  17761. let realEnvironmentInjector = environmentInjector instanceof EnvironmentInjector
  17762. ? environmentInjector
  17763. : environmentInjector?.injector;
  17764. if (realEnvironmentInjector && componentDef.getStandaloneInjector !== null) {
  17765. realEnvironmentInjector =
  17766. componentDef.getStandaloneInjector(realEnvironmentInjector) || realEnvironmentInjector;
  17767. }
  17768. const rootViewInjector = realEnvironmentInjector
  17769. ? new ChainedInjector(injector, realEnvironmentInjector)
  17770. : injector;
  17771. return rootViewInjector;
  17772. }
  17773. function createRootLViewEnvironment(rootLViewInjector) {
  17774. const rendererFactory = rootLViewInjector.get(RendererFactory2, null);
  17775. if (rendererFactory === null) {
  17776. throw new RuntimeError(407 /* RuntimeErrorCode.RENDERER_NOT_FOUND */, ngDevMode &&
  17777. 'Angular was not able to inject a renderer (RendererFactory2). ' +
  17778. 'Likely this is due to a broken DI hierarchy. ' +
  17779. 'Make sure that any injector used to create this component has a correct parent.');
  17780. }
  17781. const sanitizer = rootLViewInjector.get(Sanitizer, null);
  17782. const changeDetectionScheduler = rootLViewInjector.get(ChangeDetectionScheduler, null);
  17783. return {
  17784. rendererFactory,
  17785. sanitizer,
  17786. changeDetectionScheduler,
  17787. };
  17788. }
  17789. function createHostElement(componentDef, render) {
  17790. // Determine a tag name used for creating host elements when this component is created
  17791. // dynamically. Default to 'div' if this component did not specify any tag name in its
  17792. // selector.
  17793. const tagName = (componentDef.selectors[0][0] || 'div').toLowerCase();
  17794. const namespace = tagName === 'svg' ? SVG_NAMESPACE : tagName === 'math' ? MATH_ML_NAMESPACE : null;
  17795. return createElementNode(render, tagName, namespace);
  17796. }
  17797. /**
  17798. * ComponentFactory interface implementation.
  17799. */
  17800. class ComponentFactory extends ComponentFactory$1 {
  17801. componentDef;
  17802. ngModule;
  17803. selector;
  17804. componentType;
  17805. ngContentSelectors;
  17806. isBoundToModule;
  17807. cachedInputs = null;
  17808. cachedOutputs = null;
  17809. get inputs() {
  17810. this.cachedInputs ??= toInputRefArray(this.componentDef.inputs);
  17811. return this.cachedInputs;
  17812. }
  17813. get outputs() {
  17814. this.cachedOutputs ??= toOutputRefArray(this.componentDef.outputs);
  17815. return this.cachedOutputs;
  17816. }
  17817. /**
  17818. * @param componentDef The component definition.
  17819. * @param ngModule The NgModuleRef to which the factory is bound.
  17820. */
  17821. constructor(componentDef, ngModule) {
  17822. super();
  17823. this.componentDef = componentDef;
  17824. this.ngModule = ngModule;
  17825. this.componentType = componentDef.type;
  17826. this.selector = stringifyCSSSelectorList(componentDef.selectors);
  17827. this.ngContentSelectors = componentDef.ngContentSelectors ?? [];
  17828. this.isBoundToModule = !!ngModule;
  17829. }
  17830. create(injector, projectableNodes, rootSelectorOrNode, environmentInjector) {
  17831. profiler(22 /* ProfilerEvent.DynamicComponentStart */);
  17832. const prevConsumer = setActiveConsumer$1(null);
  17833. try {
  17834. const cmpDef = this.componentDef;
  17835. ngDevMode && verifyNotAnOrphanComponent(cmpDef);
  17836. const tAttributes = rootSelectorOrNode
  17837. ? ['ng-version', '19.2.13']
  17838. : // Extract attributes and classes from the first selector only to match VE behavior.
  17839. extractAttrsAndClassesFromSelector(this.componentDef.selectors[0]);
  17840. // Create the root view. Uses empty TView and ContentTemplate.
  17841. const rootTView = createTView(0 /* TViewType.Root */, null, null, 1, 0, null, null, null, null, [tAttributes], null);
  17842. const rootViewInjector = createRootViewInjector(cmpDef, environmentInjector || this.ngModule, injector);
  17843. const environment = createRootLViewEnvironment(rootViewInjector);
  17844. const hostRenderer = environment.rendererFactory.createRenderer(null, cmpDef);
  17845. const hostElement = rootSelectorOrNode
  17846. ? locateHostElement(hostRenderer, rootSelectorOrNode, cmpDef.encapsulation, rootViewInjector)
  17847. : createHostElement(cmpDef, hostRenderer);
  17848. const rootLView = createLView(null, rootTView, null, 512 /* LViewFlags.IsRoot */ | getInitialLViewFlagsFromDef(cmpDef), null, null, environment, hostRenderer, rootViewInjector, null, retrieveHydrationInfo(hostElement, rootViewInjector, true /* isRootView */));
  17849. rootLView[HEADER_OFFSET] = hostElement;
  17850. // rootView is the parent when bootstrapping
  17851. // TODO(misko): it looks like we are entering view here but we don't really need to as
  17852. // `renderView` does that. However as the code is written it is needed because
  17853. // `createRootComponentView` and `createRootComponent` both read global state. Fixing those
  17854. // issues would allow us to drop this.
  17855. enterView(rootLView);
  17856. let componentView = null;
  17857. try {
  17858. const hostTNode = elementStartFirstCreatePass(HEADER_OFFSET, rootTView, rootLView, '#host', () => [this.componentDef], true, 0);
  17859. // ---- element instruction
  17860. // TODO(crisbeto): in practice `hostRNode` should always be defined, but there are some
  17861. // tests where the renderer is mocked out and `undefined` is returned. We should update the
  17862. // tests so that this check can be removed.
  17863. if (hostElement) {
  17864. setupStaticAttributes(hostRenderer, hostElement, hostTNode);
  17865. attachPatchData(hostElement, rootLView);
  17866. }
  17867. // TODO(pk): this logic is similar to the instruction code where a node can have directives
  17868. createDirectivesInstances(rootTView, rootLView, hostTNode);
  17869. executeContentQueries(rootTView, hostTNode, rootLView);
  17870. elementEndFirstCreatePass(rootTView, hostTNode);
  17871. if (projectableNodes !== undefined) {
  17872. projectNodes(hostTNode, this.ngContentSelectors, projectableNodes);
  17873. }
  17874. componentView = getComponentLViewByIndex(hostTNode.index, rootLView);
  17875. // TODO(pk): why do we need this logic?
  17876. rootLView[CONTEXT] = componentView[CONTEXT];
  17877. renderView(rootTView, rootLView, null);
  17878. }
  17879. catch (e) {
  17880. // Stop tracking the views if creation failed since
  17881. // the consumer won't have a way to dereference them.
  17882. if (componentView !== null) {
  17883. unregisterLView(componentView);
  17884. }
  17885. unregisterLView(rootLView);
  17886. throw e;
  17887. }
  17888. finally {
  17889. profiler(23 /* ProfilerEvent.DynamicComponentEnd */);
  17890. leaveView();
  17891. }
  17892. return new ComponentRef(this.componentType, rootLView);
  17893. }
  17894. finally {
  17895. setActiveConsumer$1(prevConsumer);
  17896. }
  17897. }
  17898. }
  17899. /**
  17900. * Represents an instance of a Component created via a {@link ComponentFactory}.
  17901. *
  17902. * `ComponentRef` provides access to the Component Instance as well other objects related to this
  17903. * Component Instance and allows you to destroy the Component Instance via the {@link #destroy}
  17904. * method.
  17905. *
  17906. */
  17907. class ComponentRef extends ComponentRef$1 {
  17908. _rootLView;
  17909. instance;
  17910. hostView;
  17911. changeDetectorRef;
  17912. componentType;
  17913. location;
  17914. previousInputValues = null;
  17915. _tNode;
  17916. constructor(componentType, _rootLView) {
  17917. super();
  17918. this._rootLView = _rootLView;
  17919. this._tNode = getTNode(_rootLView[TVIEW], HEADER_OFFSET);
  17920. this.location = createElementRef(this._tNode, _rootLView);
  17921. this.instance = getComponentLViewByIndex(this._tNode.index, _rootLView)[CONTEXT];
  17922. this.hostView = this.changeDetectorRef = new ViewRef$1(_rootLView, undefined /* _cdRefInjectingView */, false /* notifyErrorHandler */);
  17923. this.componentType = componentType;
  17924. }
  17925. setInput(name, value) {
  17926. const tNode = this._tNode;
  17927. this.previousInputValues ??= new Map();
  17928. // Do not set the input if it is the same as the last value
  17929. // This behavior matches `bindingUpdated` when binding inputs in templates.
  17930. if (this.previousInputValues.has(name) &&
  17931. Object.is(this.previousInputValues.get(name), value)) {
  17932. return;
  17933. }
  17934. const lView = this._rootLView;
  17935. const hasSetInput = setAllInputsForProperty(tNode, lView[TVIEW], lView, name, value);
  17936. this.previousInputValues.set(name, value);
  17937. const childComponentLView = getComponentLViewByIndex(tNode.index, lView);
  17938. markViewDirty(childComponentLView, 1 /* NotificationSource.SetInput */);
  17939. if (ngDevMode && !hasSetInput) {
  17940. const cmpNameForError = stringifyForError(this.componentType);
  17941. let message = `Can't set value of the '${name}' input on the '${cmpNameForError}' component. `;
  17942. message += `Make sure that the '${name}' property is annotated with @Input() or a mapped @Input('${name}') exists.`;
  17943. reportUnknownPropertyError(message);
  17944. }
  17945. }
  17946. get injector() {
  17947. return new NodeInjector(this._tNode, this._rootLView);
  17948. }
  17949. destroy() {
  17950. this.hostView.destroy();
  17951. }
  17952. onDestroy(callback) {
  17953. this.hostView.onDestroy(callback);
  17954. }
  17955. }
  17956. /** Projects the `projectableNodes` that were specified when creating a root component. */
  17957. function projectNodes(tNode, ngContentSelectors, projectableNodes) {
  17958. const projection = (tNode.projection = []);
  17959. for (let i = 0; i < ngContentSelectors.length; i++) {
  17960. const nodesforSlot = projectableNodes[i];
  17961. // Projectable nodes can be passed as array of arrays or an array of iterables (ngUpgrade
  17962. // case). Here we do normalize passed data structure to be an array of arrays to avoid
  17963. // complex checks down the line.
  17964. // We also normalize the length of the passed in projectable nodes (to match the number of
  17965. // <ng-container> slots defined by a component).
  17966. projection.push(nodesforSlot != null && nodesforSlot.length ? Array.from(nodesforSlot) : null);
  17967. }
  17968. }
  17969. /**
  17970. * Represents a container where one or more views can be attached to a component.
  17971. *
  17972. * Can contain *host views* (created by instantiating a
  17973. * component with the `createComponent()` method), and *embedded views*
  17974. * (created by instantiating a `TemplateRef` with the `createEmbeddedView()` method).
  17975. *
  17976. * A view container instance can contain other view containers,
  17977. * creating a view hierarchy.
  17978. *
  17979. * @usageNotes
  17980. *
  17981. * The example below demonstrates how the `createComponent` function can be used
  17982. * to create an instance of a ComponentRef dynamically and attach it to an ApplicationRef,
  17983. * so that it gets included into change detection cycles.
  17984. *
  17985. * Note: the example uses standalone components, but the function can also be used for
  17986. * non-standalone components (declared in an NgModule) as well.
  17987. *
  17988. * ```angular-ts
  17989. * @Component({
  17990. * standalone: true,
  17991. * selector: 'dynamic',
  17992. * template: `<span>This is a content of a dynamic component.</span>`,
  17993. * })
  17994. * class DynamicComponent {
  17995. * vcr = inject(ViewContainerRef);
  17996. * }
  17997. *
  17998. * @Component({
  17999. * standalone: true,
  18000. * selector: 'app',
  18001. * template: `<main>Hi! This is the main content.</main>`,
  18002. * })
  18003. * class AppComponent {
  18004. * vcr = inject(ViewContainerRef);
  18005. *
  18006. * ngAfterViewInit() {
  18007. * const compRef = this.vcr.createComponent(DynamicComponent);
  18008. * compRef.changeDetectorRef.detectChanges();
  18009. * }
  18010. * }
  18011. * ```
  18012. *
  18013. * @see {@link ComponentRef}
  18014. * @see {@link EmbeddedViewRef}
  18015. *
  18016. * @publicApi
  18017. */
  18018. class ViewContainerRef {
  18019. /**
  18020. * @internal
  18021. * @nocollapse
  18022. */
  18023. static __NG_ELEMENT_ID__ = injectViewContainerRef;
  18024. }
  18025. /**
  18026. * Creates a ViewContainerRef and stores it on the injector. Or, if the ViewContainerRef
  18027. * already exists, retrieves the existing ViewContainerRef.
  18028. *
  18029. * @returns The ViewContainerRef instance to use
  18030. */
  18031. function injectViewContainerRef() {
  18032. const previousTNode = getCurrentTNode();
  18033. return createContainerRef(previousTNode, getLView());
  18034. }
  18035. const VE_ViewContainerRef = ViewContainerRef;
  18036. // TODO(alxhub): cleaning up this indirection triggers a subtle bug in Closure in g3. Once the fix
  18037. // for that lands, this can be cleaned up.
  18038. const R3ViewContainerRef = class ViewContainerRef extends VE_ViewContainerRef {
  18039. _lContainer;
  18040. _hostTNode;
  18041. _hostLView;
  18042. constructor(_lContainer, _hostTNode, _hostLView) {
  18043. super();
  18044. this._lContainer = _lContainer;
  18045. this._hostTNode = _hostTNode;
  18046. this._hostLView = _hostLView;
  18047. }
  18048. get element() {
  18049. return createElementRef(this._hostTNode, this._hostLView);
  18050. }
  18051. get injector() {
  18052. return new NodeInjector(this._hostTNode, this._hostLView);
  18053. }
  18054. /** @deprecated No replacement */
  18055. get parentInjector() {
  18056. const parentLocation = getParentInjectorLocation(this._hostTNode, this._hostLView);
  18057. if (hasParentInjector(parentLocation)) {
  18058. const parentView = getParentInjectorView(parentLocation, this._hostLView);
  18059. const injectorIndex = getParentInjectorIndex(parentLocation);
  18060. ngDevMode && assertNodeInjector(parentView, injectorIndex);
  18061. const parentTNode = parentView[TVIEW].data[injectorIndex + 8 /* NodeInjectorOffset.TNODE */];
  18062. return new NodeInjector(parentTNode, parentView);
  18063. }
  18064. else {
  18065. return new NodeInjector(null, this._hostLView);
  18066. }
  18067. }
  18068. clear() {
  18069. while (this.length > 0) {
  18070. this.remove(this.length - 1);
  18071. }
  18072. }
  18073. get(index) {
  18074. const viewRefs = getViewRefs(this._lContainer);
  18075. return (viewRefs !== null && viewRefs[index]) || null;
  18076. }
  18077. get length() {
  18078. return this._lContainer.length - CONTAINER_HEADER_OFFSET;
  18079. }
  18080. createEmbeddedView(templateRef, context, indexOrOptions) {
  18081. let index;
  18082. let injector;
  18083. if (typeof indexOrOptions === 'number') {
  18084. index = indexOrOptions;
  18085. }
  18086. else if (indexOrOptions != null) {
  18087. index = indexOrOptions.index;
  18088. injector = indexOrOptions.injector;
  18089. }
  18090. const dehydratedView = findMatchingDehydratedView(this._lContainer, templateRef.ssrId);
  18091. const viewRef = templateRef.createEmbeddedViewImpl(context || {}, injector, dehydratedView);
  18092. this.insertImpl(viewRef, index, shouldAddViewToDom(this._hostTNode, dehydratedView));
  18093. return viewRef;
  18094. }
  18095. createComponent(componentFactoryOrType, indexOrOptions, injector, projectableNodes, environmentInjector) {
  18096. const isComponentFactory = componentFactoryOrType && !isType(componentFactoryOrType);
  18097. let index;
  18098. // This function supports 2 signatures and we need to handle options correctly for both:
  18099. // 1. When first argument is a Component type. This signature also requires extra
  18100. // options to be provided as object (more ergonomic option).
  18101. // 2. First argument is a Component factory. In this case extra options are represented as
  18102. // positional arguments. This signature is less ergonomic and will be deprecated.
  18103. if (isComponentFactory) {
  18104. if (ngDevMode) {
  18105. assertEqual(typeof indexOrOptions !== 'object', true, 'It looks like Component factory was provided as the first argument ' +
  18106. 'and an options object as the second argument. This combination of arguments ' +
  18107. 'is incompatible. You can either change the first argument to provide Component ' +
  18108. 'type or change the second argument to be a number (representing an index at ' +
  18109. "which to insert the new component's host view into this container)");
  18110. }
  18111. index = indexOrOptions;
  18112. }
  18113. else {
  18114. if (ngDevMode) {
  18115. assertDefined(getComponentDef(componentFactoryOrType), `Provided Component class doesn't contain Component definition. ` +
  18116. `Please check whether provided class has @Component decorator.`);
  18117. assertEqual(typeof indexOrOptions !== 'number', true, 'It looks like Component type was provided as the first argument ' +
  18118. "and a number (representing an index at which to insert the new component's " +
  18119. 'host view into this container as the second argument. This combination of arguments ' +
  18120. 'is incompatible. Please use an object as the second argument instead.');
  18121. }
  18122. const options = (indexOrOptions || {});
  18123. if (ngDevMode && options.environmentInjector && options.ngModuleRef) {
  18124. throwError(`Cannot pass both environmentInjector and ngModuleRef options to createComponent().`);
  18125. }
  18126. index = options.index;
  18127. injector = options.injector;
  18128. projectableNodes = options.projectableNodes;
  18129. environmentInjector = options.environmentInjector || options.ngModuleRef;
  18130. }
  18131. const componentFactory = isComponentFactory
  18132. ? componentFactoryOrType
  18133. : new ComponentFactory(getComponentDef(componentFactoryOrType));
  18134. const contextInjector = injector || this.parentInjector;
  18135. // If an `NgModuleRef` is not provided explicitly, try retrieving it from the DI tree.
  18136. if (!environmentInjector && componentFactory.ngModule == null) {
  18137. // For the `ComponentFactory` case, entering this logic is very unlikely, since we expect that
  18138. // an instance of a `ComponentFactory`, resolved via `ComponentFactoryResolver` would have an
  18139. // `ngModule` field. This is possible in some test scenarios and potentially in some JIT-based
  18140. // use-cases. For the `ComponentFactory` case we preserve backwards-compatibility and try
  18141. // using a provided injector first, then fall back to the parent injector of this
  18142. // `ViewContainerRef` instance.
  18143. //
  18144. // For the factory-less case, it's critical to establish a connection with the module
  18145. // injector tree (by retrieving an instance of an `NgModuleRef` and accessing its injector),
  18146. // so that a component can use DI tokens provided in MgModules. For this reason, we can not
  18147. // rely on the provided injector, since it might be detached from the DI tree (for example, if
  18148. // it was created via `Injector.create` without specifying a parent injector, or if an
  18149. // injector is retrieved from an `NgModuleRef` created via `createNgModule` using an
  18150. // NgModule outside of a module tree). Instead, we always use `ViewContainerRef`'s parent
  18151. // injector, which is normally connected to the DI tree, which includes module injector
  18152. // subtree.
  18153. const _injector = isComponentFactory ? contextInjector : this.parentInjector;
  18154. // DO NOT REFACTOR. The code here used to have a `injector.get(NgModuleRef, null) ||
  18155. // undefined` expression which seems to cause internal google apps to fail. This is documented
  18156. // in the following internal bug issue: go/b/142967802
  18157. const result = _injector.get(EnvironmentInjector, null);
  18158. if (result) {
  18159. environmentInjector = result;
  18160. }
  18161. }
  18162. const componentDef = getComponentDef(componentFactory.componentType ?? {});
  18163. const dehydratedView = findMatchingDehydratedView(this._lContainer, componentDef?.id ?? null);
  18164. const rNode = dehydratedView?.firstChild ?? null;
  18165. const componentRef = componentFactory.create(contextInjector, projectableNodes, rNode, environmentInjector);
  18166. this.insertImpl(componentRef.hostView, index, shouldAddViewToDom(this._hostTNode, dehydratedView));
  18167. return componentRef;
  18168. }
  18169. insert(viewRef, index) {
  18170. return this.insertImpl(viewRef, index, true);
  18171. }
  18172. insertImpl(viewRef, index, addToDOM) {
  18173. const lView = viewRef._lView;
  18174. if (ngDevMode && viewRef.destroyed) {
  18175. throw new Error('Cannot insert a destroyed View in a ViewContainer!');
  18176. }
  18177. if (viewAttachedToContainer(lView)) {
  18178. // If view is already attached, detach it first so we clean up references appropriately.
  18179. const prevIdx = this.indexOf(viewRef);
  18180. // A view might be attached either to this or a different container. The `prevIdx` for
  18181. // those cases will be:
  18182. // equal to -1 for views attached to this ViewContainerRef
  18183. // >= 0 for views attached to a different ViewContainerRef
  18184. if (prevIdx !== -1) {
  18185. this.detach(prevIdx);
  18186. }
  18187. else {
  18188. const prevLContainer = lView[PARENT];
  18189. ngDevMode &&
  18190. assertEqual(isLContainer(prevLContainer), true, 'An attached view should have its PARENT point to a container.');
  18191. // We need to re-create a R3ViewContainerRef instance since those are not stored on
  18192. // LView (nor anywhere else).
  18193. const prevVCRef = new R3ViewContainerRef(prevLContainer, prevLContainer[T_HOST], prevLContainer[PARENT]);
  18194. prevVCRef.detach(prevVCRef.indexOf(viewRef));
  18195. }
  18196. }
  18197. // Logical operation of adding `LView` to `LContainer`
  18198. const adjustedIdx = this._adjustIndex(index);
  18199. const lContainer = this._lContainer;
  18200. addLViewToLContainer(lContainer, lView, adjustedIdx, addToDOM);
  18201. viewRef.attachToViewContainerRef();
  18202. addToArray(getOrCreateViewRefs(lContainer), adjustedIdx, viewRef);
  18203. return viewRef;
  18204. }
  18205. move(viewRef, newIndex) {
  18206. if (ngDevMode && viewRef.destroyed) {
  18207. throw new Error('Cannot move a destroyed View in a ViewContainer!');
  18208. }
  18209. return this.insert(viewRef, newIndex);
  18210. }
  18211. indexOf(viewRef) {
  18212. const viewRefsArr = getViewRefs(this._lContainer);
  18213. return viewRefsArr !== null ? viewRefsArr.indexOf(viewRef) : -1;
  18214. }
  18215. remove(index) {
  18216. const adjustedIdx = this._adjustIndex(index, -1);
  18217. const detachedView = detachView(this._lContainer, adjustedIdx);
  18218. if (detachedView) {
  18219. // Before destroying the view, remove it from the container's array of `ViewRef`s.
  18220. // This ensures the view container length is updated before calling
  18221. // `destroyLView`, which could recursively call view container methods that
  18222. // rely on an accurate container length.
  18223. // (e.g. a method on this view container being called by a child directive's OnDestroy
  18224. // lifecycle hook)
  18225. removeFromArray(getOrCreateViewRefs(this._lContainer), adjustedIdx);
  18226. destroyLView(detachedView[TVIEW], detachedView);
  18227. }
  18228. }
  18229. detach(index) {
  18230. const adjustedIdx = this._adjustIndex(index, -1);
  18231. const view = detachView(this._lContainer, adjustedIdx);
  18232. const wasDetached = view && removeFromArray(getOrCreateViewRefs(this._lContainer), adjustedIdx) != null;
  18233. return wasDetached ? new ViewRef$1(view) : null;
  18234. }
  18235. _adjustIndex(index, shift = 0) {
  18236. if (index == null) {
  18237. return this.length + shift;
  18238. }
  18239. if (ngDevMode) {
  18240. assertGreaterThan(index, -1, `ViewRef index must be positive, got ${index}`);
  18241. // +1 because it's legal to insert at the end.
  18242. assertLessThan(index, this.length + 1 + shift, 'index');
  18243. }
  18244. return index;
  18245. }
  18246. };
  18247. function getViewRefs(lContainer) {
  18248. return lContainer[VIEW_REFS];
  18249. }
  18250. function getOrCreateViewRefs(lContainer) {
  18251. return (lContainer[VIEW_REFS] || (lContainer[VIEW_REFS] = []));
  18252. }
  18253. /**
  18254. * Creates a ViewContainerRef and stores it on the injector.
  18255. *
  18256. * @param hostTNode The node that is requesting a ViewContainerRef
  18257. * @param hostLView The view to which the node belongs
  18258. * @returns The ViewContainerRef instance to use
  18259. */
  18260. function createContainerRef(hostTNode, hostLView) {
  18261. ngDevMode && assertTNodeType(hostTNode, 12 /* TNodeType.AnyContainer */ | 3 /* TNodeType.AnyRNode */);
  18262. let lContainer;
  18263. const slotValue = hostLView[hostTNode.index];
  18264. if (isLContainer(slotValue)) {
  18265. // If the host is a container, we don't need to create a new LContainer
  18266. lContainer = slotValue;
  18267. }
  18268. else {
  18269. // An LContainer anchor can not be `null`, but we set it here temporarily
  18270. // and update to the actual value later in this function (see
  18271. // `_locateOrCreateAnchorNode`).
  18272. lContainer = createLContainer(slotValue, hostLView, null, hostTNode);
  18273. hostLView[hostTNode.index] = lContainer;
  18274. addToEndOfViewTree(hostLView, lContainer);
  18275. }
  18276. _locateOrCreateAnchorNode(lContainer, hostLView, hostTNode, slotValue);
  18277. return new R3ViewContainerRef(lContainer, hostTNode, hostLView);
  18278. }
  18279. /**
  18280. * Creates and inserts a comment node that acts as an anchor for a view container.
  18281. *
  18282. * If the host is a regular element, we have to insert a comment node manually which will
  18283. * be used as an anchor when inserting elements. In this specific case we use low-level DOM
  18284. * manipulation to insert it.
  18285. */
  18286. function insertAnchorNode(hostLView, hostTNode) {
  18287. const renderer = hostLView[RENDERER];
  18288. ngDevMode && ngDevMode.rendererCreateComment++;
  18289. const commentNode = renderer.createComment(ngDevMode ? 'container' : '');
  18290. const hostNative = getNativeByTNode(hostTNode, hostLView);
  18291. const parentOfHostNative = renderer.parentNode(hostNative);
  18292. nativeInsertBefore(renderer, parentOfHostNative, commentNode, renderer.nextSibling(hostNative), false);
  18293. return commentNode;
  18294. }
  18295. let _locateOrCreateAnchorNode = createAnchorNode;
  18296. let _populateDehydratedViewsInLContainer = () => false; // noop by default
  18297. /**
  18298. * Looks up dehydrated views that belong to a given LContainer and populates
  18299. * this information into the `LContainer[DEHYDRATED_VIEWS]` slot. When running
  18300. * in client-only mode, this function is a noop.
  18301. *
  18302. * @param lContainer LContainer that should be populated.
  18303. * @param tNode Corresponding TNode.
  18304. * @param hostLView LView that hosts LContainer.
  18305. * @returns a boolean flag that indicates whether a populating operation
  18306. * was successful. The operation might be unsuccessful in case is has completed
  18307. * previously, we are rendering in client-only mode or this content is located
  18308. * in a skip hydration section.
  18309. */
  18310. function populateDehydratedViewsInLContainer(lContainer, tNode, hostLView) {
  18311. return _populateDehydratedViewsInLContainer(lContainer, tNode, hostLView);
  18312. }
  18313. /**
  18314. * Regular creation mode: an anchor is created and
  18315. * assigned to the `lContainer[NATIVE]` slot.
  18316. */
  18317. function createAnchorNode(lContainer, hostLView, hostTNode, slotValue) {
  18318. // We already have a native element (anchor) set, return.
  18319. if (lContainer[NATIVE])
  18320. return;
  18321. let commentNode;
  18322. // If the host is an element container, the native host element is guaranteed to be a
  18323. // comment and we can reuse that comment as anchor element for the new LContainer.
  18324. // The comment node in question is already part of the DOM structure so we don't need to append
  18325. // it again.
  18326. if (hostTNode.type & 8 /* TNodeType.ElementContainer */) {
  18327. commentNode = unwrapRNode(slotValue);
  18328. }
  18329. else {
  18330. commentNode = insertAnchorNode(hostLView, hostTNode);
  18331. }
  18332. lContainer[NATIVE] = commentNode;
  18333. }
  18334. /**
  18335. * Hydration logic that looks up all dehydrated views in this container
  18336. * and puts them into `lContainer[DEHYDRATED_VIEWS]` slot.
  18337. *
  18338. * @returns a boolean flag that indicates whether a populating operation
  18339. * was successful. The operation might be unsuccessful in case is has completed
  18340. * previously, we are rendering in client-only mode or this content is located
  18341. * in a skip hydration section.
  18342. */
  18343. function populateDehydratedViewsInLContainerImpl(lContainer, tNode, hostLView) {
  18344. // We already have a native element (anchor) set and the process
  18345. // of finding dehydrated views happened (so the `lContainer[DEHYDRATED_VIEWS]`
  18346. // is not null), exit early.
  18347. if (lContainer[NATIVE] && lContainer[DEHYDRATED_VIEWS]) {
  18348. return true;
  18349. }
  18350. const hydrationInfo = hostLView[HYDRATION];
  18351. const noOffsetIndex = tNode.index - HEADER_OFFSET;
  18352. const isNodeCreationMode = !hydrationInfo ||
  18353. isInSkipHydrationBlock(tNode) ||
  18354. isDisconnectedNode$1(hydrationInfo, noOffsetIndex);
  18355. // Regular creation mode.
  18356. if (isNodeCreationMode) {
  18357. return false;
  18358. }
  18359. // Hydration mode, looking up an anchor node and dehydrated views in DOM.
  18360. const currentRNode = getSegmentHead(hydrationInfo, noOffsetIndex);
  18361. const serializedViews = hydrationInfo.data[CONTAINERS]?.[noOffsetIndex];
  18362. ngDevMode &&
  18363. assertDefined(serializedViews, 'Unexpected state: no hydration info available for a given TNode, ' +
  18364. 'which represents a view container.');
  18365. const [commentNode, dehydratedViews] = locateDehydratedViewsInContainer(currentRNode, serializedViews);
  18366. if (ngDevMode) {
  18367. validateMatchingNode(commentNode, Node.COMMENT_NODE, null, hostLView, tNode, true);
  18368. // Do not throw in case this node is already claimed (thus `false` as a second
  18369. // argument). If this container is created based on an `<ng-template>`, the comment
  18370. // node would be already claimed from the `template` instruction. If an element acts
  18371. // as an anchor (e.g. <div #vcRef>), a separate comment node would be created/located,
  18372. // so we need to claim it here.
  18373. markRNodeAsClaimedByHydration(commentNode, false);
  18374. }
  18375. lContainer[NATIVE] = commentNode;
  18376. lContainer[DEHYDRATED_VIEWS] = dehydratedViews;
  18377. return true;
  18378. }
  18379. function locateOrCreateAnchorNode(lContainer, hostLView, hostTNode, slotValue) {
  18380. if (!_populateDehydratedViewsInLContainer(lContainer, hostTNode, hostLView)) {
  18381. // Populating dehydrated views operation returned `false`, which indicates
  18382. // that the logic was running in client-only mode, this an anchor comment
  18383. // node should be created for this container.
  18384. createAnchorNode(lContainer, hostLView, hostTNode, slotValue);
  18385. }
  18386. }
  18387. function enableLocateOrCreateContainerRefImpl() {
  18388. _locateOrCreateAnchorNode = locateOrCreateAnchorNode;
  18389. _populateDehydratedViewsInLContainer = populateDehydratedViewsInLContainerImpl;
  18390. }
  18391. class LQuery_ {
  18392. queryList;
  18393. matches = null;
  18394. constructor(queryList) {
  18395. this.queryList = queryList;
  18396. }
  18397. clone() {
  18398. return new LQuery_(this.queryList);
  18399. }
  18400. setDirty() {
  18401. this.queryList.setDirty();
  18402. }
  18403. }
  18404. class LQueries_ {
  18405. queries;
  18406. constructor(queries = []) {
  18407. this.queries = queries;
  18408. }
  18409. createEmbeddedView(tView) {
  18410. const tQueries = tView.queries;
  18411. if (tQueries !== null) {
  18412. const noOfInheritedQueries = tView.contentQueries !== null ? tView.contentQueries[0] : tQueries.length;
  18413. const viewLQueries = [];
  18414. // An embedded view has queries propagated from a declaration view at the beginning of the
  18415. // TQueries collection and up until a first content query declared in the embedded view. Only
  18416. // propagated LQueries are created at this point (LQuery corresponding to declared content
  18417. // queries will be instantiated from the content query instructions for each directive).
  18418. for (let i = 0; i < noOfInheritedQueries; i++) {
  18419. const tQuery = tQueries.getByIndex(i);
  18420. const parentLQuery = this.queries[tQuery.indexInDeclarationView];
  18421. viewLQueries.push(parentLQuery.clone());
  18422. }
  18423. return new LQueries_(viewLQueries);
  18424. }
  18425. return null;
  18426. }
  18427. insertView(tView) {
  18428. this.dirtyQueriesWithMatches(tView);
  18429. }
  18430. detachView(tView) {
  18431. this.dirtyQueriesWithMatches(tView);
  18432. }
  18433. finishViewCreation(tView) {
  18434. this.dirtyQueriesWithMatches(tView);
  18435. }
  18436. dirtyQueriesWithMatches(tView) {
  18437. for (let i = 0; i < this.queries.length; i++) {
  18438. if (getTQuery(tView, i).matches !== null) {
  18439. this.queries[i].setDirty();
  18440. }
  18441. }
  18442. }
  18443. }
  18444. class TQueryMetadata_ {
  18445. flags;
  18446. read;
  18447. predicate;
  18448. constructor(predicate, flags, read = null) {
  18449. this.flags = flags;
  18450. this.read = read;
  18451. // Compiler might not be able to pre-optimize and split multiple selectors.
  18452. if (typeof predicate === 'string') {
  18453. this.predicate = splitQueryMultiSelectors(predicate);
  18454. }
  18455. else {
  18456. this.predicate = predicate;
  18457. }
  18458. }
  18459. }
  18460. class TQueries_ {
  18461. queries;
  18462. constructor(queries = []) {
  18463. this.queries = queries;
  18464. }
  18465. elementStart(tView, tNode) {
  18466. ngDevMode &&
  18467. assertFirstCreatePass(tView, 'Queries should collect results on the first template pass only');
  18468. for (let i = 0; i < this.queries.length; i++) {
  18469. this.queries[i].elementStart(tView, tNode);
  18470. }
  18471. }
  18472. elementEnd(tNode) {
  18473. for (let i = 0; i < this.queries.length; i++) {
  18474. this.queries[i].elementEnd(tNode);
  18475. }
  18476. }
  18477. embeddedTView(tNode) {
  18478. let queriesForTemplateRef = null;
  18479. for (let i = 0; i < this.length; i++) {
  18480. const childQueryIndex = queriesForTemplateRef !== null ? queriesForTemplateRef.length : 0;
  18481. const tqueryClone = this.getByIndex(i).embeddedTView(tNode, childQueryIndex);
  18482. if (tqueryClone) {
  18483. tqueryClone.indexInDeclarationView = i;
  18484. if (queriesForTemplateRef !== null) {
  18485. queriesForTemplateRef.push(tqueryClone);
  18486. }
  18487. else {
  18488. queriesForTemplateRef = [tqueryClone];
  18489. }
  18490. }
  18491. }
  18492. return queriesForTemplateRef !== null ? new TQueries_(queriesForTemplateRef) : null;
  18493. }
  18494. template(tView, tNode) {
  18495. ngDevMode &&
  18496. assertFirstCreatePass(tView, 'Queries should collect results on the first template pass only');
  18497. for (let i = 0; i < this.queries.length; i++) {
  18498. this.queries[i].template(tView, tNode);
  18499. }
  18500. }
  18501. getByIndex(index) {
  18502. ngDevMode && assertIndexInRange(this.queries, index);
  18503. return this.queries[index];
  18504. }
  18505. get length() {
  18506. return this.queries.length;
  18507. }
  18508. track(tquery) {
  18509. this.queries.push(tquery);
  18510. }
  18511. }
  18512. class TQuery_ {
  18513. metadata;
  18514. matches = null;
  18515. indexInDeclarationView = -1;
  18516. crossesNgTemplate = false;
  18517. /**
  18518. * A node index on which a query was declared (-1 for view queries and ones inherited from the
  18519. * declaration template). We use this index (alongside with _appliesToNextNode flag) to know
  18520. * when to apply content queries to elements in a template.
  18521. */
  18522. _declarationNodeIndex;
  18523. /**
  18524. * A flag indicating if a given query still applies to nodes it is crossing. We use this flag
  18525. * (alongside with _declarationNodeIndex) to know when to stop applying content queries to
  18526. * elements in a template.
  18527. */
  18528. _appliesToNextNode = true;
  18529. constructor(metadata, nodeIndex = -1) {
  18530. this.metadata = metadata;
  18531. this._declarationNodeIndex = nodeIndex;
  18532. }
  18533. elementStart(tView, tNode) {
  18534. if (this.isApplyingToNode(tNode)) {
  18535. this.matchTNode(tView, tNode);
  18536. }
  18537. }
  18538. elementEnd(tNode) {
  18539. if (this._declarationNodeIndex === tNode.index) {
  18540. this._appliesToNextNode = false;
  18541. }
  18542. }
  18543. template(tView, tNode) {
  18544. this.elementStart(tView, tNode);
  18545. }
  18546. embeddedTView(tNode, childQueryIndex) {
  18547. if (this.isApplyingToNode(tNode)) {
  18548. this.crossesNgTemplate = true;
  18549. // A marker indicating a `<ng-template>` element (a placeholder for query results from
  18550. // embedded views created based on this `<ng-template>`).
  18551. this.addMatch(-tNode.index, childQueryIndex);
  18552. return new TQuery_(this.metadata);
  18553. }
  18554. return null;
  18555. }
  18556. isApplyingToNode(tNode) {
  18557. if (this._appliesToNextNode &&
  18558. (this.metadata.flags & 1 /* QueryFlags.descendants */) !== 1 /* QueryFlags.descendants */) {
  18559. const declarationNodeIdx = this._declarationNodeIndex;
  18560. let parent = tNode.parent;
  18561. // Determine if a given TNode is a "direct" child of a node on which a content query was
  18562. // declared (only direct children of query's host node can match with the descendants: false
  18563. // option). There are 3 main use-case / conditions to consider here:
  18564. // - <needs-target><i #target></i></needs-target>: here <i #target> parent node is a query
  18565. // host node;
  18566. // - <needs-target><ng-template [ngIf]="true"><i #target></i></ng-template></needs-target>:
  18567. // here <i #target> parent node is null;
  18568. // - <needs-target><ng-container><i #target></i></ng-container></needs-target>: here we need
  18569. // to go past `<ng-container>` to determine <i #target> parent node (but we shouldn't traverse
  18570. // up past the query's host node!).
  18571. while (parent !== null &&
  18572. parent.type & 8 /* TNodeType.ElementContainer */ &&
  18573. parent.index !== declarationNodeIdx) {
  18574. parent = parent.parent;
  18575. }
  18576. return declarationNodeIdx === (parent !== null ? parent.index : -1);
  18577. }
  18578. return this._appliesToNextNode;
  18579. }
  18580. matchTNode(tView, tNode) {
  18581. const predicate = this.metadata.predicate;
  18582. if (Array.isArray(predicate)) {
  18583. for (let i = 0; i < predicate.length; i++) {
  18584. const name = predicate[i];
  18585. this.matchTNodeWithReadOption(tView, tNode, getIdxOfMatchingSelector(tNode, name));
  18586. // Also try matching the name to a provider since strings can be used as DI tokens too.
  18587. this.matchTNodeWithReadOption(tView, tNode, locateDirectiveOrProvider(tNode, tView, name, false, false));
  18588. }
  18589. }
  18590. else {
  18591. if (predicate === TemplateRef) {
  18592. if (tNode.type & 4 /* TNodeType.Container */) {
  18593. this.matchTNodeWithReadOption(tView, tNode, -1);
  18594. }
  18595. }
  18596. else {
  18597. this.matchTNodeWithReadOption(tView, tNode, locateDirectiveOrProvider(tNode, tView, predicate, false, false));
  18598. }
  18599. }
  18600. }
  18601. matchTNodeWithReadOption(tView, tNode, nodeMatchIdx) {
  18602. if (nodeMatchIdx !== null) {
  18603. const read = this.metadata.read;
  18604. if (read !== null) {
  18605. if (read === ElementRef ||
  18606. read === ViewContainerRef ||
  18607. (read === TemplateRef && tNode.type & 4 /* TNodeType.Container */)) {
  18608. this.addMatch(tNode.index, -2);
  18609. }
  18610. else {
  18611. const directiveOrProviderIdx = locateDirectiveOrProvider(tNode, tView, read, false, false);
  18612. if (directiveOrProviderIdx !== null) {
  18613. this.addMatch(tNode.index, directiveOrProviderIdx);
  18614. }
  18615. }
  18616. }
  18617. else {
  18618. this.addMatch(tNode.index, nodeMatchIdx);
  18619. }
  18620. }
  18621. }
  18622. addMatch(tNodeIdx, matchIdx) {
  18623. if (this.matches === null) {
  18624. this.matches = [tNodeIdx, matchIdx];
  18625. }
  18626. else {
  18627. this.matches.push(tNodeIdx, matchIdx);
  18628. }
  18629. }
  18630. }
  18631. /**
  18632. * Iterates over local names for a given node and returns directive index
  18633. * (or -1 if a local name points to an element).
  18634. *
  18635. * @param tNode static data of a node to check
  18636. * @param selector selector to match
  18637. * @returns directive index, -1 or null if a selector didn't match any of the local names
  18638. */
  18639. function getIdxOfMatchingSelector(tNode, selector) {
  18640. const localNames = tNode.localNames;
  18641. if (localNames !== null) {
  18642. for (let i = 0; i < localNames.length; i += 2) {
  18643. if (localNames[i] === selector) {
  18644. return localNames[i + 1];
  18645. }
  18646. }
  18647. }
  18648. return null;
  18649. }
  18650. function createResultByTNodeType(tNode, currentView) {
  18651. if (tNode.type & (3 /* TNodeType.AnyRNode */ | 8 /* TNodeType.ElementContainer */)) {
  18652. return createElementRef(tNode, currentView);
  18653. }
  18654. else if (tNode.type & 4 /* TNodeType.Container */) {
  18655. return createTemplateRef(tNode, currentView);
  18656. }
  18657. return null;
  18658. }
  18659. function createResultForNode(lView, tNode, matchingIdx, read) {
  18660. if (matchingIdx === -1) {
  18661. // if read token and / or strategy is not specified, detect it using appropriate tNode type
  18662. return createResultByTNodeType(tNode, lView);
  18663. }
  18664. else if (matchingIdx === -2) {
  18665. // read a special token from a node injector
  18666. return createSpecialToken(lView, tNode, read);
  18667. }
  18668. else {
  18669. // read a token
  18670. return getNodeInjectable(lView, lView[TVIEW], matchingIdx, tNode);
  18671. }
  18672. }
  18673. function createSpecialToken(lView, tNode, read) {
  18674. if (read === ElementRef) {
  18675. return createElementRef(tNode, lView);
  18676. }
  18677. else if (read === TemplateRef) {
  18678. return createTemplateRef(tNode, lView);
  18679. }
  18680. else if (read === ViewContainerRef) {
  18681. ngDevMode && assertTNodeType(tNode, 3 /* TNodeType.AnyRNode */ | 12 /* TNodeType.AnyContainer */);
  18682. return createContainerRef(tNode, lView);
  18683. }
  18684. else {
  18685. ngDevMode &&
  18686. throwError(`Special token to read should be one of ElementRef, TemplateRef or ViewContainerRef but got ${stringify(read)}.`);
  18687. }
  18688. }
  18689. /**
  18690. * A helper function that creates query results for a given view. This function is meant to do the
  18691. * processing once and only once for a given view instance (a set of results for a given view
  18692. * doesn't change).
  18693. */
  18694. function materializeViewResults(tView, lView, tQuery, queryIndex) {
  18695. const lQuery = lView[QUERIES].queries[queryIndex];
  18696. if (lQuery.matches === null) {
  18697. const tViewData = tView.data;
  18698. const tQueryMatches = tQuery.matches;
  18699. const result = [];
  18700. for (let i = 0; tQueryMatches !== null && i < tQueryMatches.length; i += 2) {
  18701. const matchedNodeIdx = tQueryMatches[i];
  18702. if (matchedNodeIdx < 0) {
  18703. // we at the <ng-template> marker which might have results in views created based on this
  18704. // <ng-template> - those results will be in separate views though, so here we just leave
  18705. // null as a placeholder
  18706. result.push(null);
  18707. }
  18708. else {
  18709. ngDevMode && assertIndexInRange(tViewData, matchedNodeIdx);
  18710. const tNode = tViewData[matchedNodeIdx];
  18711. result.push(createResultForNode(lView, tNode, tQueryMatches[i + 1], tQuery.metadata.read));
  18712. }
  18713. }
  18714. lQuery.matches = result;
  18715. }
  18716. return lQuery.matches;
  18717. }
  18718. /**
  18719. * A helper function that collects (already materialized) query results from a tree of views,
  18720. * starting with a provided LView.
  18721. */
  18722. function collectQueryResults(tView, lView, queryIndex, result) {
  18723. const tQuery = tView.queries.getByIndex(queryIndex);
  18724. const tQueryMatches = tQuery.matches;
  18725. if (tQueryMatches !== null) {
  18726. const lViewResults = materializeViewResults(tView, lView, tQuery, queryIndex);
  18727. for (let i = 0; i < tQueryMatches.length; i += 2) {
  18728. const tNodeIdx = tQueryMatches[i];
  18729. if (tNodeIdx > 0) {
  18730. result.push(lViewResults[i / 2]);
  18731. }
  18732. else {
  18733. const childQueryIndex = tQueryMatches[i + 1];
  18734. const declarationLContainer = lView[-tNodeIdx];
  18735. ngDevMode && assertLContainer(declarationLContainer);
  18736. // collect matches for views inserted in this container
  18737. for (let i = CONTAINER_HEADER_OFFSET; i < declarationLContainer.length; i++) {
  18738. const embeddedLView = declarationLContainer[i];
  18739. if (embeddedLView[DECLARATION_LCONTAINER] === embeddedLView[PARENT]) {
  18740. collectQueryResults(embeddedLView[TVIEW], embeddedLView, childQueryIndex, result);
  18741. }
  18742. }
  18743. // collect matches for views created from this declaration container and inserted into
  18744. // different containers
  18745. if (declarationLContainer[MOVED_VIEWS] !== null) {
  18746. const embeddedLViews = declarationLContainer[MOVED_VIEWS];
  18747. for (let i = 0; i < embeddedLViews.length; i++) {
  18748. const embeddedLView = embeddedLViews[i];
  18749. collectQueryResults(embeddedLView[TVIEW], embeddedLView, childQueryIndex, result);
  18750. }
  18751. }
  18752. }
  18753. }
  18754. }
  18755. return result;
  18756. }
  18757. function loadQueryInternal(lView, queryIndex) {
  18758. ngDevMode &&
  18759. assertDefined(lView[QUERIES], 'LQueries should be defined when trying to load a query');
  18760. ngDevMode && assertIndexInRange(lView[QUERIES].queries, queryIndex);
  18761. return lView[QUERIES].queries[queryIndex].queryList;
  18762. }
  18763. /**
  18764. * Creates a new instance of LQuery and returns its index in the collection of LQuery objects.
  18765. *
  18766. * @returns index in the collection of LQuery objects
  18767. */
  18768. function createLQuery(tView, lView, flags) {
  18769. const queryList = new QueryList((flags & 4 /* QueryFlags.emitDistinctChangesOnly */) === 4 /* QueryFlags.emitDistinctChangesOnly */);
  18770. storeCleanupWithContext(tView, lView, queryList, queryList.destroy);
  18771. const lQueries = (lView[QUERIES] ??= new LQueries_()).queries;
  18772. return lQueries.push(new LQuery_(queryList)) - 1;
  18773. }
  18774. function createViewQuery(predicate, flags, read) {
  18775. ngDevMode && assertNumber(flags, 'Expecting flags');
  18776. const tView = getTView();
  18777. if (tView.firstCreatePass) {
  18778. createTQuery(tView, new TQueryMetadata_(predicate, flags, read), -1);
  18779. if ((flags & 2 /* QueryFlags.isStatic */) === 2 /* QueryFlags.isStatic */) {
  18780. tView.staticViewQueries = true;
  18781. }
  18782. }
  18783. return createLQuery(tView, getLView(), flags);
  18784. }
  18785. function createContentQuery(directiveIndex, predicate, flags, read) {
  18786. ngDevMode && assertNumber(flags, 'Expecting flags');
  18787. const tView = getTView();
  18788. if (tView.firstCreatePass) {
  18789. const tNode = getCurrentTNode();
  18790. createTQuery(tView, new TQueryMetadata_(predicate, flags, read), tNode.index);
  18791. saveContentQueryAndDirectiveIndex(tView, directiveIndex);
  18792. if ((flags & 2 /* QueryFlags.isStatic */) === 2 /* QueryFlags.isStatic */) {
  18793. tView.staticContentQueries = true;
  18794. }
  18795. }
  18796. return createLQuery(tView, getLView(), flags);
  18797. }
  18798. /** Splits multiple selectors in the locator. */
  18799. function splitQueryMultiSelectors(locator) {
  18800. return locator.split(',').map((s) => s.trim());
  18801. }
  18802. function createTQuery(tView, metadata, nodeIndex) {
  18803. if (tView.queries === null)
  18804. tView.queries = new TQueries_();
  18805. tView.queries.track(new TQuery_(metadata, nodeIndex));
  18806. }
  18807. function saveContentQueryAndDirectiveIndex(tView, directiveIndex) {
  18808. const tViewContentQueries = tView.contentQueries || (tView.contentQueries = []);
  18809. const lastSavedDirectiveIndex = tViewContentQueries.length
  18810. ? tViewContentQueries[tViewContentQueries.length - 1]
  18811. : -1;
  18812. if (directiveIndex !== lastSavedDirectiveIndex) {
  18813. tViewContentQueries.push(tView.queries.length - 1, directiveIndex);
  18814. }
  18815. }
  18816. function getTQuery(tView, index) {
  18817. ngDevMode && assertDefined(tView.queries, 'TQueries must be defined to retrieve a TQuery');
  18818. return tView.queries.getByIndex(index);
  18819. }
  18820. /**
  18821. * A helper function collecting results from all the views where a given query was active.
  18822. * @param lView
  18823. * @param queryIndex
  18824. */
  18825. function getQueryResults(lView, queryIndex) {
  18826. const tView = lView[TVIEW];
  18827. const tQuery = getTQuery(tView, queryIndex);
  18828. return tQuery.crossesNgTemplate
  18829. ? collectQueryResults(tView, lView, queryIndex, [])
  18830. : materializeViewResults(tView, lView, tQuery, queryIndex);
  18831. }
  18832. /**
  18833. * A signal factory function in charge of creating a new computed signal capturing query
  18834. * results. This centralized creation function is used by all types of queries (child / children,
  18835. * required / optional).
  18836. *
  18837. * @param firstOnly indicates if all or only the first result should be returned
  18838. * @param required indicates if at least one result is required
  18839. * @returns a read-only signal with query results
  18840. */
  18841. function createQuerySignalFn(firstOnly, required, opts) {
  18842. let node;
  18843. const signalFn = createComputed(() => {
  18844. // A dedicated signal that increments its value every time a query changes its dirty status. By
  18845. // using this signal we can implement a query as computed and avoid creation of a specialized
  18846. // reactive node type. Please note that a query gets marked dirty under the following
  18847. // circumstances:
  18848. // - a view (where a query is active) finished its first creation pass;
  18849. // - a new view is inserted / deleted and it impacts query results.
  18850. node._dirtyCounter();
  18851. const value = refreshSignalQuery(node, firstOnly);
  18852. if (required && value === undefined) {
  18853. throw new RuntimeError(-951 /* RuntimeErrorCode.REQUIRED_QUERY_NO_VALUE */, ngDevMode && 'Child query result is required but no value is available.');
  18854. }
  18855. return value;
  18856. });
  18857. node = signalFn[SIGNAL];
  18858. node._dirtyCounter = signal(0);
  18859. node._flatValue = undefined;
  18860. if (ngDevMode) {
  18861. signalFn.toString = () => `[Query Signal]`;
  18862. node.debugName = opts?.debugName;
  18863. }
  18864. return signalFn;
  18865. }
  18866. function createSingleResultOptionalQuerySignalFn(opts) {
  18867. return createQuerySignalFn(/* firstOnly */ true, /* required */ false, opts);
  18868. }
  18869. function createSingleResultRequiredQuerySignalFn(opts) {
  18870. return createQuerySignalFn(/* firstOnly */ true, /* required */ true, opts);
  18871. }
  18872. function createMultiResultQuerySignalFn(opts) {
  18873. return createQuerySignalFn(/* firstOnly */ false, /* required */ false, opts);
  18874. }
  18875. function bindQueryToSignal(target, queryIndex) {
  18876. const node = target[SIGNAL];
  18877. node._lView = getLView();
  18878. node._queryIndex = queryIndex;
  18879. node._queryList = loadQueryInternal(node._lView, queryIndex);
  18880. node._queryList.onDirty(() => node._dirtyCounter.update((v) => v + 1));
  18881. }
  18882. function refreshSignalQuery(node, firstOnly) {
  18883. const lView = node._lView;
  18884. const queryIndex = node._queryIndex;
  18885. // There are 2 conditions under which we want to return "empty" results instead of the ones
  18886. // collected by a query:
  18887. //
  18888. // 1) a given query wasn't created yet (this is a period of time between the directive creation
  18889. // and execution of the query creation function) - in this case a query doesn't exist yet and we
  18890. // don't have any results to return.
  18891. //
  18892. // 2) we are in the process of constructing a view (the first
  18893. // creation pass didn't finish) and a query might have partial results, but we don't want to
  18894. // return those - instead we do delay results collection until all nodes had a chance of matching
  18895. // and we can present consistent, "atomic" (on a view level) results.
  18896. if (lView === undefined || queryIndex === undefined || lView[FLAGS] & 4 /* LViewFlags.CreationMode */) {
  18897. return (firstOnly ? undefined : EMPTY_ARRAY);
  18898. }
  18899. const queryList = loadQueryInternal(lView, queryIndex);
  18900. const results = getQueryResults(lView, queryIndex);
  18901. queryList.reset(results, unwrapElementRef);
  18902. if (firstOnly) {
  18903. return queryList.first;
  18904. }
  18905. else {
  18906. // TODO: remove access to the private _changesDetected field by abstracting / removing usage of
  18907. // QueryList in the signal-based queries (perf follow-up)
  18908. const resultChanged = queryList._changesDetected;
  18909. if (resultChanged || node._flatValue === undefined) {
  18910. return (node._flatValue = queryList.toArray());
  18911. }
  18912. return node._flatValue;
  18913. }
  18914. }
  18915. function viewChildFn(locator, opts) {
  18916. ngDevMode && assertInInjectionContext(viewChild);
  18917. return createSingleResultOptionalQuerySignalFn(opts);
  18918. }
  18919. function viewChildRequiredFn(locator, opts) {
  18920. ngDevMode && assertInInjectionContext(viewChild);
  18921. return createSingleResultRequiredQuerySignalFn(opts);
  18922. }
  18923. /**
  18924. * Initializes a view child query.
  18925. *
  18926. * Consider using `viewChild.required` for queries that should always match.
  18927. *
  18928. * @usageNotes
  18929. * Create a child query in your component by declaring a
  18930. * class field and initializing it with the `viewChild()` function.
  18931. *
  18932. * ```angular-ts
  18933. * @Component({template: '<div #el></div><my-component #cmp />'})
  18934. * export class TestComponent {
  18935. * divEl = viewChild<ElementRef>('el'); // Signal<ElementRef|undefined>
  18936. * divElRequired = viewChild.required<ElementRef>('el'); // Signal<ElementRef>
  18937. * cmp = viewChild(MyComponent); // Signal<MyComponent|undefined>
  18938. * cmpRequired = viewChild.required(MyComponent); // Signal<MyComponent>
  18939. * }
  18940. * ```
  18941. *
  18942. * @publicAPI
  18943. * @initializerApiFunction
  18944. */
  18945. const viewChild = (() => {
  18946. // Note: This may be considered a side-effect, but nothing will depend on
  18947. // this assignment, unless this `viewChild` constant export is accessed. It's a
  18948. // self-contained side effect that is local to the user facing `viewChild` export.
  18949. viewChildFn.required = viewChildRequiredFn;
  18950. return viewChildFn;
  18951. })();
  18952. /**
  18953. * Initializes a view children query.
  18954. *
  18955. * Query results are represented as a signal of a read-only collection containing all matched
  18956. * elements.
  18957. *
  18958. * @usageNotes
  18959. * Create a children query in your component by declaring a
  18960. * class field and initializing it with the `viewChildren()` function.
  18961. *
  18962. * ```ts
  18963. * @Component({...})
  18964. * export class TestComponent {
  18965. * divEls = viewChildren<ElementRef>('el'); // Signal<ReadonlyArray<ElementRef>>
  18966. * }
  18967. * ```
  18968. *
  18969. * @initializerApiFunction
  18970. * @publicAPI
  18971. */
  18972. function viewChildren(locator, opts) {
  18973. ngDevMode && assertInInjectionContext(viewChildren);
  18974. return createMultiResultQuerySignalFn(opts);
  18975. }
  18976. function contentChildFn(locator, opts) {
  18977. ngDevMode && assertInInjectionContext(contentChild);
  18978. return createSingleResultOptionalQuerySignalFn(opts);
  18979. }
  18980. function contentChildRequiredFn(locator, opts) {
  18981. ngDevMode && assertInInjectionContext(contentChildren);
  18982. return createSingleResultRequiredQuerySignalFn(opts);
  18983. }
  18984. /**
  18985. * Initializes a content child query. Consider using `contentChild.required` for queries that should
  18986. * always match.
  18987. *
  18988. * @usageNotes
  18989. * Create a child query in your component by declaring a
  18990. * class field and initializing it with the `contentChild()` function.
  18991. *
  18992. * ```ts
  18993. * @Component({...})
  18994. * export class TestComponent {
  18995. * headerEl = contentChild<ElementRef>('h'); // Signal<ElementRef|undefined>
  18996. * headerElElRequired = contentChild.required<ElementRef>('h'); // Signal<ElementRef>
  18997. * header = contentChild(MyHeader); // Signal<MyHeader|undefined>
  18998. * headerRequired = contentChild.required(MyHeader); // Signal<MyHeader>
  18999. * }
  19000. * ```
  19001. *
  19002. * @initializerApiFunction
  19003. * @publicAPI
  19004. */
  19005. const contentChild = (() => {
  19006. // Note: This may be considered a side-effect, but nothing will depend on
  19007. // this assignment, unless this `viewChild` constant export is accessed. It's a
  19008. // self-contained side effect that is local to the user facing `viewChild` export.
  19009. contentChildFn.required = contentChildRequiredFn;
  19010. return contentChildFn;
  19011. })();
  19012. /**
  19013. * Initializes a content children query.
  19014. *
  19015. * Query results are represented as a signal of a read-only collection containing all matched
  19016. * elements.
  19017. *
  19018. * @usageNotes
  19019. * Create a children query in your component by declaring a
  19020. * class field and initializing it with the `contentChildren()` function.
  19021. *
  19022. * ```ts
  19023. * @Component({...})
  19024. * export class TestComponent {
  19025. * headerEl = contentChildren<ElementRef>('h'); // Signal<ReadonlyArray<ElementRef>>
  19026. * }
  19027. * ```
  19028. *
  19029. * @initializerApiFunction
  19030. * @publicAPI
  19031. */
  19032. function contentChildren(locator, opts) {
  19033. return createMultiResultQuerySignalFn(opts);
  19034. }
  19035. /**
  19036. * Creates a model signal.
  19037. *
  19038. * @param initialValue The initial value.
  19039. * Can be set to {@link REQUIRED_UNSET_VALUE} for required model signals.
  19040. * @param options Additional options for the model.
  19041. */
  19042. function createModelSignal(initialValue, opts) {
  19043. const node = Object.create(INPUT_SIGNAL_NODE);
  19044. const emitterRef = new OutputEmitterRef();
  19045. node.value = initialValue;
  19046. function getter() {
  19047. producerAccessed(node);
  19048. assertModelSet(node.value);
  19049. return node.value;
  19050. }
  19051. getter[SIGNAL] = node;
  19052. getter.asReadonly = signalAsReadonlyFn.bind(getter);
  19053. // TODO: Should we throw an error when updating a destroyed model?
  19054. getter.set = (newValue) => {
  19055. if (!node.equal(node.value, newValue)) {
  19056. signalSetFn(node, newValue);
  19057. emitterRef.emit(newValue);
  19058. }
  19059. };
  19060. getter.update = (updateFn) => {
  19061. assertModelSet(node.value);
  19062. getter.set(updateFn(node.value));
  19063. };
  19064. getter.subscribe = emitterRef.subscribe.bind(emitterRef);
  19065. getter.destroyRef = emitterRef.destroyRef;
  19066. if (ngDevMode) {
  19067. getter.toString = () => `[Model Signal: ${getter()}]`;
  19068. node.debugName = opts?.debugName;
  19069. }
  19070. return getter;
  19071. }
  19072. /** Asserts that a model's value is set. */
  19073. function assertModelSet(value) {
  19074. if (value === REQUIRED_UNSET_VALUE) {
  19075. throw new RuntimeError(952 /* RuntimeErrorCode.REQUIRED_MODEL_NO_VALUE */, ngDevMode && 'Model is required but no value is available yet.');
  19076. }
  19077. }
  19078. function modelFunction(initialValue, opts) {
  19079. ngDevMode && assertInInjectionContext(model);
  19080. return createModelSignal(initialValue, opts);
  19081. }
  19082. function modelRequiredFunction(opts) {
  19083. ngDevMode && assertInInjectionContext(model);
  19084. return createModelSignal(REQUIRED_UNSET_VALUE, opts);
  19085. }
  19086. /**
  19087. * `model` declares a writeable signal that is exposed as an input/output
  19088. * pair on the containing directive.
  19089. *
  19090. * The input name is taken either from the class member or from the `alias` option.
  19091. * The output name is generated by taking the input name and appending `Change`.
  19092. *
  19093. * @usageNotes
  19094. *
  19095. * To use `model()`, import the function from `@angular/core`.
  19096. *
  19097. * ```ts
  19098. * import {model} from '@angular/core`;
  19099. * ```
  19100. *
  19101. * Inside your component, introduce a new class member and initialize
  19102. * it with a call to `model` or `model.required`.
  19103. *
  19104. * ```ts
  19105. * @Directive({
  19106. * ...
  19107. * })
  19108. * export class MyDir {
  19109. * firstName = model<string>(); // ModelSignal<string|undefined>
  19110. * lastName = model.required<string>(); // ModelSignal<string>
  19111. * age = model(0); // ModelSignal<number>
  19112. * }
  19113. * ```
  19114. *
  19115. * Inside your component template, you can display the value of a `model`
  19116. * by calling the signal.
  19117. *
  19118. * ```html
  19119. * <span>{{firstName()}}</span>
  19120. * ```
  19121. *
  19122. * Updating the `model` is equivalent to updating a writable signal.
  19123. *
  19124. * ```ts
  19125. * updateName(newFirstName: string): void {
  19126. * this.firstName.set(newFirstName);
  19127. * }
  19128. * ```
  19129. *
  19130. * @publicAPI
  19131. * @initializerApiFunction
  19132. */
  19133. const model = (() => {
  19134. // Note: This may be considered a side-effect, but nothing will depend on
  19135. // this assignment, unless this `model` constant export is accessed. It's a
  19136. // self-contained side effect that is local to the user facing `model` export.
  19137. modelFunction.required = modelRequiredFunction;
  19138. return modelFunction;
  19139. })();
  19140. // Stores the default value of `emitDistinctChangesOnly` when the `emitDistinctChangesOnly` is not
  19141. // explicitly set.
  19142. const emitDistinctChangesOnlyDefaultValue = true;
  19143. /**
  19144. * Base class for query metadata.
  19145. *
  19146. * @see {@link ContentChildren}
  19147. * @see {@link ContentChild}
  19148. * @see {@link ViewChildren}
  19149. * @see {@link ViewChild}
  19150. *
  19151. * @publicApi
  19152. */
  19153. class Query {
  19154. }
  19155. /**
  19156. * ContentChildren decorator and metadata.
  19157. *
  19158. *
  19159. * @Annotation
  19160. * @publicApi
  19161. */
  19162. const ContentChildren = makePropDecorator('ContentChildren', (selector, opts = {}) => ({
  19163. selector,
  19164. first: false,
  19165. isViewQuery: false,
  19166. descendants: false,
  19167. emitDistinctChangesOnly: emitDistinctChangesOnlyDefaultValue,
  19168. ...opts,
  19169. }), Query);
  19170. /**
  19171. * ContentChild decorator and metadata.
  19172. *
  19173. *
  19174. * @Annotation
  19175. *
  19176. * @publicApi
  19177. */
  19178. const ContentChild = makePropDecorator('ContentChild', (selector, opts = {}) => ({
  19179. selector,
  19180. first: true,
  19181. isViewQuery: false,
  19182. descendants: true,
  19183. ...opts,
  19184. }), Query);
  19185. /**
  19186. * ViewChildren decorator and metadata.
  19187. *
  19188. * @Annotation
  19189. * @publicApi
  19190. */
  19191. const ViewChildren = makePropDecorator('ViewChildren', (selector, opts = {}) => ({
  19192. selector,
  19193. first: false,
  19194. isViewQuery: true,
  19195. descendants: true,
  19196. emitDistinctChangesOnly: emitDistinctChangesOnlyDefaultValue,
  19197. ...opts,
  19198. }), Query);
  19199. /**
  19200. * ViewChild decorator and metadata.
  19201. *
  19202. * @Annotation
  19203. * @publicApi
  19204. */
  19205. const ViewChild = makePropDecorator('ViewChild', (selector, opts) => ({
  19206. selector,
  19207. first: true,
  19208. isViewQuery: true,
  19209. descendants: true,
  19210. ...opts,
  19211. }), Query);
  19212. /**
  19213. * Used to resolve resource URLs on `@Component` when used with JIT compilation.
  19214. *
  19215. * Example:
  19216. * ```ts
  19217. * @Component({
  19218. * selector: 'my-comp',
  19219. * templateUrl: 'my-comp.html', // This requires asynchronous resolution
  19220. * })
  19221. * class MyComponent{
  19222. * }
  19223. *
  19224. * // Calling `renderComponent` will fail because `renderComponent` is a synchronous process
  19225. * // and `MyComponent`'s `@Component.templateUrl` needs to be resolved asynchronously.
  19226. *
  19227. * // Calling `resolveComponentResources()` will resolve `@Component.templateUrl` into
  19228. * // `@Component.template`, which allows `renderComponent` to proceed in a synchronous manner.
  19229. *
  19230. * // Use browser's `fetch()` function as the default resource resolution strategy.
  19231. * resolveComponentResources(fetch).then(() => {
  19232. * // After resolution all URLs have been converted into `template` strings.
  19233. * renderComponent(MyComponent);
  19234. * });
  19235. *
  19236. * ```
  19237. *
  19238. * NOTE: In AOT the resolution happens during compilation, and so there should be no need
  19239. * to call this method outside JIT mode.
  19240. *
  19241. * @param resourceResolver a function which is responsible for returning a `Promise` to the
  19242. * contents of the resolved URL. Browser's `fetch()` method is a good default implementation.
  19243. */
  19244. function resolveComponentResources(resourceResolver) {
  19245. // Store all promises which are fetching the resources.
  19246. const componentResolved = [];
  19247. // Cache so that we don't fetch the same resource more than once.
  19248. const urlMap = new Map();
  19249. function cachedResourceResolve(url) {
  19250. let promise = urlMap.get(url);
  19251. if (!promise) {
  19252. const resp = resourceResolver(url);
  19253. urlMap.set(url, (promise = resp.then(unwrapResponse)));
  19254. }
  19255. return promise;
  19256. }
  19257. componentResourceResolutionQueue.forEach((component, type) => {
  19258. const promises = [];
  19259. if (component.templateUrl) {
  19260. promises.push(cachedResourceResolve(component.templateUrl).then((template) => {
  19261. component.template = template;
  19262. }));
  19263. }
  19264. const styles = typeof component.styles === 'string' ? [component.styles] : component.styles || [];
  19265. component.styles = styles;
  19266. if (component.styleUrl && component.styleUrls?.length) {
  19267. throw new Error('@Component cannot define both `styleUrl` and `styleUrls`. ' +
  19268. 'Use `styleUrl` if the component has one stylesheet, or `styleUrls` if it has multiple');
  19269. }
  19270. else if (component.styleUrls?.length) {
  19271. const styleOffset = component.styles.length;
  19272. const styleUrls = component.styleUrls;
  19273. component.styleUrls.forEach((styleUrl, index) => {
  19274. styles.push(''); // pre-allocate array.
  19275. promises.push(cachedResourceResolve(styleUrl).then((style) => {
  19276. styles[styleOffset + index] = style;
  19277. styleUrls.splice(styleUrls.indexOf(styleUrl), 1);
  19278. if (styleUrls.length == 0) {
  19279. component.styleUrls = undefined;
  19280. }
  19281. }));
  19282. });
  19283. }
  19284. else if (component.styleUrl) {
  19285. promises.push(cachedResourceResolve(component.styleUrl).then((style) => {
  19286. styles.push(style);
  19287. component.styleUrl = undefined;
  19288. }));
  19289. }
  19290. const fullyResolved = Promise.all(promises).then(() => componentDefResolved(type));
  19291. componentResolved.push(fullyResolved);
  19292. });
  19293. clearResolutionOfComponentResourcesQueue();
  19294. return Promise.all(componentResolved).then(() => undefined);
  19295. }
  19296. let componentResourceResolutionQueue = new Map();
  19297. // Track when existing ɵcmp for a Type is waiting on resources.
  19298. const componentDefPendingResolution = new Set();
  19299. function maybeQueueResolutionOfComponentResources(type, metadata) {
  19300. if (componentNeedsResolution(metadata)) {
  19301. componentResourceResolutionQueue.set(type, metadata);
  19302. componentDefPendingResolution.add(type);
  19303. }
  19304. }
  19305. function isComponentDefPendingResolution(type) {
  19306. return componentDefPendingResolution.has(type);
  19307. }
  19308. function componentNeedsResolution(component) {
  19309. return !!((component.templateUrl && !component.hasOwnProperty('template')) ||
  19310. (component.styleUrls && component.styleUrls.length) ||
  19311. component.styleUrl);
  19312. }
  19313. function clearResolutionOfComponentResourcesQueue() {
  19314. const old = componentResourceResolutionQueue;
  19315. componentResourceResolutionQueue = new Map();
  19316. return old;
  19317. }
  19318. function restoreComponentResolutionQueue(queue) {
  19319. componentDefPendingResolution.clear();
  19320. queue.forEach((_, type) => componentDefPendingResolution.add(type));
  19321. componentResourceResolutionQueue = queue;
  19322. }
  19323. function isComponentResourceResolutionQueueEmpty() {
  19324. return componentResourceResolutionQueue.size === 0;
  19325. }
  19326. function unwrapResponse(response) {
  19327. return typeof response == 'string' ? response : response.text();
  19328. }
  19329. function componentDefResolved(type) {
  19330. componentDefPendingResolution.delete(type);
  19331. }
  19332. /**
  19333. * Map of module-id to the corresponding NgModule.
  19334. */
  19335. const modules = new Map();
  19336. /**
  19337. * Whether to check for duplicate NgModule registrations.
  19338. *
  19339. * This can be disabled for testing.
  19340. */
  19341. let checkForDuplicateNgModules = true;
  19342. function assertSameOrNotExisting(id, type, incoming) {
  19343. if (type && type !== incoming && checkForDuplicateNgModules) {
  19344. throw new Error(`Duplicate module registered for ${id} - ${stringify(type)} vs ${stringify(type.name)}`);
  19345. }
  19346. }
  19347. /**
  19348. * Adds the given NgModule type to Angular's NgModule registry.
  19349. *
  19350. * This is generated as a side-effect of NgModule compilation. Note that the `id` is passed in
  19351. * explicitly and not read from the NgModule definition. This is for two reasons: it avoids a
  19352. * megamorphic read, and in JIT there's a chicken-and-egg problem where the NgModule may not be
  19353. * fully resolved when it's registered.
  19354. *
  19355. * @codeGenApi
  19356. */
  19357. function registerNgModuleType(ngModuleType, id) {
  19358. const existing = modules.get(id) || null;
  19359. assertSameOrNotExisting(id, existing, ngModuleType);
  19360. modules.set(id, ngModuleType);
  19361. }
  19362. function getRegisteredNgModuleType(id) {
  19363. return modules.get(id);
  19364. }
  19365. /**
  19366. * Control whether the NgModule registration system enforces that each NgModule type registered has
  19367. * a unique id.
  19368. *
  19369. * This is useful for testing as the NgModule registry cannot be properly reset between tests with
  19370. * Angular's current API.
  19371. */
  19372. function setAllowDuplicateNgModuleIdsForTest(allowDuplicates) {
  19373. checkForDuplicateNgModules = !allowDuplicates;
  19374. }
  19375. /**
  19376. * Validation function invoked at runtime for each binding that might potentially
  19377. * represent a security-sensitive attribute of an <iframe>.
  19378. * See `IFRAME_SECURITY_SENSITIVE_ATTRS` in the
  19379. * `packages/compiler/src/schema/dom_security_schema.ts` script for the full list
  19380. * of such attributes.
  19381. *
  19382. * @codeGenApi
  19383. */
  19384. function ɵɵvalidateIframeAttribute(attrValue, tagName, attrName) {
  19385. const lView = getLView();
  19386. const tNode = getSelectedTNode();
  19387. const element = getNativeByTNode(tNode, lView);
  19388. // Restrict any dynamic bindings of security-sensitive attributes/properties
  19389. // on an <iframe> for security reasons.
  19390. if (tNode.type === 2 /* TNodeType.Element */ && tagName.toLowerCase() === 'iframe') {
  19391. const iframe = element;
  19392. // Unset previously applied `src` and `srcdoc` if we come across a situation when
  19393. // a security-sensitive attribute is set later via an attribute/property binding.
  19394. iframe.src = '';
  19395. iframe.srcdoc = trustedHTMLFromString('');
  19396. // Also remove the <iframe> from the document.
  19397. nativeRemoveNode(lView[RENDERER], iframe);
  19398. const errorMessage = ngDevMode &&
  19399. `Angular has detected that the \`${attrName}\` was applied ` +
  19400. `as a binding to an <iframe>${getTemplateLocationDetails(lView)}. ` +
  19401. `For security reasons, the \`${attrName}\` can be set on an <iframe> ` +
  19402. `as a static attribute only. \n` +
  19403. `To fix this, switch the \`${attrName}\` binding to a static attribute ` +
  19404. `in a template or in host bindings section.`;
  19405. throw new RuntimeError(-910 /* RuntimeErrorCode.UNSAFE_IFRAME_ATTRS */, errorMessage);
  19406. }
  19407. return attrValue;
  19408. }
  19409. /**
  19410. * Represents an instance of an `NgModule` created by an `NgModuleFactory`.
  19411. * Provides access to the `NgModule` instance and related objects.
  19412. *
  19413. * @publicApi
  19414. */
  19415. let NgModuleRef$1 = class NgModuleRef {
  19416. };
  19417. /**
  19418. * @publicApi
  19419. *
  19420. * @deprecated
  19421. * This class was mostly used as a part of ViewEngine-based JIT API and is no longer needed in Ivy
  19422. * JIT mode. Angular provides APIs that accept NgModule classes directly (such as
  19423. * [PlatformRef.bootstrapModule](api/core/PlatformRef#bootstrapModule) and
  19424. * [createNgModule](api/core/createNgModule)), consider switching to those APIs instead of
  19425. * using factory-based ones.
  19426. */
  19427. let NgModuleFactory$1 = class NgModuleFactory {
  19428. };
  19429. /**
  19430. * Returns a new NgModuleRef instance based on the NgModule class and parent injector provided.
  19431. *
  19432. * @param ngModule NgModule class.
  19433. * @param parentInjector Optional injector instance to use as a parent for the module injector. If
  19434. * not provided, `NullInjector` will be used instead.
  19435. * @returns NgModuleRef that represents an NgModule instance.
  19436. *
  19437. * @publicApi
  19438. */
  19439. function createNgModule(ngModule, parentInjector) {
  19440. return new NgModuleRef(ngModule, parentInjector ?? null, []);
  19441. }
  19442. /**
  19443. * The `createNgModule` function alias for backwards-compatibility.
  19444. * Please avoid using it directly and use `createNgModule` instead.
  19445. *
  19446. * @deprecated Use `createNgModule` instead.
  19447. */
  19448. const createNgModuleRef = createNgModule;
  19449. class NgModuleRef extends NgModuleRef$1 {
  19450. ngModuleType;
  19451. _parent;
  19452. // tslint:disable-next-line:require-internal-with-underscore
  19453. _bootstrapComponents = [];
  19454. _r3Injector;
  19455. instance;
  19456. destroyCbs = [];
  19457. // When bootstrapping a module we have a dependency graph that looks like this:
  19458. // ApplicationRef -> ComponentFactoryResolver -> NgModuleRef. The problem is that if the
  19459. // module being resolved tries to inject the ComponentFactoryResolver, it'll create a
  19460. // circular dependency which will result in a runtime error, because the injector doesn't
  19461. // exist yet. We work around the issue by creating the ComponentFactoryResolver ourselves
  19462. // and providing it, rather than letting the injector resolve it.
  19463. componentFactoryResolver = new ComponentFactoryResolver(this);
  19464. constructor(ngModuleType, _parent, additionalProviders, runInjectorInitializers = true) {
  19465. super();
  19466. this.ngModuleType = ngModuleType;
  19467. this._parent = _parent;
  19468. const ngModuleDef = getNgModuleDef(ngModuleType);
  19469. ngDevMode &&
  19470. assertDefined(ngModuleDef, `NgModule '${stringify(ngModuleType)}' is not a subtype of 'NgModuleType'.`);
  19471. this._bootstrapComponents = maybeUnwrapFn(ngModuleDef.bootstrap);
  19472. this._r3Injector = createInjectorWithoutInjectorInstances(ngModuleType, _parent, [
  19473. { provide: NgModuleRef$1, useValue: this },
  19474. {
  19475. provide: ComponentFactoryResolver$1,
  19476. useValue: this.componentFactoryResolver,
  19477. },
  19478. ...additionalProviders,
  19479. ], stringify(ngModuleType), new Set(['environment']));
  19480. // We need to resolve the injector types separately from the injector creation, because
  19481. // the module might be trying to use this ref in its constructor for DI which will cause a
  19482. // circular error that will eventually error out, because the injector isn't created yet.
  19483. if (runInjectorInitializers) {
  19484. this.resolveInjectorInitializers();
  19485. }
  19486. }
  19487. resolveInjectorInitializers() {
  19488. this._r3Injector.resolveInjectorInitializers();
  19489. this.instance = this._r3Injector.get(this.ngModuleType);
  19490. }
  19491. get injector() {
  19492. return this._r3Injector;
  19493. }
  19494. destroy() {
  19495. ngDevMode && assertDefined(this.destroyCbs, 'NgModule already destroyed');
  19496. const injector = this._r3Injector;
  19497. !injector.destroyed && injector.destroy();
  19498. this.destroyCbs.forEach((fn) => fn());
  19499. this.destroyCbs = null;
  19500. }
  19501. onDestroy(callback) {
  19502. ngDevMode && assertDefined(this.destroyCbs, 'NgModule already destroyed');
  19503. this.destroyCbs.push(callback);
  19504. }
  19505. }
  19506. class NgModuleFactory extends NgModuleFactory$1 {
  19507. moduleType;
  19508. constructor(moduleType) {
  19509. super();
  19510. this.moduleType = moduleType;
  19511. }
  19512. create(parentInjector) {
  19513. return new NgModuleRef(this.moduleType, parentInjector, []);
  19514. }
  19515. }
  19516. function createNgModuleRefWithProviders(moduleType, parentInjector, additionalProviders) {
  19517. return new NgModuleRef(moduleType, parentInjector, additionalProviders, false);
  19518. }
  19519. class EnvironmentNgModuleRefAdapter extends NgModuleRef$1 {
  19520. injector;
  19521. componentFactoryResolver = new ComponentFactoryResolver(this);
  19522. instance = null;
  19523. constructor(config) {
  19524. super();
  19525. const injector = new R3Injector([
  19526. ...config.providers,
  19527. { provide: NgModuleRef$1, useValue: this },
  19528. { provide: ComponentFactoryResolver$1, useValue: this.componentFactoryResolver },
  19529. ], config.parent || getNullInjector(), config.debugName, new Set(['environment']));
  19530. this.injector = injector;
  19531. if (config.runEnvironmentInitializers) {
  19532. injector.resolveInjectorInitializers();
  19533. }
  19534. }
  19535. destroy() {
  19536. this.injector.destroy();
  19537. }
  19538. onDestroy(callback) {
  19539. this.injector.onDestroy(callback);
  19540. }
  19541. }
  19542. /**
  19543. * Create a new environment injector.
  19544. *
  19545. * @param providers An array of providers.
  19546. * @param parent A parent environment injector.
  19547. * @param debugName An optional name for this injector instance, which will be used in error
  19548. * messages.
  19549. *
  19550. * @publicApi
  19551. */
  19552. function createEnvironmentInjector(providers, parent, debugName = null) {
  19553. const adapter = new EnvironmentNgModuleRefAdapter({
  19554. providers,
  19555. parent,
  19556. debugName,
  19557. runEnvironmentInitializers: true,
  19558. });
  19559. return adapter.injector;
  19560. }
  19561. /**
  19562. * A service used by the framework to create instances of standalone injectors. Those injectors are
  19563. * created on demand in case of dynamic component instantiation and contain ambient providers
  19564. * collected from the imports graph rooted at a given standalone component.
  19565. */
  19566. class StandaloneService {
  19567. _injector;
  19568. cachedInjectors = new Map();
  19569. constructor(_injector) {
  19570. this._injector = _injector;
  19571. }
  19572. getOrCreateStandaloneInjector(componentDef) {
  19573. if (!componentDef.standalone) {
  19574. return null;
  19575. }
  19576. if (!this.cachedInjectors.has(componentDef)) {
  19577. const providers = internalImportProvidersFrom(false, componentDef.type);
  19578. const standaloneInjector = providers.length > 0
  19579. ? createEnvironmentInjector([providers], this._injector, `Standalone[${componentDef.type.name}]`)
  19580. : null;
  19581. this.cachedInjectors.set(componentDef, standaloneInjector);
  19582. }
  19583. return this.cachedInjectors.get(componentDef);
  19584. }
  19585. ngOnDestroy() {
  19586. try {
  19587. for (const injector of this.cachedInjectors.values()) {
  19588. if (injector !== null) {
  19589. injector.destroy();
  19590. }
  19591. }
  19592. }
  19593. finally {
  19594. this.cachedInjectors.clear();
  19595. }
  19596. }
  19597. /** @nocollapse */
  19598. static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
  19599. token: StandaloneService,
  19600. providedIn: 'environment',
  19601. factory: () => new StandaloneService(ɵɵinject(EnvironmentInjector)),
  19602. });
  19603. }
  19604. /**
  19605. * Create a component definition object.
  19606. *
  19607. *
  19608. * # Example
  19609. * ```ts
  19610. * class MyComponent {
  19611. * // Generated by Angular Template Compiler
  19612. * // [Symbol] syntax will not be supported by TypeScript until v2.7
  19613. * static ɵcmp = defineComponent({
  19614. * ...
  19615. * });
  19616. * }
  19617. * ```
  19618. * @codeGenApi
  19619. */
  19620. function ɵɵdefineComponent(componentDefinition) {
  19621. return noSideEffects(() => {
  19622. // Initialize ngDevMode. This must be the first statement in ɵɵdefineComponent.
  19623. // See the `initNgDevMode` docstring for more information.
  19624. (typeof ngDevMode === 'undefined' || ngDevMode) && initNgDevMode();
  19625. const baseDef = getNgDirectiveDef(componentDefinition);
  19626. const def = {
  19627. ...baseDef,
  19628. decls: componentDefinition.decls,
  19629. vars: componentDefinition.vars,
  19630. template: componentDefinition.template,
  19631. consts: componentDefinition.consts || null,
  19632. ngContentSelectors: componentDefinition.ngContentSelectors,
  19633. onPush: componentDefinition.changeDetection === ChangeDetectionStrategy.OnPush,
  19634. directiveDefs: null, // assigned in noSideEffects
  19635. pipeDefs: null, // assigned in noSideEffects
  19636. dependencies: (baseDef.standalone && componentDefinition.dependencies) || null,
  19637. getStandaloneInjector: baseDef.standalone
  19638. ? (parentInjector) => {
  19639. return parentInjector.get(StandaloneService).getOrCreateStandaloneInjector(def);
  19640. }
  19641. : null,
  19642. getExternalStyles: null,
  19643. signals: componentDefinition.signals ?? false,
  19644. data: componentDefinition.data || {},
  19645. encapsulation: componentDefinition.encapsulation || ViewEncapsulation.Emulated,
  19646. styles: componentDefinition.styles || EMPTY_ARRAY,
  19647. _: null,
  19648. schemas: componentDefinition.schemas || null,
  19649. tView: null,
  19650. id: '',
  19651. };
  19652. // TODO: Do we still need/want this ?
  19653. if (baseDef.standalone) {
  19654. performanceMarkFeature('NgStandalone');
  19655. }
  19656. initFeatures(def);
  19657. const dependencies = componentDefinition.dependencies;
  19658. def.directiveDefs = extractDefListOrFactory(dependencies, /* pipeDef */ false);
  19659. def.pipeDefs = extractDefListOrFactory(dependencies, /* pipeDef */ true);
  19660. def.id = getComponentId(def);
  19661. return def;
  19662. });
  19663. }
  19664. function extractDirectiveDef(type) {
  19665. return getComponentDef(type) || getDirectiveDef(type);
  19666. }
  19667. function nonNull(value) {
  19668. return value !== null;
  19669. }
  19670. /**
  19671. * @codeGenApi
  19672. */
  19673. function ɵɵdefineNgModule(def) {
  19674. return noSideEffects(() => {
  19675. const res = {
  19676. type: def.type,
  19677. bootstrap: def.bootstrap || EMPTY_ARRAY,
  19678. declarations: def.declarations || EMPTY_ARRAY,
  19679. imports: def.imports || EMPTY_ARRAY,
  19680. exports: def.exports || EMPTY_ARRAY,
  19681. transitiveCompileScopes: null,
  19682. schemas: def.schemas || null,
  19683. id: def.id || null,
  19684. };
  19685. return res;
  19686. });
  19687. }
  19688. /**
  19689. * Converts binding objects from the `DirectiveDefinition` into more efficient
  19690. * lookup dictionaries that are optimized for the framework runtime.
  19691. *
  19692. * This function converts inputs or output directive information into new objects
  19693. * where the public name conveniently maps to the minified internal field name.
  19694. *
  19695. * For inputs, the input flags are additionally persisted into the new data structure,
  19696. * so that those can be quickly retrieved when needed.
  19697. *
  19698. * e.g. for
  19699. *
  19700. * ```ts
  19701. * class Comp {
  19702. * @Input()
  19703. * propName1: string;
  19704. *
  19705. * @Input('publicName2')
  19706. * declaredPropName2: number;
  19707. *
  19708. * inputSignal = input(3);
  19709. * }
  19710. * ```
  19711. *
  19712. * will be serialized as
  19713. *
  19714. * ```ts
  19715. * {
  19716. * propName1: 'propName1',
  19717. * declaredPropName2: ['publicName2', 'declaredPropName2'],
  19718. * inputSignal: [InputFlags.SignalBased, 'inputSignal'],
  19719. * }
  19720. * ```
  19721. *
  19722. * which is than translated by the minifier as:
  19723. *
  19724. * ```ts
  19725. * {
  19726. * minifiedPropName1: 'propName1',
  19727. * minifiedPropName2: ['publicName2', 'declaredPropName2'],
  19728. * minifiedInputSignal: [InputFlags.SignalBased, 'inputSignal'],
  19729. * }
  19730. * ```
  19731. *
  19732. * becomes: (public name => minifiedName + isSignal if needed)
  19733. *
  19734. * ```ts
  19735. * {
  19736. * 'propName1': 'minifiedPropName1',
  19737. * 'publicName2': 'minifiedPropName2',
  19738. * 'inputSignal': ['minifiedInputSignal', InputFlags.SignalBased],
  19739. * }
  19740. * ```
  19741. *
  19742. * Optionally the function can take `declaredInputs` which will result
  19743. * in: (public name => declared name)
  19744. *
  19745. * ```ts
  19746. * {
  19747. * 'propName1': 'propName1',
  19748. * 'publicName2': 'declaredPropName2',
  19749. * 'inputSignal': 'inputSignal',
  19750. * }
  19751. * ```
  19752. *
  19753. */
  19754. function parseAndConvertInputsForDefinition(obj, declaredInputs) {
  19755. if (obj == null)
  19756. return EMPTY_OBJ;
  19757. const newLookup = {};
  19758. for (const minifiedKey in obj) {
  19759. if (obj.hasOwnProperty(minifiedKey)) {
  19760. const value = obj[minifiedKey];
  19761. let publicName;
  19762. let declaredName;
  19763. let inputFlags;
  19764. let transform;
  19765. if (Array.isArray(value)) {
  19766. inputFlags = value[0];
  19767. publicName = value[1];
  19768. declaredName = value[2] ?? publicName; // declared name might not be set to save bytes.
  19769. transform = value[3] || null;
  19770. }
  19771. else {
  19772. publicName = value;
  19773. declaredName = value;
  19774. inputFlags = InputFlags.None;
  19775. transform = null;
  19776. }
  19777. newLookup[publicName] = [minifiedKey, inputFlags, transform];
  19778. declaredInputs[publicName] = declaredName;
  19779. }
  19780. }
  19781. return newLookup;
  19782. }
  19783. function parseAndConvertOutputsForDefinition(obj) {
  19784. if (obj == null)
  19785. return EMPTY_OBJ;
  19786. const newLookup = {};
  19787. for (const minifiedKey in obj) {
  19788. if (obj.hasOwnProperty(minifiedKey)) {
  19789. newLookup[obj[minifiedKey]] = minifiedKey;
  19790. }
  19791. }
  19792. return newLookup;
  19793. }
  19794. /**
  19795. * Create a directive definition object.
  19796. *
  19797. * # Example
  19798. * ```ts
  19799. * class MyDirective {
  19800. * // Generated by Angular Template Compiler
  19801. * // [Symbol] syntax will not be supported by TypeScript until v2.7
  19802. * static ɵdir = ɵɵdefineDirective({
  19803. * ...
  19804. * });
  19805. * }
  19806. * ```
  19807. *
  19808. * @codeGenApi
  19809. */
  19810. function ɵɵdefineDirective(directiveDefinition) {
  19811. return noSideEffects(() => {
  19812. const def = getNgDirectiveDef(directiveDefinition);
  19813. initFeatures(def);
  19814. return def;
  19815. });
  19816. }
  19817. /**
  19818. * Create a pipe definition object.
  19819. *
  19820. * # Example
  19821. * ```ts
  19822. * class MyPipe implements PipeTransform {
  19823. * // Generated by Angular Template Compiler
  19824. * static ɵpipe = definePipe({
  19825. * ...
  19826. * });
  19827. * }
  19828. * ```
  19829. * @param pipeDef Pipe definition generated by the compiler
  19830. *
  19831. * @codeGenApi
  19832. */
  19833. function ɵɵdefinePipe(pipeDef) {
  19834. return {
  19835. type: pipeDef.type,
  19836. name: pipeDef.name,
  19837. factory: null,
  19838. pure: pipeDef.pure !== false,
  19839. standalone: pipeDef.standalone ?? true,
  19840. onDestroy: pipeDef.type.prototype.ngOnDestroy || null,
  19841. };
  19842. }
  19843. function getNgDirectiveDef(directiveDefinition) {
  19844. const declaredInputs = {};
  19845. return {
  19846. type: directiveDefinition.type,
  19847. providersResolver: null,
  19848. factory: null,
  19849. hostBindings: directiveDefinition.hostBindings || null,
  19850. hostVars: directiveDefinition.hostVars || 0,
  19851. hostAttrs: directiveDefinition.hostAttrs || null,
  19852. contentQueries: directiveDefinition.contentQueries || null,
  19853. declaredInputs: declaredInputs,
  19854. inputConfig: directiveDefinition.inputs || EMPTY_OBJ,
  19855. exportAs: directiveDefinition.exportAs || null,
  19856. standalone: directiveDefinition.standalone ?? true,
  19857. signals: directiveDefinition.signals === true,
  19858. selectors: directiveDefinition.selectors || EMPTY_ARRAY,
  19859. viewQuery: directiveDefinition.viewQuery || null,
  19860. features: directiveDefinition.features || null,
  19861. setInput: null,
  19862. findHostDirectiveDefs: null,
  19863. hostDirectives: null,
  19864. inputs: parseAndConvertInputsForDefinition(directiveDefinition.inputs, declaredInputs),
  19865. outputs: parseAndConvertOutputsForDefinition(directiveDefinition.outputs),
  19866. debugInfo: null,
  19867. };
  19868. }
  19869. function initFeatures(definition) {
  19870. definition.features?.forEach((fn) => fn(definition));
  19871. }
  19872. function extractDefListOrFactory(dependencies, pipeDef) {
  19873. if (!dependencies) {
  19874. return null;
  19875. }
  19876. const defExtractor = pipeDef ? getPipeDef$1 : extractDirectiveDef;
  19877. return () => (typeof dependencies === 'function' ? dependencies() : dependencies)
  19878. .map((dep) => defExtractor(dep))
  19879. .filter(nonNull);
  19880. }
  19881. /**
  19882. * A map that contains the generated component IDs and type.
  19883. */
  19884. const GENERATED_COMP_IDS = new Map();
  19885. /**
  19886. * A method can returns a component ID from the component definition using a variant of DJB2 hash
  19887. * algorithm.
  19888. */
  19889. function getComponentId(componentDef) {
  19890. let hash = 0;
  19891. // For components with i18n in templates, the `consts` array is generated by the compiler
  19892. // as a function. If client and server bundles were produced with different minification
  19893. // configurations, the serializable contents of the function body would be different on
  19894. // the client and on the server. This might result in different ids generated. To avoid this
  19895. // issue, we do not take the `consts` contents into account if it's a function.
  19896. // See https://github.com/angular/angular/issues/58713.
  19897. const componentDefConsts = typeof componentDef.consts === 'function' ? '' : componentDef.consts;
  19898. // We cannot rely solely on the component selector as the same selector can be used in different
  19899. // modules.
  19900. //
  19901. // `componentDef.style` is not used, due to it causing inconsistencies. Ex: when server
  19902. // component styles has no sourcemaps and browsers do.
  19903. //
  19904. // Example:
  19905. // https://github.com/angular/components/blob/d9f82c8f95309e77a6d82fd574c65871e91354c2/src/material/core/option/option.ts#L248
  19906. // https://github.com/angular/components/blob/285f46dc2b4c5b127d356cb7c4714b221f03ce50/src/material/legacy-core/option/option.ts#L32
  19907. const hashSelectors = [
  19908. componentDef.selectors,
  19909. componentDef.ngContentSelectors,
  19910. componentDef.hostVars,
  19911. componentDef.hostAttrs,
  19912. componentDefConsts,
  19913. componentDef.vars,
  19914. componentDef.decls,
  19915. componentDef.encapsulation,
  19916. componentDef.standalone,
  19917. componentDef.signals,
  19918. componentDef.exportAs,
  19919. JSON.stringify(componentDef.inputs),
  19920. JSON.stringify(componentDef.outputs),
  19921. // We cannot use 'componentDef.type.name' as the name of the symbol will change and will not
  19922. // match in the server and browser bundles.
  19923. Object.getOwnPropertyNames(componentDef.type.prototype),
  19924. !!componentDef.contentQueries,
  19925. !!componentDef.viewQuery,
  19926. ];
  19927. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  19928. // If client and server bundles were produced with different minification configurations,
  19929. // the serializable contents of the function body would be different on the client and on
  19930. // the server. Ensure that we do not accidentally use functions in component id computation.
  19931. for (const item of hashSelectors) {
  19932. assertNotEqual(typeof item, 'function', 'Internal error: attempting to use a function in component id computation logic.');
  19933. }
  19934. }
  19935. for (const char of hashSelectors.join('|')) {
  19936. hash = (Math.imul(31, hash) + char.charCodeAt(0)) << 0;
  19937. }
  19938. // Force positive number hash.
  19939. // 2147483647 = equivalent of Integer.MAX_VALUE.
  19940. hash += 2147483647 + 1;
  19941. const compId = 'c' + hash;
  19942. if ((typeof ngDevMode === 'undefined' || ngDevMode) &&
  19943. // Skip the check on the server since we can't guarantee the same component instance between
  19944. // requests. Note that we can't use DI to check if we're on the server, because the component
  19945. // hasn't been instantiated yet.
  19946. (typeof ngServerMode === 'undefined' || !ngServerMode)) {
  19947. if (GENERATED_COMP_IDS.has(compId)) {
  19948. const previousCompDefType = GENERATED_COMP_IDS.get(compId);
  19949. if (previousCompDefType !== componentDef.type) {
  19950. 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.`));
  19951. }
  19952. }
  19953. else {
  19954. GENERATED_COMP_IDS.set(compId, componentDef.type);
  19955. }
  19956. }
  19957. return compId;
  19958. }
  19959. function getSuperType(type) {
  19960. return Object.getPrototypeOf(type.prototype).constructor;
  19961. }
  19962. /**
  19963. * Merges the definition from a super class to a sub class.
  19964. * @param definition The definition that is a SubClass of another directive of component
  19965. *
  19966. * @codeGenApi
  19967. */
  19968. function ɵɵInheritDefinitionFeature(definition) {
  19969. let superType = getSuperType(definition.type);
  19970. let shouldInheritFields = true;
  19971. const inheritanceChain = [definition];
  19972. while (superType) {
  19973. let superDef = undefined;
  19974. if (isComponentDef(definition)) {
  19975. // Don't use getComponentDef/getDirectiveDef. This logic relies on inheritance.
  19976. superDef = superType.ɵcmp || superType.ɵdir;
  19977. }
  19978. else {
  19979. if (superType.ɵcmp) {
  19980. throw new RuntimeError(903 /* RuntimeErrorCode.INVALID_INHERITANCE */, ngDevMode &&
  19981. `Directives cannot inherit Components. Directive ${stringifyForError(definition.type)} is attempting to extend component ${stringifyForError(superType)}`);
  19982. }
  19983. // Don't use getComponentDef/getDirectiveDef. This logic relies on inheritance.
  19984. superDef = superType.ɵdir;
  19985. }
  19986. if (superDef) {
  19987. if (shouldInheritFields) {
  19988. inheritanceChain.push(superDef);
  19989. // Some fields in the definition may be empty, if there were no values to put in them that
  19990. // would've justified object creation. Unwrap them if necessary.
  19991. const writeableDef = definition;
  19992. writeableDef.inputs = maybeUnwrapEmpty(definition.inputs);
  19993. writeableDef.declaredInputs = maybeUnwrapEmpty(definition.declaredInputs);
  19994. writeableDef.outputs = maybeUnwrapEmpty(definition.outputs);
  19995. // Merge hostBindings
  19996. const superHostBindings = superDef.hostBindings;
  19997. superHostBindings && inheritHostBindings(definition, superHostBindings);
  19998. // Merge queries
  19999. const superViewQuery = superDef.viewQuery;
  20000. const superContentQueries = superDef.contentQueries;
  20001. superViewQuery && inheritViewQuery(definition, superViewQuery);
  20002. superContentQueries && inheritContentQueries(definition, superContentQueries);
  20003. // Merge inputs and outputs
  20004. mergeInputsWithTransforms(definition, superDef);
  20005. fillProperties(definition.outputs, superDef.outputs);
  20006. // Merge animations metadata.
  20007. // If `superDef` is a Component, the `data` field is present (defaults to an empty object).
  20008. if (isComponentDef(superDef) && superDef.data.animation) {
  20009. // If super def is a Component, the `definition` is also a Component, since Directives can
  20010. // not inherit Components (we throw an error above and cannot reach this code).
  20011. const defData = definition.data;
  20012. defData.animation = (defData.animation || []).concat(superDef.data.animation);
  20013. }
  20014. }
  20015. // Run parent features
  20016. const features = superDef.features;
  20017. if (features) {
  20018. for (let i = 0; i < features.length; i++) {
  20019. const feature = features[i];
  20020. if (feature && feature.ngInherit) {
  20021. feature(definition);
  20022. }
  20023. // If `InheritDefinitionFeature` is a part of the current `superDef`, it means that this
  20024. // def already has all the necessary information inherited from its super class(es), so we
  20025. // can stop merging fields from super classes. However we need to iterate through the
  20026. // prototype chain to look for classes that might contain other "features" (like
  20027. // NgOnChanges), which we should invoke for the original `definition`. We set the
  20028. // `shouldInheritFields` flag to indicate that, essentially skipping fields inheritance
  20029. // logic and only invoking functions from the "features" list.
  20030. if (feature === ɵɵInheritDefinitionFeature) {
  20031. shouldInheritFields = false;
  20032. }
  20033. }
  20034. }
  20035. }
  20036. superType = Object.getPrototypeOf(superType);
  20037. }
  20038. mergeHostAttrsAcrossInheritance(inheritanceChain);
  20039. }
  20040. function mergeInputsWithTransforms(target, source) {
  20041. for (const key in source.inputs) {
  20042. if (!source.inputs.hasOwnProperty(key)) {
  20043. continue;
  20044. }
  20045. if (target.inputs.hasOwnProperty(key)) {
  20046. continue;
  20047. }
  20048. const value = source.inputs[key];
  20049. if (value !== undefined) {
  20050. target.inputs[key] = value;
  20051. target.declaredInputs[key] = source.declaredInputs[key];
  20052. }
  20053. }
  20054. }
  20055. /**
  20056. * Merge the `hostAttrs` and `hostVars` from the inherited parent to the base class.
  20057. *
  20058. * @param inheritanceChain A list of `WritableDefs` starting at the top most type and listing
  20059. * sub-types in order. For each type take the `hostAttrs` and `hostVars` and merge it with the child
  20060. * type.
  20061. */
  20062. function mergeHostAttrsAcrossInheritance(inheritanceChain) {
  20063. let hostVars = 0;
  20064. let hostAttrs = null;
  20065. // We process the inheritance order from the base to the leaves here.
  20066. for (let i = inheritanceChain.length - 1; i >= 0; i--) {
  20067. const def = inheritanceChain[i];
  20068. // For each `hostVars`, we need to add the superclass amount.
  20069. def.hostVars = hostVars += def.hostVars;
  20070. // for each `hostAttrs` we need to merge it with superclass.
  20071. def.hostAttrs = mergeHostAttrs(def.hostAttrs, (hostAttrs = mergeHostAttrs(hostAttrs, def.hostAttrs)));
  20072. }
  20073. }
  20074. function maybeUnwrapEmpty(value) {
  20075. if (value === EMPTY_OBJ) {
  20076. return {};
  20077. }
  20078. else if (value === EMPTY_ARRAY) {
  20079. return [];
  20080. }
  20081. else {
  20082. return value;
  20083. }
  20084. }
  20085. function inheritViewQuery(definition, superViewQuery) {
  20086. const prevViewQuery = definition.viewQuery;
  20087. if (prevViewQuery) {
  20088. definition.viewQuery = (rf, ctx) => {
  20089. superViewQuery(rf, ctx);
  20090. prevViewQuery(rf, ctx);
  20091. };
  20092. }
  20093. else {
  20094. definition.viewQuery = superViewQuery;
  20095. }
  20096. }
  20097. function inheritContentQueries(definition, superContentQueries) {
  20098. const prevContentQueries = definition.contentQueries;
  20099. if (prevContentQueries) {
  20100. definition.contentQueries = (rf, ctx, directiveIndex) => {
  20101. superContentQueries(rf, ctx, directiveIndex);
  20102. prevContentQueries(rf, ctx, directiveIndex);
  20103. };
  20104. }
  20105. else {
  20106. definition.contentQueries = superContentQueries;
  20107. }
  20108. }
  20109. function inheritHostBindings(definition, superHostBindings) {
  20110. const prevHostBindings = definition.hostBindings;
  20111. if (prevHostBindings) {
  20112. definition.hostBindings = (rf, ctx) => {
  20113. superHostBindings(rf, ctx);
  20114. prevHostBindings(rf, ctx);
  20115. };
  20116. }
  20117. else {
  20118. definition.hostBindings = superHostBindings;
  20119. }
  20120. }
  20121. /**
  20122. * Fields which exist on either directive or component definitions, and need to be copied from
  20123. * parent to child classes by the `ɵɵCopyDefinitionFeature`.
  20124. */
  20125. const COPY_DIRECTIVE_FIELDS = [
  20126. // The child class should use the providers of its parent.
  20127. 'providersResolver',
  20128. // Not listed here are any fields which are handled by the `ɵɵInheritDefinitionFeature`, such
  20129. // as inputs, outputs, and host binding functions.
  20130. ];
  20131. /**
  20132. * Fields which exist only on component definitions, and need to be copied from parent to child
  20133. * classes by the `ɵɵCopyDefinitionFeature`.
  20134. *
  20135. * The type here allows any field of `ComponentDef` which is not also a property of `DirectiveDef`,
  20136. * since those should go in `COPY_DIRECTIVE_FIELDS` above.
  20137. */
  20138. const COPY_COMPONENT_FIELDS = [
  20139. // The child class should use the template function of its parent, including all template
  20140. // semantics.
  20141. 'template',
  20142. 'decls',
  20143. 'consts',
  20144. 'vars',
  20145. 'onPush',
  20146. 'ngContentSelectors',
  20147. // The child class should use the CSS styles of its parent, including all styling semantics.
  20148. 'styles',
  20149. 'encapsulation',
  20150. // The child class should be checked by the runtime in the same way as its parent.
  20151. 'schemas',
  20152. ];
  20153. /**
  20154. * Copies the fields not handled by the `ɵɵInheritDefinitionFeature` from the supertype of a
  20155. * definition.
  20156. *
  20157. * This exists primarily to support ngcc migration of an existing View Engine pattern, where an
  20158. * entire decorator is inherited from a parent to a child class. When ngcc detects this case, it
  20159. * generates a skeleton definition on the child class, and applies this feature.
  20160. *
  20161. * The `ɵɵCopyDefinitionFeature` then copies any needed fields from the parent class' definition,
  20162. * including things like the component template function.
  20163. *
  20164. * @param definition The definition of a child class which inherits from a parent class with its
  20165. * own definition.
  20166. *
  20167. * @codeGenApi
  20168. */
  20169. function ɵɵCopyDefinitionFeature(definition) {
  20170. let superType = getSuperType(definition.type);
  20171. let superDef = undefined;
  20172. if (isComponentDef(definition)) {
  20173. // Don't use getComponentDef/getDirectiveDef. This logic relies on inheritance.
  20174. superDef = superType.ɵcmp;
  20175. }
  20176. else {
  20177. // Don't use getComponentDef/getDirectiveDef. This logic relies on inheritance.
  20178. superDef = superType.ɵdir;
  20179. }
  20180. // Needed because `definition` fields are readonly.
  20181. const defAny = definition;
  20182. // Copy over any fields that apply to either directives or components.
  20183. for (const field of COPY_DIRECTIVE_FIELDS) {
  20184. defAny[field] = superDef[field];
  20185. }
  20186. if (isComponentDef(superDef)) {
  20187. // Copy over any component-specific fields.
  20188. for (const field of COPY_COMPONENT_FIELDS) {
  20189. defAny[field] = superDef[field];
  20190. }
  20191. }
  20192. }
  20193. /**
  20194. * This feature adds the host directives behavior to a directive definition by patching a
  20195. * function onto it. The expectation is that the runtime will invoke the function during
  20196. * directive matching.
  20197. *
  20198. * For example:
  20199. * ```ts
  20200. * class ComponentWithHostDirective {
  20201. * static ɵcmp = defineComponent({
  20202. * type: ComponentWithHostDirective,
  20203. * features: [ɵɵHostDirectivesFeature([
  20204. * SimpleHostDirective,
  20205. * {directive: AdvancedHostDirective, inputs: ['foo: alias'], outputs: ['bar']},
  20206. * ])]
  20207. * });
  20208. * }
  20209. * ```
  20210. *
  20211. * @codeGenApi
  20212. */
  20213. function ɵɵHostDirectivesFeature(rawHostDirectives) {
  20214. const feature = (definition) => {
  20215. const isEager = Array.isArray(rawHostDirectives);
  20216. if (definition.hostDirectives === null) {
  20217. definition.findHostDirectiveDefs = findHostDirectiveDefs;
  20218. definition.hostDirectives = isEager
  20219. ? rawHostDirectives.map(createHostDirectiveDef)
  20220. : [rawHostDirectives];
  20221. }
  20222. else if (isEager) {
  20223. definition.hostDirectives.unshift(...rawHostDirectives.map(createHostDirectiveDef));
  20224. }
  20225. else {
  20226. definition.hostDirectives.unshift(rawHostDirectives);
  20227. }
  20228. };
  20229. feature.ngInherit = true;
  20230. return feature;
  20231. }
  20232. function findHostDirectiveDefs(currentDef, matchedDefs, hostDirectiveDefs) {
  20233. if (currentDef.hostDirectives !== null) {
  20234. for (const configOrFn of currentDef.hostDirectives) {
  20235. if (typeof configOrFn === 'function') {
  20236. const resolved = configOrFn();
  20237. for (const config of resolved) {
  20238. trackHostDirectiveDef(createHostDirectiveDef(config), matchedDefs, hostDirectiveDefs);
  20239. }
  20240. }
  20241. else {
  20242. trackHostDirectiveDef(configOrFn, matchedDefs, hostDirectiveDefs);
  20243. }
  20244. }
  20245. }
  20246. }
  20247. /** Tracks a single host directive during directive matching. */
  20248. function trackHostDirectiveDef(def, matchedDefs, hostDirectiveDefs) {
  20249. const hostDirectiveDef = getDirectiveDef(def.directive);
  20250. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  20251. validateHostDirective(def, hostDirectiveDef);
  20252. }
  20253. // We need to patch the `declaredInputs` so that
  20254. // `ngOnChanges` can map the properties correctly.
  20255. patchDeclaredInputs(hostDirectiveDef.declaredInputs, def.inputs);
  20256. // Host directives execute before the host so that its host bindings can be overwritten.
  20257. findHostDirectiveDefs(hostDirectiveDef, matchedDefs, hostDirectiveDefs);
  20258. hostDirectiveDefs.set(hostDirectiveDef, def);
  20259. matchedDefs.push(hostDirectiveDef);
  20260. }
  20261. /** Creates a `HostDirectiveDef` from a used-defined host directive configuration. */
  20262. function createHostDirectiveDef(config) {
  20263. return typeof config === 'function'
  20264. ? { directive: resolveForwardRef(config), inputs: EMPTY_OBJ, outputs: EMPTY_OBJ }
  20265. : {
  20266. directive: resolveForwardRef(config.directive),
  20267. inputs: bindingArrayToMap(config.inputs),
  20268. outputs: bindingArrayToMap(config.outputs),
  20269. };
  20270. }
  20271. /**
  20272. * Converts an array in the form of `['publicName', 'alias', 'otherPublicName', 'otherAlias']` into
  20273. * a map in the form of `{publicName: 'alias', otherPublicName: 'otherAlias'}`.
  20274. */
  20275. function bindingArrayToMap(bindings) {
  20276. if (bindings === undefined || bindings.length === 0) {
  20277. return EMPTY_OBJ;
  20278. }
  20279. const result = {};
  20280. for (let i = 0; i < bindings.length; i += 2) {
  20281. result[bindings[i]] = bindings[i + 1];
  20282. }
  20283. return result;
  20284. }
  20285. /**
  20286. * `ngOnChanges` has some leftover legacy ViewEngine behavior where the keys inside the
  20287. * `SimpleChanges` event refer to the *declared* name of the input, not its public name or its
  20288. * minified name. E.g. in `@Input('alias') foo: string`, the name in the `SimpleChanges` object
  20289. * will always be `foo`, and not `alias` or the minified name of `foo` in apps using property
  20290. * minification.
  20291. *
  20292. * This is achieved through the `DirectiveDef.declaredInputs` map that is constructed when the
  20293. * definition is declared. When a property is written to the directive instance, the
  20294. * `NgOnChangesFeature` will try to remap the property name being written to using the
  20295. * `declaredInputs`.
  20296. *
  20297. * Since the host directive input remapping happens during directive matching, `declaredInputs`
  20298. * won't contain the new alias that the input is available under. This function addresses the
  20299. * issue by patching the host directive aliases to the `declaredInputs`. There is *not* a risk of
  20300. * this patching accidentally introducing new inputs to the host directive, because `declaredInputs`
  20301. * is used *only* by the `NgOnChangesFeature` when determining what name is used in the
  20302. * `SimpleChanges` object which won't be reached if an input doesn't exist.
  20303. */
  20304. function patchDeclaredInputs(declaredInputs, exposedInputs) {
  20305. for (const publicName in exposedInputs) {
  20306. if (exposedInputs.hasOwnProperty(publicName)) {
  20307. const remappedPublicName = exposedInputs[publicName];
  20308. const privateName = declaredInputs[publicName];
  20309. // We *technically* shouldn't be able to hit this case because we can't have multiple
  20310. // inputs on the same property and we have validations against conflicting aliases in
  20311. // `validateMappings`. If we somehow did, it would lead to `ngOnChanges` being invoked
  20312. // with the wrong name so we have a non-user-friendly assertion here just in case.
  20313. if ((typeof ngDevMode === 'undefined' || ngDevMode) &&
  20314. declaredInputs.hasOwnProperty(remappedPublicName)) {
  20315. assertEqual(declaredInputs[remappedPublicName], declaredInputs[publicName], `Conflicting host directive input alias ${publicName}.`);
  20316. }
  20317. declaredInputs[remappedPublicName] = privateName;
  20318. }
  20319. }
  20320. }
  20321. /**
  20322. * Verifies that the host directive has been configured correctly.
  20323. * @param hostDirectiveConfig Host directive configuration object.
  20324. * @param directiveDef Directive definition of the host directive.
  20325. */
  20326. function validateHostDirective(hostDirectiveConfig, directiveDef) {
  20327. const type = hostDirectiveConfig.directive;
  20328. if (directiveDef === null) {
  20329. if (getComponentDef(type) !== null) {
  20330. throw new RuntimeError(310 /* RuntimeErrorCode.HOST_DIRECTIVE_COMPONENT */, `Host directive ${type.name} cannot be a component.`);
  20331. }
  20332. throw new RuntimeError(307 /* RuntimeErrorCode.HOST_DIRECTIVE_UNRESOLVABLE */, `Could not resolve metadata for host directive ${type.name}. ` +
  20333. `Make sure that the ${type.name} class is annotated with an @Directive decorator.`);
  20334. }
  20335. if (!directiveDef.standalone) {
  20336. throw new RuntimeError(308 /* RuntimeErrorCode.HOST_DIRECTIVE_NOT_STANDALONE */, `Host directive ${directiveDef.type.name} must be standalone.`);
  20337. }
  20338. validateMappings('input', directiveDef, hostDirectiveConfig.inputs);
  20339. validateMappings('output', directiveDef, hostDirectiveConfig.outputs);
  20340. }
  20341. /**
  20342. * Checks that the host directive inputs/outputs configuration is valid.
  20343. * @param bindingType Kind of binding that is being validated. Used in the error message.
  20344. * @param def Definition of the host directive that is being validated against.
  20345. * @param hostDirectiveBindings Host directive mapping object that shold be validated.
  20346. */
  20347. function validateMappings(bindingType, def, hostDirectiveBindings) {
  20348. const className = def.type.name;
  20349. const bindings = bindingType === 'input' ? def.inputs : def.outputs;
  20350. for (const publicName in hostDirectiveBindings) {
  20351. if (hostDirectiveBindings.hasOwnProperty(publicName)) {
  20352. if (!bindings.hasOwnProperty(publicName)) {
  20353. throw new RuntimeError(311 /* RuntimeErrorCode.HOST_DIRECTIVE_UNDEFINED_BINDING */, `Directive ${className} does not have an ${bindingType} with a public name of ${publicName}.`);
  20354. }
  20355. const remappedPublicName = hostDirectiveBindings[publicName];
  20356. if (bindings.hasOwnProperty(remappedPublicName) && remappedPublicName !== publicName) {
  20357. 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.`);
  20358. }
  20359. }
  20360. }
  20361. }
  20362. function isListLikeIterable(obj) {
  20363. if (!isJsObject(obj))
  20364. return false;
  20365. return (Array.isArray(obj) ||
  20366. (!(obj instanceof Map) && // JS Map are iterables but return entries as [k, v]
  20367. Symbol.iterator in obj)); // JS Iterable have a Symbol.iterator prop
  20368. }
  20369. function areIterablesEqual(a, b, comparator) {
  20370. const iterator1 = a[Symbol.iterator]();
  20371. const iterator2 = b[Symbol.iterator]();
  20372. while (true) {
  20373. const item1 = iterator1.next();
  20374. const item2 = iterator2.next();
  20375. if (item1.done && item2.done)
  20376. return true;
  20377. if (item1.done || item2.done)
  20378. return false;
  20379. if (!comparator(item1.value, item2.value))
  20380. return false;
  20381. }
  20382. }
  20383. function iterateListLike(obj, fn) {
  20384. if (Array.isArray(obj)) {
  20385. for (let i = 0; i < obj.length; i++) {
  20386. fn(obj[i]);
  20387. }
  20388. }
  20389. else {
  20390. const iterator = obj[Symbol.iterator]();
  20391. let item;
  20392. while (!(item = iterator.next()).done) {
  20393. fn(item.value);
  20394. }
  20395. }
  20396. }
  20397. function isJsObject(o) {
  20398. return o !== null && (typeof o === 'function' || typeof o === 'object');
  20399. }
  20400. function devModeEqual(a, b) {
  20401. const isListLikeIterableA = isListLikeIterable(a);
  20402. const isListLikeIterableB = isListLikeIterable(b);
  20403. if (isListLikeIterableA && isListLikeIterableB) {
  20404. return areIterablesEqual(a, b, devModeEqual);
  20405. }
  20406. else {
  20407. const isAObject = a && (typeof a === 'object' || typeof a === 'function');
  20408. const isBObject = b && (typeof b === 'object' || typeof b === 'function');
  20409. if (!isListLikeIterableA && isAObject && !isListLikeIterableB && isBObject) {
  20410. return true;
  20411. }
  20412. else {
  20413. return Object.is(a, b);
  20414. }
  20415. }
  20416. }
  20417. // TODO(misko): consider inlining
  20418. /** Updates binding and returns the value. */
  20419. function updateBinding(lView, bindingIndex, value) {
  20420. return (lView[bindingIndex] = value);
  20421. }
  20422. /** Gets the current binding value. */
  20423. function getBinding(lView, bindingIndex) {
  20424. ngDevMode && assertIndexInRange(lView, bindingIndex);
  20425. ngDevMode &&
  20426. assertNotSame(lView[bindingIndex], NO_CHANGE, 'Stored value should never be NO_CHANGE.');
  20427. return lView[bindingIndex];
  20428. }
  20429. /**
  20430. * Updates binding if changed, then returns whether it was updated.
  20431. *
  20432. * This function also checks the `CheckNoChangesMode` and throws if changes are made.
  20433. * Some changes (Objects/iterables) during `CheckNoChangesMode` are exempt to comply with VE
  20434. * behavior.
  20435. *
  20436. * @param lView current `LView`
  20437. * @param bindingIndex The binding in the `LView` to check
  20438. * @param value New value to check against `lView[bindingIndex]`
  20439. * @returns `true` if the bindings has changed. (Throws if binding has changed during
  20440. * `CheckNoChangesMode`)
  20441. */
  20442. function bindingUpdated(lView, bindingIndex, value) {
  20443. ngDevMode && assertNotSame(value, NO_CHANGE, 'Incoming value should never be NO_CHANGE.');
  20444. ngDevMode &&
  20445. assertLessThan(bindingIndex, lView.length, `Slot should have been initialized to NO_CHANGE`);
  20446. const oldValue = lView[bindingIndex];
  20447. if (Object.is(oldValue, value)) {
  20448. return false;
  20449. }
  20450. else {
  20451. if (ngDevMode && isInCheckNoChangesMode()) {
  20452. // View engine didn't report undefined values as changed on the first checkNoChanges pass
  20453. // (before the change detection was run).
  20454. const oldValueToCompare = oldValue !== NO_CHANGE ? oldValue : undefined;
  20455. if (!devModeEqual(oldValueToCompare, value)) {
  20456. const details = getExpressionChangedErrorDetails(lView, bindingIndex, oldValueToCompare, value);
  20457. throwErrorIfNoChangesMode(oldValue === NO_CHANGE, details.oldValue, details.newValue, details.propName, lView);
  20458. }
  20459. // There was a change, but the `devModeEqual` decided that the change is exempt from an error.
  20460. // For this reason we exit as if no change. The early exit is needed to prevent the changed
  20461. // value to be written into `LView` (If we would write the new value that we would not see it
  20462. // as change on next CD.)
  20463. return false;
  20464. }
  20465. lView[bindingIndex] = value;
  20466. return true;
  20467. }
  20468. }
  20469. /** Updates 2 bindings if changed, then returns whether either was updated. */
  20470. function bindingUpdated2(lView, bindingIndex, exp1, exp2) {
  20471. const different = bindingUpdated(lView, bindingIndex, exp1);
  20472. return bindingUpdated(lView, bindingIndex + 1, exp2) || different;
  20473. }
  20474. /** Updates 3 bindings if changed, then returns whether any was updated. */
  20475. function bindingUpdated3(lView, bindingIndex, exp1, exp2, exp3) {
  20476. const different = bindingUpdated2(lView, bindingIndex, exp1, exp2);
  20477. return bindingUpdated(lView, bindingIndex + 2, exp3) || different;
  20478. }
  20479. /** Updates 4 bindings if changed, then returns whether any was updated. */
  20480. function bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4) {
  20481. const different = bindingUpdated2(lView, bindingIndex, exp1, exp2);
  20482. return bindingUpdated2(lView, bindingIndex + 2, exp3, exp4) || different;
  20483. }
  20484. function templateFirstCreatePass(index, tView, lView, templateFn, decls, vars, tagName, attrs, localRefsIndex) {
  20485. ngDevMode && assertFirstCreatePass(tView);
  20486. ngDevMode && ngDevMode.firstCreatePass++;
  20487. const tViewConsts = tView.consts;
  20488. // TODO(pk): refactor getOrCreateTNode to have the "create" only version
  20489. const tNode = getOrCreateTNode(tView, index, 4 /* TNodeType.Container */, tagName || null, attrs || null);
  20490. if (getBindingsEnabled()) {
  20491. resolveDirectives(tView, lView, tNode, getConstant(tViewConsts, localRefsIndex), findDirectiveDefMatches);
  20492. }
  20493. // Merge the template attrs last so that they have the highest priority.
  20494. tNode.mergedAttrs = mergeHostAttrs(tNode.mergedAttrs, tNode.attrs);
  20495. registerPostOrderHooks(tView, tNode);
  20496. const embeddedTView = (tNode.tView = createTView(2 /* TViewType.Embedded */, tNode, templateFn, decls, vars, tView.directiveRegistry, tView.pipeRegistry, null, tView.schemas, tViewConsts, null /* ssrId */));
  20497. if (tView.queries !== null) {
  20498. tView.queries.template(tView, tNode);
  20499. embeddedTView.queries = tView.queries.embeddedTView(tNode);
  20500. }
  20501. return tNode;
  20502. }
  20503. /**
  20504. * Creates an LContainer for an embedded view.
  20505. *
  20506. * @param declarationLView LView in which the template was declared.
  20507. * @param declarationTView TView in which the template wa declared.
  20508. * @param index The index of the container in the data array
  20509. * @param templateFn Inline template
  20510. * @param decls The number of nodes, local refs, and pipes for this template
  20511. * @param vars The number of bindings for this template
  20512. * @param tagName The name of the container element, if applicable
  20513. * @param attrsIndex Index of template attributes in the `consts` array.
  20514. * @param localRefs Index of the local references in the `consts` array.
  20515. * @param localRefExtractor A function which extracts local-refs values from the template.
  20516. * Defaults to the current element associated with the local-ref.
  20517. */
  20518. function declareTemplate(declarationLView, declarationTView, index, templateFn, decls, vars, tagName, attrs, localRefsIndex, localRefExtractor) {
  20519. const adjustedIndex = index + HEADER_OFFSET;
  20520. const tNode = declarationTView.firstCreatePass
  20521. ? templateFirstCreatePass(adjustedIndex, declarationTView, declarationLView, templateFn, decls, vars, tagName, attrs, localRefsIndex)
  20522. : declarationTView.data[adjustedIndex];
  20523. setCurrentTNode(tNode, false);
  20524. const comment = _locateOrCreateContainerAnchor(declarationTView, declarationLView, tNode, index);
  20525. if (wasLastNodeCreated()) {
  20526. appendChild(declarationTView, declarationLView, comment, tNode);
  20527. }
  20528. attachPatchData(comment, declarationLView);
  20529. const lContainer = createLContainer(comment, declarationLView, comment, tNode);
  20530. declarationLView[adjustedIndex] = lContainer;
  20531. addToEndOfViewTree(declarationLView, lContainer);
  20532. // If hydration is enabled, looks up dehydrated views in the DOM
  20533. // using hydration annotation info and stores those views on LContainer.
  20534. // In client-only mode, this function is a noop.
  20535. populateDehydratedViewsInLContainer(lContainer, tNode, declarationLView);
  20536. if (isDirectiveHost(tNode)) {
  20537. createDirectivesInstances(declarationTView, declarationLView, tNode);
  20538. }
  20539. if (localRefsIndex != null) {
  20540. saveResolvedLocalsInData(declarationLView, tNode, localRefExtractor);
  20541. }
  20542. return tNode;
  20543. }
  20544. /**
  20545. * Creates an LContainer for an ng-template (dynamically-inserted view), e.g.
  20546. *
  20547. * <ng-template #foo>
  20548. * <div></div>
  20549. * </ng-template>
  20550. *
  20551. * @param index The index of the container in the data array
  20552. * @param templateFn Inline template
  20553. * @param decls The number of nodes, local refs, and pipes for this template
  20554. * @param vars The number of bindings for this template
  20555. * @param tagName The name of the container element, if applicable
  20556. * @param attrsIndex Index of template attributes in the `consts` array.
  20557. * @param localRefs Index of the local references in the `consts` array.
  20558. * @param localRefExtractor A function which extracts local-refs values from the template.
  20559. * Defaults to the current element associated with the local-ref.
  20560. *
  20561. * @codeGenApi
  20562. */
  20563. function ɵɵtemplate(index, templateFn, decls, vars, tagName, attrsIndex, localRefsIndex, localRefExtractor) {
  20564. const lView = getLView();
  20565. const tView = getTView();
  20566. const attrs = getConstant(tView.consts, attrsIndex);
  20567. declareTemplate(lView, tView, index, templateFn, decls, vars, tagName, attrs, localRefsIndex, localRefExtractor);
  20568. return ɵɵtemplate;
  20569. }
  20570. let _locateOrCreateContainerAnchor = createContainerAnchorImpl;
  20571. /**
  20572. * Regular creation mode for LContainers and their anchor (comment) nodes.
  20573. */
  20574. function createContainerAnchorImpl(tView, lView, tNode, index) {
  20575. lastNodeWasCreated(true);
  20576. return lView[RENDERER].createComment(ngDevMode ? 'container' : '');
  20577. }
  20578. /**
  20579. * Enables hydration code path (to lookup existing elements in DOM)
  20580. * in addition to the regular creation mode for LContainers and their
  20581. * anchor (comment) nodes.
  20582. */
  20583. function locateOrCreateContainerAnchorImpl(tView, lView, tNode, index) {
  20584. const hydrationInfo = lView[HYDRATION];
  20585. const isNodeCreationMode = !hydrationInfo ||
  20586. isInSkipHydrationBlock$1() ||
  20587. isDetachedByI18n(tNode) ||
  20588. isDisconnectedNode$1(hydrationInfo, index);
  20589. lastNodeWasCreated(isNodeCreationMode);
  20590. // Regular creation mode.
  20591. if (isNodeCreationMode) {
  20592. return createContainerAnchorImpl(tView, lView);
  20593. }
  20594. const ssrId = hydrationInfo.data[TEMPLATES]?.[index] ?? null;
  20595. // Apply `ssrId` value to the underlying TView if it was not previously set.
  20596. //
  20597. // There might be situations when the same component is present in a template
  20598. // multiple times and some instances are opted-out of using hydration via
  20599. // `ngSkipHydration` attribute. In this scenario, at the time a TView is created,
  20600. // the `ssrId` might be `null` (if the first component is opted-out of hydration).
  20601. // The code below makes sure that the `ssrId` is applied to the TView if it's still
  20602. // `null` and verifies we never try to override it with a different value.
  20603. if (ssrId !== null && tNode.tView !== null) {
  20604. if (tNode.tView.ssrId === null) {
  20605. tNode.tView.ssrId = ssrId;
  20606. }
  20607. else {
  20608. ngDevMode &&
  20609. assertEqual(tNode.tView.ssrId, ssrId, 'Unexpected value of the `ssrId` for this TView');
  20610. }
  20611. }
  20612. // Hydration mode, looking up existing elements in DOM.
  20613. const currentRNode = locateNextRNode(hydrationInfo, tView, lView, tNode);
  20614. ngDevMode && validateNodeExists(currentRNode, lView, tNode);
  20615. setSegmentHead(hydrationInfo, index, currentRNode);
  20616. const viewContainerSize = calcSerializedContainerSize(hydrationInfo, index);
  20617. const comment = siblingAfter(viewContainerSize, currentRNode);
  20618. if (ngDevMode) {
  20619. validateMatchingNode(comment, Node.COMMENT_NODE, null, lView, tNode);
  20620. markRNodeAsClaimedByHydration(comment);
  20621. }
  20622. return comment;
  20623. }
  20624. function enableLocateOrCreateContainerAnchorImpl() {
  20625. _locateOrCreateContainerAnchor = locateOrCreateContainerAnchorImpl;
  20626. }
  20627. /**
  20628. * Helper function to schedule a callback to be invoked when a browser becomes idle.
  20629. *
  20630. * @param callback A function to be invoked when a browser becomes idle.
  20631. * @param injector injector for the app
  20632. */
  20633. function onIdle(callback, injector) {
  20634. const scheduler = injector.get(IdleScheduler);
  20635. const cleanupFn = () => scheduler.remove(callback);
  20636. scheduler.add(callback);
  20637. return cleanupFn;
  20638. }
  20639. /**
  20640. * Use shims for the `requestIdleCallback` and `cancelIdleCallback` functions for
  20641. * environments where those functions are not available (e.g. Node.js and Safari).
  20642. *
  20643. * Note: we wrap the `requestIdleCallback` call into a function, so that it can be
  20644. * overridden/mocked in test environment and picked up by the runtime code.
  20645. */
  20646. const _requestIdleCallback = () => typeof requestIdleCallback !== 'undefined' ? requestIdleCallback : setTimeout;
  20647. const _cancelIdleCallback = () => typeof requestIdleCallback !== 'undefined' ? cancelIdleCallback : clearTimeout;
  20648. /**
  20649. * Helper service to schedule `requestIdleCallback`s for batches of defer blocks,
  20650. * to avoid calling `requestIdleCallback` for each defer block (e.g. if
  20651. * defer blocks are defined inside a for loop).
  20652. */
  20653. class IdleScheduler {
  20654. // Indicates whether current callbacks are being invoked.
  20655. executingCallbacks = false;
  20656. // Currently scheduled idle callback id.
  20657. idleId = null;
  20658. // Set of callbacks to be invoked next.
  20659. current = new Set();
  20660. // Set of callbacks collected while invoking current set of callbacks.
  20661. // Those callbacks are scheduled for the next idle period.
  20662. deferred = new Set();
  20663. ngZone = inject(NgZone);
  20664. requestIdleCallbackFn = _requestIdleCallback().bind(globalThis);
  20665. cancelIdleCallbackFn = _cancelIdleCallback().bind(globalThis);
  20666. add(callback) {
  20667. const target = this.executingCallbacks ? this.deferred : this.current;
  20668. target.add(callback);
  20669. if (this.idleId === null) {
  20670. this.scheduleIdleCallback();
  20671. }
  20672. }
  20673. remove(callback) {
  20674. const { current, deferred } = this;
  20675. current.delete(callback);
  20676. deferred.delete(callback);
  20677. // If the last callback was removed and there is a pending
  20678. // idle callback - cancel it.
  20679. if (current.size === 0 && deferred.size === 0) {
  20680. this.cancelIdleCallback();
  20681. }
  20682. }
  20683. scheduleIdleCallback() {
  20684. const callback = () => {
  20685. this.cancelIdleCallback();
  20686. this.executingCallbacks = true;
  20687. for (const callback of this.current) {
  20688. callback();
  20689. }
  20690. this.current.clear();
  20691. this.executingCallbacks = false;
  20692. // If there are any callbacks added during an invocation
  20693. // of the current ones - make them "current" and schedule
  20694. // a new idle callback.
  20695. if (this.deferred.size > 0) {
  20696. for (const callback of this.deferred) {
  20697. this.current.add(callback);
  20698. }
  20699. this.deferred.clear();
  20700. this.scheduleIdleCallback();
  20701. }
  20702. };
  20703. // Ensure that the callback runs in the NgZone since
  20704. // the `requestIdleCallback` is not currently patched by Zone.js.
  20705. this.idleId = this.requestIdleCallbackFn(() => this.ngZone.run(callback));
  20706. }
  20707. cancelIdleCallback() {
  20708. if (this.idleId !== null) {
  20709. this.cancelIdleCallbackFn(this.idleId);
  20710. this.idleId = null;
  20711. }
  20712. }
  20713. ngOnDestroy() {
  20714. this.cancelIdleCallback();
  20715. this.current.clear();
  20716. this.deferred.clear();
  20717. }
  20718. /** @nocollapse */
  20719. static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
  20720. token: IdleScheduler,
  20721. providedIn: 'root',
  20722. factory: () => new IdleScheduler(),
  20723. });
  20724. }
  20725. /**
  20726. * Returns a function that captures a provided delay.
  20727. * Invoking the returned function schedules a trigger.
  20728. */
  20729. function onTimer(delay) {
  20730. return (callback, injector) => scheduleTimerTrigger(delay, callback, injector);
  20731. }
  20732. /**
  20733. * Schedules a callback to be invoked after a given timeout.
  20734. *
  20735. * @param delay A number of ms to wait until firing a callback.
  20736. * @param callback A function to be invoked after a timeout.
  20737. * @param injector injector for the app.
  20738. */
  20739. function scheduleTimerTrigger(delay, callback, injector) {
  20740. const scheduler = injector.get(TimerScheduler);
  20741. const ngZone = injector.get(NgZone);
  20742. const cleanupFn = () => scheduler.remove(callback);
  20743. scheduler.add(delay, callback, ngZone);
  20744. return cleanupFn;
  20745. }
  20746. /**
  20747. * Helper service to schedule `setTimeout`s for batches of defer blocks,
  20748. * to avoid calling `setTimeout` for each defer block (e.g. if defer blocks
  20749. * are created inside a for loop).
  20750. */
  20751. class TimerScheduler {
  20752. // Indicates whether current callbacks are being invoked.
  20753. executingCallbacks = false;
  20754. // Currently scheduled `setTimeout` id.
  20755. timeoutId = null;
  20756. // When currently scheduled timer would fire.
  20757. invokeTimerAt = null;
  20758. // List of callbacks to be invoked.
  20759. // For each callback we also store a timestamp on when the callback
  20760. // should be invoked. We store timestamps and callback functions
  20761. // in a flat array to avoid creating new objects for each entry.
  20762. // [timestamp1, callback1, timestamp2, callback2, ...]
  20763. current = [];
  20764. // List of callbacks collected while invoking current set of callbacks.
  20765. // Those callbacks are added to the "current" queue at the end of
  20766. // the current callback invocation. The shape of this list is the same
  20767. // as the shape of the `current` list.
  20768. deferred = [];
  20769. add(delay, callback, ngZone) {
  20770. const target = this.executingCallbacks ? this.deferred : this.current;
  20771. this.addToQueue(target, Date.now() + delay, callback);
  20772. this.scheduleTimer(ngZone);
  20773. }
  20774. remove(callback) {
  20775. const { current, deferred } = this;
  20776. const callbackIndex = this.removeFromQueue(current, callback);
  20777. if (callbackIndex === -1) {
  20778. // Try cleaning up deferred queue only in case
  20779. // we didn't find a callback in the "current" queue.
  20780. this.removeFromQueue(deferred, callback);
  20781. }
  20782. // If the last callback was removed and there is a pending timeout - cancel it.
  20783. if (current.length === 0 && deferred.length === 0) {
  20784. this.clearTimeout();
  20785. }
  20786. }
  20787. addToQueue(target, invokeAt, callback) {
  20788. let insertAtIndex = target.length;
  20789. for (let i = 0; i < target.length; i += 2) {
  20790. const invokeQueuedCallbackAt = target[i];
  20791. if (invokeQueuedCallbackAt > invokeAt) {
  20792. // We've reached a first timer that is scheduled
  20793. // for a later time than what we are trying to insert.
  20794. // This is the location at which we need to insert,
  20795. // no need to iterate further.
  20796. insertAtIndex = i;
  20797. break;
  20798. }
  20799. }
  20800. arrayInsert2(target, insertAtIndex, invokeAt, callback);
  20801. }
  20802. removeFromQueue(target, callback) {
  20803. let index = -1;
  20804. for (let i = 0; i < target.length; i += 2) {
  20805. const queuedCallback = target[i + 1];
  20806. if (queuedCallback === callback) {
  20807. index = i;
  20808. break;
  20809. }
  20810. }
  20811. if (index > -1) {
  20812. // Remove 2 elements: a timestamp slot and
  20813. // the following slot with a callback function.
  20814. arraySplice(target, index, 2);
  20815. }
  20816. return index;
  20817. }
  20818. scheduleTimer(ngZone) {
  20819. const callback = () => {
  20820. this.clearTimeout();
  20821. this.executingCallbacks = true;
  20822. // Clone the current state of the queue, since it might be altered
  20823. // as we invoke callbacks.
  20824. const current = [...this.current];
  20825. // Invoke callbacks that were scheduled to run before the current time.
  20826. const now = Date.now();
  20827. for (let i = 0; i < current.length; i += 2) {
  20828. const invokeAt = current[i];
  20829. const callback = current[i + 1];
  20830. if (invokeAt <= now) {
  20831. callback();
  20832. }
  20833. else {
  20834. // We've reached a timer that should not be invoked yet.
  20835. break;
  20836. }
  20837. }
  20838. // The state of the queue might've changed after callbacks invocation,
  20839. // run the cleanup logic based on the *current* state of the queue.
  20840. let lastCallbackIndex = -1;
  20841. for (let i = 0; i < this.current.length; i += 2) {
  20842. const invokeAt = this.current[i];
  20843. if (invokeAt <= now) {
  20844. // Add +1 to account for a callback function that
  20845. // goes after the timestamp in events array.
  20846. lastCallbackIndex = i + 1;
  20847. }
  20848. else {
  20849. // We've reached a timer that should not be invoked yet.
  20850. break;
  20851. }
  20852. }
  20853. if (lastCallbackIndex >= 0) {
  20854. arraySplice(this.current, 0, lastCallbackIndex + 1);
  20855. }
  20856. this.executingCallbacks = false;
  20857. // If there are any callbacks added during an invocation
  20858. // of the current ones - move them over to the "current"
  20859. // queue.
  20860. if (this.deferred.length > 0) {
  20861. for (let i = 0; i < this.deferred.length; i += 2) {
  20862. const invokeAt = this.deferred[i];
  20863. const callback = this.deferred[i + 1];
  20864. this.addToQueue(this.current, invokeAt, callback);
  20865. }
  20866. this.deferred.length = 0;
  20867. }
  20868. this.scheduleTimer(ngZone);
  20869. };
  20870. // Avoid running timer callbacks more than once per
  20871. // average frame duration. This is needed for better
  20872. // batching and to avoid kicking off excessive change
  20873. // detection cycles.
  20874. const FRAME_DURATION_MS = 16; // 1000ms / 60fps
  20875. if (this.current.length > 0) {
  20876. const now = Date.now();
  20877. // First element in the queue points at the timestamp
  20878. // of the first (earliest) event.
  20879. const invokeAt = this.current[0];
  20880. if (this.timeoutId === null ||
  20881. // Reschedule a timer in case a queue contains an item with
  20882. // an earlier timestamp and the delta is more than an average
  20883. // frame duration.
  20884. (this.invokeTimerAt && this.invokeTimerAt - invokeAt > FRAME_DURATION_MS)) {
  20885. // There was a timeout already, but an earlier event was added
  20886. // into the queue. In this case we drop an old timer and setup
  20887. // a new one with an updated (smaller) timeout.
  20888. this.clearTimeout();
  20889. const timeout = Math.max(invokeAt - now, FRAME_DURATION_MS);
  20890. this.invokeTimerAt = invokeAt;
  20891. this.timeoutId = ngZone.runOutsideAngular(() => {
  20892. return setTimeout(() => ngZone.run(callback), timeout);
  20893. });
  20894. }
  20895. }
  20896. }
  20897. clearTimeout() {
  20898. if (this.timeoutId !== null) {
  20899. clearTimeout(this.timeoutId);
  20900. this.timeoutId = null;
  20901. }
  20902. }
  20903. ngOnDestroy() {
  20904. this.clearTimeout();
  20905. this.current.length = 0;
  20906. this.deferred.length = 0;
  20907. }
  20908. /** @nocollapse */
  20909. static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
  20910. token: TimerScheduler,
  20911. providedIn: 'root',
  20912. factory: () => new TimerScheduler(),
  20913. });
  20914. }
  20915. /**
  20916. * A service used by the framework to create and cache injector instances.
  20917. *
  20918. * This service is used to create a single injector instance for each defer
  20919. * block definition, to avoid creating an injector for each defer block instance
  20920. * of a certain type.
  20921. */
  20922. class CachedInjectorService {
  20923. cachedInjectors = new Map();
  20924. getOrCreateInjector(key, parentInjector, providers, debugName) {
  20925. if (!this.cachedInjectors.has(key)) {
  20926. const injector = providers.length > 0
  20927. ? createEnvironmentInjector(providers, parentInjector, debugName)
  20928. : null;
  20929. this.cachedInjectors.set(key, injector);
  20930. }
  20931. return this.cachedInjectors.get(key);
  20932. }
  20933. ngOnDestroy() {
  20934. try {
  20935. for (const injector of this.cachedInjectors.values()) {
  20936. if (injector !== null) {
  20937. injector.destroy();
  20938. }
  20939. }
  20940. }
  20941. finally {
  20942. this.cachedInjectors.clear();
  20943. }
  20944. }
  20945. /** @nocollapse */
  20946. static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
  20947. token: CachedInjectorService,
  20948. providedIn: 'environment',
  20949. factory: () => new CachedInjectorService(),
  20950. });
  20951. }
  20952. /**
  20953. * **INTERNAL**, avoid referencing it in application code.
  20954. * *
  20955. * Injector token that allows to provide `DeferBlockDependencyInterceptor` class
  20956. * implementation.
  20957. *
  20958. * This token is only injected in devMode
  20959. */
  20960. const DEFER_BLOCK_DEPENDENCY_INTERCEPTOR =
  20961. /* @__PURE__ */ new InjectionToken('DEFER_BLOCK_DEPENDENCY_INTERCEPTOR');
  20962. /**
  20963. * **INTERNAL**, token used for configuring defer block behavior.
  20964. */
  20965. const DEFER_BLOCK_CONFIG = new InjectionToken(ngDevMode ? 'DEFER_BLOCK_CONFIG' : '');
  20966. /**
  20967. * Checks whether there is a cached injector associated with a given defer block
  20968. * declaration and returns if it exists. If there is no cached injector present -
  20969. * creates a new injector and stores in the cache.
  20970. */
  20971. function getOrCreateEnvironmentInjector(parentInjector, tDetails, providers) {
  20972. return parentInjector
  20973. .get(CachedInjectorService)
  20974. .getOrCreateInjector(tDetails, parentInjector, providers, ngDevMode ? 'DeferBlock Injector' : '');
  20975. }
  20976. /** Injector Helpers */
  20977. /**
  20978. * Creates a new injector, which contains providers collected from dependencies (NgModules) of
  20979. * defer-loaded components. This function detects different types of parent injectors and creates
  20980. * a new injector based on that.
  20981. */
  20982. function createDeferBlockInjector(parentInjector, tDetails, providers) {
  20983. // Check if the parent injector is an instance of a `ChainedInjector`.
  20984. //
  20985. // In this case, we retain the shape of the injector and use a newly created
  20986. // `EnvironmentInjector` as a parent in the `ChainedInjector`. That is needed to
  20987. // make sure that the primary injector gets consulted first (since it's typically
  20988. // a NodeInjector) and `EnvironmentInjector` tree is consulted after that.
  20989. if (parentInjector instanceof ChainedInjector) {
  20990. const origInjector = parentInjector.injector;
  20991. // Guaranteed to be an environment injector
  20992. const parentEnvInjector = parentInjector.parentInjector;
  20993. const envInjector = getOrCreateEnvironmentInjector(parentEnvInjector, tDetails, providers);
  20994. return new ChainedInjector(origInjector, envInjector);
  20995. }
  20996. const parentEnvInjector = parentInjector.get(EnvironmentInjector);
  20997. // If the `parentInjector` is *not* an `EnvironmentInjector` - we need to create
  20998. // a new `ChainedInjector` with the following setup:
  20999. //
  21000. // - the provided `parentInjector` becomes a primary injector
  21001. // - an existing (real) `EnvironmentInjector` becomes a parent injector for
  21002. // a newly-created one, which contains extra providers
  21003. //
  21004. // So the final order in which injectors would be consulted in this case would look like this:
  21005. //
  21006. // 1. Provided `parentInjector`
  21007. // 2. Newly-created `EnvironmentInjector` with extra providers
  21008. // 3. `EnvironmentInjector` from the `parentInjector`
  21009. if (parentEnvInjector !== parentInjector) {
  21010. const envInjector = getOrCreateEnvironmentInjector(parentEnvInjector, tDetails, providers);
  21011. return new ChainedInjector(parentInjector, envInjector);
  21012. }
  21013. // The `parentInjector` is an instance of an `EnvironmentInjector`.
  21014. // No need for special handling, we can use `parentInjector` as a
  21015. // parent injector directly.
  21016. return getOrCreateEnvironmentInjector(parentInjector, tDetails, providers);
  21017. }
  21018. /** Rendering Helpers */
  21019. /**
  21020. * Transitions a defer block to the new state. Updates the necessary
  21021. * data structures and renders corresponding block.
  21022. *
  21023. * @param newState New state that should be applied to the defer block.
  21024. * @param tNode TNode that represents a defer block.
  21025. * @param lContainer Represents an instance of a defer block.
  21026. * @param skipTimerScheduling Indicates that `@loading` and `@placeholder` block
  21027. * should be rendered immediately, even if they have `after` or `minimum` config
  21028. * options setup. This flag to needed for testing APIs to transition defer block
  21029. * between states via `DeferFixture.render` method.
  21030. */
  21031. function renderDeferBlockState(newState, tNode, lContainer, skipTimerScheduling = false) {
  21032. const hostLView = lContainer[PARENT];
  21033. const hostTView = hostLView[TVIEW];
  21034. // Check if this view is not destroyed. Since the loading process was async,
  21035. // the view might end up being destroyed by the time rendering happens.
  21036. if (isDestroyed(hostLView))
  21037. return;
  21038. // Make sure this TNode belongs to TView that represents host LView.
  21039. ngDevMode && assertTNodeForLView(tNode, hostLView);
  21040. const lDetails = getLDeferBlockDetails(hostLView, tNode);
  21041. ngDevMode && assertDefined(lDetails, 'Expected a defer block state defined');
  21042. const currentState = lDetails[DEFER_BLOCK_STATE];
  21043. const ssrState = lDetails[SSR_BLOCK_STATE];
  21044. if (ssrState !== null && newState < ssrState) {
  21045. return; // trying to render a previous state, exit
  21046. }
  21047. if (isValidStateChange(currentState, newState) &&
  21048. isValidStateChange(lDetails[NEXT_DEFER_BLOCK_STATE] ?? -1, newState)) {
  21049. const tDetails = getTDeferBlockDetails(hostTView, tNode);
  21050. // Skips scheduling on the server since it can delay the server response.
  21051. const needsScheduling = !skipTimerScheduling &&
  21052. (typeof ngServerMode === 'undefined' || !ngServerMode) &&
  21053. (getLoadingBlockAfter(tDetails) !== null ||
  21054. getMinimumDurationForState(tDetails, DeferBlockState.Loading) !== null ||
  21055. getMinimumDurationForState(tDetails, DeferBlockState.Placeholder));
  21056. if (ngDevMode && needsScheduling) {
  21057. assertDefined(applyDeferBlockStateWithSchedulingImpl, 'Expected scheduling function to be defined');
  21058. }
  21059. const applyStateFn = needsScheduling
  21060. ? applyDeferBlockStateWithSchedulingImpl
  21061. : applyDeferBlockState;
  21062. try {
  21063. applyStateFn(newState, lDetails, lContainer, tNode, hostLView);
  21064. }
  21065. catch (error) {
  21066. handleError$1(hostLView, error);
  21067. }
  21068. }
  21069. }
  21070. function findMatchingDehydratedViewForDeferBlock(lContainer, lDetails) {
  21071. const dehydratedViewIx = lContainer[DEHYDRATED_VIEWS]?.findIndex((view) => view.data[DEFER_BLOCK_STATE$1] === lDetails[DEFER_BLOCK_STATE]) ?? -1;
  21072. const dehydratedView = dehydratedViewIx > -1 ? lContainer[DEHYDRATED_VIEWS][dehydratedViewIx] : null;
  21073. return { dehydratedView, dehydratedViewIx };
  21074. }
  21075. /**
  21076. * Applies changes to the DOM to reflect a given state.
  21077. */
  21078. function applyDeferBlockState(newState, lDetails, lContainer, tNode, hostLView) {
  21079. profiler(20 /* ProfilerEvent.DeferBlockStateStart */);
  21080. const stateTmplIndex = getTemplateIndexForState(newState, hostLView, tNode);
  21081. if (stateTmplIndex !== null) {
  21082. lDetails[DEFER_BLOCK_STATE] = newState;
  21083. const hostTView = hostLView[TVIEW];
  21084. const adjustedIndex = stateTmplIndex + HEADER_OFFSET;
  21085. // The TNode that represents a template that will activated in the defer block
  21086. const activeBlockTNode = getTNode(hostTView, adjustedIndex);
  21087. // There is only 1 view that can be present in an LContainer that
  21088. // represents a defer block, so always refer to the first one.
  21089. const viewIndex = 0;
  21090. removeLViewFromLContainer(lContainer, viewIndex);
  21091. let injector;
  21092. if (newState === DeferBlockState.Complete) {
  21093. // When we render a defer block in completed state, there might be
  21094. // newly loaded standalone components used within the block, which may
  21095. // import NgModules with providers. In order to make those providers
  21096. // available for components declared in that NgModule, we create an instance
  21097. // of an environment injector to host those providers and pass this injector
  21098. // to the logic that creates a view.
  21099. const tDetails = getTDeferBlockDetails(hostTView, tNode);
  21100. const providers = tDetails.providers;
  21101. if (providers && providers.length > 0) {
  21102. injector = createDeferBlockInjector(hostLView[INJECTOR], tDetails, providers);
  21103. }
  21104. }
  21105. const { dehydratedView, dehydratedViewIx } = findMatchingDehydratedViewForDeferBlock(lContainer, lDetails);
  21106. const embeddedLView = createAndRenderEmbeddedLView(hostLView, activeBlockTNode, null, {
  21107. injector,
  21108. dehydratedView,
  21109. });
  21110. addLViewToLContainer(lContainer, embeddedLView, viewIndex, shouldAddViewToDom(activeBlockTNode, dehydratedView));
  21111. markViewDirty(embeddedLView, 2 /* NotificationSource.DeferBlockStateUpdate */);
  21112. if (dehydratedViewIx > -1) {
  21113. // Erase dehydrated view info in a given LContainer, so that the view is not
  21114. // removed later by post-hydration cleanup process (which iterates over all
  21115. // dehydrated views in component tree). This clears only the dehydrated view
  21116. // that was found for this render, which in most cases will be the only view.
  21117. // In the case that there was control flow that changed, there may be either
  21118. // more than one or the views would not match up due to the server rendered
  21119. // content being a different branch of the control flow.
  21120. lContainer[DEHYDRATED_VIEWS]?.splice(dehydratedViewIx, 1);
  21121. }
  21122. if ((newState === DeferBlockState.Complete || newState === DeferBlockState.Error) &&
  21123. Array.isArray(lDetails[ON_COMPLETE_FNS])) {
  21124. for (const callback of lDetails[ON_COMPLETE_FNS]) {
  21125. callback();
  21126. }
  21127. lDetails[ON_COMPLETE_FNS] = null;
  21128. }
  21129. }
  21130. profiler(21 /* ProfilerEvent.DeferBlockStateEnd */);
  21131. }
  21132. /**
  21133. * Extends the `applyDeferBlockState` with timer-based scheduling.
  21134. * This function becomes available on a page if there are defer blocks
  21135. * that use `after` or `minimum` parameters in the `@loading` or
  21136. * `@placeholder` blocks.
  21137. */
  21138. function applyDeferBlockStateWithScheduling(newState, lDetails, lContainer, tNode, hostLView) {
  21139. const now = Date.now();
  21140. const hostTView = hostLView[TVIEW];
  21141. const tDetails = getTDeferBlockDetails(hostTView, tNode);
  21142. if (lDetails[STATE_IS_FROZEN_UNTIL] === null || lDetails[STATE_IS_FROZEN_UNTIL] <= now) {
  21143. lDetails[STATE_IS_FROZEN_UNTIL] = null;
  21144. const loadingAfter = getLoadingBlockAfter(tDetails);
  21145. const inLoadingAfterPhase = lDetails[LOADING_AFTER_CLEANUP_FN] !== null;
  21146. if (newState === DeferBlockState.Loading && loadingAfter !== null && !inLoadingAfterPhase) {
  21147. // Trying to render loading, but it has an `after` config,
  21148. // so schedule an update action after a timeout.
  21149. lDetails[NEXT_DEFER_BLOCK_STATE] = newState;
  21150. const cleanupFn = scheduleDeferBlockUpdate(loadingAfter, lDetails, tNode, lContainer, hostLView);
  21151. lDetails[LOADING_AFTER_CLEANUP_FN] = cleanupFn;
  21152. }
  21153. else {
  21154. // If we transition to a complete or an error state and there is a pending
  21155. // operation to render loading after a timeout - invoke a cleanup operation,
  21156. // which stops the timer.
  21157. if (newState > DeferBlockState.Loading && inLoadingAfterPhase) {
  21158. lDetails[LOADING_AFTER_CLEANUP_FN]();
  21159. lDetails[LOADING_AFTER_CLEANUP_FN] = null;
  21160. lDetails[NEXT_DEFER_BLOCK_STATE] = null;
  21161. }
  21162. applyDeferBlockState(newState, lDetails, lContainer, tNode, hostLView);
  21163. const duration = getMinimumDurationForState(tDetails, newState);
  21164. if (duration !== null) {
  21165. lDetails[STATE_IS_FROZEN_UNTIL] = now + duration;
  21166. scheduleDeferBlockUpdate(duration, lDetails, tNode, lContainer, hostLView);
  21167. }
  21168. }
  21169. }
  21170. else {
  21171. // We are still rendering the previous state.
  21172. // Update the `NEXT_DEFER_BLOCK_STATE`, which would be
  21173. // picked up once it's time to transition to the next state.
  21174. lDetails[NEXT_DEFER_BLOCK_STATE] = newState;
  21175. }
  21176. }
  21177. /**
  21178. * Schedules an update operation after a specified timeout.
  21179. */
  21180. function scheduleDeferBlockUpdate(timeout, lDetails, tNode, lContainer, hostLView) {
  21181. const callback = () => {
  21182. const nextState = lDetails[NEXT_DEFER_BLOCK_STATE];
  21183. lDetails[STATE_IS_FROZEN_UNTIL] = null;
  21184. lDetails[NEXT_DEFER_BLOCK_STATE] = null;
  21185. if (nextState !== null) {
  21186. renderDeferBlockState(nextState, tNode, lContainer);
  21187. }
  21188. };
  21189. return scheduleTimerTrigger(timeout, callback, hostLView[INJECTOR]);
  21190. }
  21191. /**
  21192. * Checks whether we can transition to the next state.
  21193. *
  21194. * We transition to the next state if the previous state was represented
  21195. * with a number that is less than the next state. For example, if the current
  21196. * state is "loading" (represented as `1`), we should not show a placeholder
  21197. * (represented as `0`), but we can show a completed state (represented as `2`)
  21198. * or an error state (represented as `3`).
  21199. */
  21200. function isValidStateChange(currentState, newState) {
  21201. return currentState < newState;
  21202. }
  21203. /** Utility function to render placeholder content (if present) */
  21204. function renderPlaceholder(lView, tNode) {
  21205. const lContainer = lView[tNode.index];
  21206. ngDevMode && assertLContainer(lContainer);
  21207. renderDeferBlockState(DeferBlockState.Placeholder, tNode, lContainer);
  21208. }
  21209. /**
  21210. * Subscribes to the "loading" Promise and renders corresponding defer sub-block,
  21211. * based on the loading results.
  21212. *
  21213. * @param lContainer Represents an instance of a defer block.
  21214. * @param tNode Represents defer block info shared across all instances.
  21215. */
  21216. function renderDeferStateAfterResourceLoading(tDetails, tNode, lContainer) {
  21217. ngDevMode &&
  21218. assertDefined(tDetails.loadingPromise, 'Expected loading Promise to exist on this defer block');
  21219. tDetails.loadingPromise.then(() => {
  21220. if (tDetails.loadingState === DeferDependenciesLoadingState.COMPLETE) {
  21221. ngDevMode && assertDeferredDependenciesLoaded(tDetails);
  21222. // Everything is loaded, show the primary block content
  21223. renderDeferBlockState(DeferBlockState.Complete, tNode, lContainer);
  21224. }
  21225. else if (tDetails.loadingState === DeferDependenciesLoadingState.FAILED) {
  21226. renderDeferBlockState(DeferBlockState.Error, tNode, lContainer);
  21227. }
  21228. });
  21229. }
  21230. /**
  21231. * Reference to the timer-based scheduler implementation of defer block state
  21232. * rendering method. It's used to make timer-based scheduling tree-shakable.
  21233. * If `minimum` or `after` parameters are used, compiler generates an extra
  21234. * argument for the `ɵɵdefer` instruction, which references a timer-based
  21235. * implementation.
  21236. */
  21237. let applyDeferBlockStateWithSchedulingImpl = null;
  21238. /**
  21239. * Enables timer-related scheduling if `after` or `minimum` parameters are setup
  21240. * on the `@loading` or `@placeholder` blocks.
  21241. */
  21242. function ɵɵdeferEnableTimerScheduling(tView, tDetails, placeholderConfigIndex, loadingConfigIndex) {
  21243. const tViewConsts = tView.consts;
  21244. if (placeholderConfigIndex != null) {
  21245. tDetails.placeholderBlockConfig = getConstant(tViewConsts, placeholderConfigIndex);
  21246. }
  21247. if (loadingConfigIndex != null) {
  21248. tDetails.loadingBlockConfig = getConstant(tViewConsts, loadingConfigIndex);
  21249. }
  21250. // Enable implementation that supports timer-based scheduling.
  21251. if (applyDeferBlockStateWithSchedulingImpl === null) {
  21252. applyDeferBlockStateWithSchedulingImpl = applyDeferBlockStateWithScheduling;
  21253. }
  21254. }
  21255. /**
  21256. * The name of a field that Angular monkey-patches onto a component
  21257. * class to store a function that loads defer-loadable dependencies
  21258. * and applies metadata to a class.
  21259. */
  21260. const ASYNC_COMPONENT_METADATA_FN = '__ngAsyncComponentMetadataFn__';
  21261. /**
  21262. * If a given component has unresolved async metadata - returns a reference
  21263. * to a function that applies component metadata after resolving defer-loadable
  21264. * dependencies. Otherwise - this function returns `null`.
  21265. */
  21266. function getAsyncClassMetadataFn(type) {
  21267. const componentClass = type; // cast to `any`, so that we can read a monkey-patched field
  21268. return componentClass[ASYNC_COMPONENT_METADATA_FN] ?? null;
  21269. }
  21270. /**
  21271. * Handles the process of applying metadata info to a component class in case
  21272. * component template has defer blocks (thus some dependencies became deferrable).
  21273. *
  21274. * @param type Component class where metadata should be added
  21275. * @param dependencyLoaderFn Function that loads dependencies
  21276. * @param metadataSetterFn Function that forms a scope in which the `setClassMetadata` is invoked
  21277. */
  21278. function setClassMetadataAsync(type, dependencyLoaderFn, metadataSetterFn) {
  21279. const componentClass = type; // cast to `any`, so that we can monkey-patch it
  21280. componentClass[ASYNC_COMPONENT_METADATA_FN] = () => Promise.all(dependencyLoaderFn()).then((dependencies) => {
  21281. metadataSetterFn(...dependencies);
  21282. // Metadata is now set, reset field value to indicate that this component
  21283. // can by used/compiled synchronously.
  21284. componentClass[ASYNC_COMPONENT_METADATA_FN] = null;
  21285. return dependencies;
  21286. });
  21287. return componentClass[ASYNC_COMPONENT_METADATA_FN];
  21288. }
  21289. /**
  21290. * Adds decorator, constructor, and property metadata to a given type via static metadata fields
  21291. * on the type.
  21292. *
  21293. * These metadata fields can later be read with Angular's `ReflectionCapabilities` API.
  21294. *
  21295. * Calls to `setClassMetadata` can be guarded by ngDevMode, resulting in the metadata assignments
  21296. * being tree-shaken away during production builds.
  21297. */
  21298. function setClassMetadata(type, decorators, ctorParameters, propDecorators) {
  21299. return noSideEffects(() => {
  21300. const clazz = type;
  21301. if (decorators !== null) {
  21302. if (clazz.hasOwnProperty('decorators') && clazz.decorators !== undefined) {
  21303. clazz.decorators.push(...decorators);
  21304. }
  21305. else {
  21306. clazz.decorators = decorators;
  21307. }
  21308. }
  21309. if (ctorParameters !== null) {
  21310. // Rather than merging, clobber the existing parameters. If other projects exist which
  21311. // use tsickle-style annotations and reflect over them in the same way, this could
  21312. // cause issues, but that is vanishingly unlikely.
  21313. clazz.ctorParameters = ctorParameters;
  21314. }
  21315. if (propDecorators !== null) {
  21316. // The property decorator objects are merged as it is possible different fields have
  21317. // different decorator types. Decorators on individual fields are not merged, as it's
  21318. // also incredibly unlikely that a field will be decorated both with an Angular
  21319. // decorator and a non-Angular decorator that's also been downleveled.
  21320. if (clazz.hasOwnProperty('propDecorators') && clazz.propDecorators !== undefined) {
  21321. clazz.propDecorators = { ...clazz.propDecorators, ...propDecorators };
  21322. }
  21323. else {
  21324. clazz.propDecorators = propDecorators;
  21325. }
  21326. }
  21327. });
  21328. }
  21329. class Console {
  21330. log(message) {
  21331. // tslint:disable-next-line:no-console
  21332. console.log(message);
  21333. }
  21334. // Note: for reporting errors use `DOM.logError()` as it is platform specific
  21335. warn(message) {
  21336. console.warn(message);
  21337. }
  21338. static ɵfac = function Console_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || Console)(); };
  21339. static ɵprov = /*@__PURE__*/ ɵɵdefineInjectable({ token: Console, factory: Console.ɵfac, providedIn: 'platform' });
  21340. }
  21341. (() => { (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(Console, [{
  21342. type: Injectable,
  21343. args: [{ providedIn: 'platform' }]
  21344. }], null, null); })();
  21345. /**
  21346. * These are the data structures that our framework injector profiler will fill with data in order
  21347. * to support DI debugging APIs.
  21348. *
  21349. * resolverToTokenToDependencies: Maps an injector to a Map of tokens to an Array of
  21350. * dependencies. Injector -> Token -> Dependencies This is used to support the
  21351. * getDependenciesFromInjectable API, which takes in an injector and a token and returns it's
  21352. * dependencies.
  21353. *
  21354. * resolverToProviders: Maps a DI resolver (an Injector or a TNode) to the providers configured
  21355. * within it This is used to support the getInjectorProviders API, which takes in an injector and
  21356. * returns the providers that it was configured with. Note that for the element injector case we
  21357. * use the TNode instead of the LView as the DI resolver. This is because the registration of
  21358. * providers happens only once per type of TNode. If an injector is created with an identical TNode,
  21359. * the providers for that injector will not be reconfigured.
  21360. *
  21361. * standaloneInjectorToComponent: Maps the injector of a standalone component to the standalone
  21362. * component that it is associated with. Used in the getInjectorProviders API, specificially in the
  21363. * discovery of import paths for each provider. This is necessary because the imports array of a
  21364. * standalone component is processed and configured in its standalone injector, but exists within
  21365. * the component's definition. Because getInjectorProviders takes in an injector, if that injector
  21366. * is the injector of a standalone component, we need to be able to discover the place where the
  21367. * imports array is located (the component) in order to flatten the imports array within it to
  21368. * discover all of it's providers.
  21369. *
  21370. *
  21371. * All of these data structures are instantiated with WeakMaps. This will ensure that the presence
  21372. * of any object in the keys of these maps does not prevent the garbage collector from collecting
  21373. * those objects. Because of this property of WeakMaps, these data structures will never be the
  21374. * source of a memory leak.
  21375. *
  21376. * An example of this advantage: When components are destroyed, we don't need to do
  21377. * any additional work to remove that component from our mappings.
  21378. *
  21379. */
  21380. class DIDebugData {
  21381. resolverToTokenToDependencies = new WeakMap();
  21382. resolverToProviders = new WeakMap();
  21383. resolverToEffects = new WeakMap();
  21384. standaloneInjectorToComponent = new WeakMap();
  21385. reset() {
  21386. this.resolverToTokenToDependencies = new WeakMap();
  21387. this.resolverToProviders = new WeakMap();
  21388. this.standaloneInjectorToComponent = new WeakMap();
  21389. }
  21390. }
  21391. let frameworkDIDebugData = new DIDebugData();
  21392. function getFrameworkDIDebugData() {
  21393. return frameworkDIDebugData;
  21394. }
  21395. /**
  21396. * Initalize default handling of injector events. This handling parses events
  21397. * as they are emitted and constructs the data structures necessary to support
  21398. * some of debug APIs.
  21399. *
  21400. * See handleInjectEvent, handleCreateEvent and handleProviderConfiguredEvent
  21401. * for descriptions of each handler
  21402. *
  21403. * Supported APIs:
  21404. * - getDependenciesFromInjectable
  21405. * - getInjectorProviders
  21406. */
  21407. function setupFrameworkInjectorProfiler() {
  21408. frameworkDIDebugData.reset();
  21409. setInjectorProfiler((injectorProfilerEvent) => handleInjectorProfilerEvent(injectorProfilerEvent));
  21410. }
  21411. function handleInjectorProfilerEvent(injectorProfilerEvent) {
  21412. const { context, type } = injectorProfilerEvent;
  21413. if (type === 0 /* InjectorProfilerEventType.Inject */) {
  21414. handleInjectEvent(context, injectorProfilerEvent.service);
  21415. }
  21416. else if (type === 1 /* InjectorProfilerEventType.InstanceCreatedByInjector */) {
  21417. handleInstanceCreatedByInjectorEvent(context, injectorProfilerEvent.instance);
  21418. }
  21419. else if (type === 2 /* InjectorProfilerEventType.ProviderConfigured */) {
  21420. handleProviderConfiguredEvent(context, injectorProfilerEvent.providerRecord);
  21421. }
  21422. else if (type === 3 /* InjectorProfilerEventType.EffectCreated */) {
  21423. handleEffectCreatedEvent(context, injectorProfilerEvent.effect);
  21424. }
  21425. }
  21426. function handleEffectCreatedEvent(context, effect) {
  21427. const diResolver = getDIResolver(context.injector);
  21428. if (diResolver === null) {
  21429. throwError('An EffectCreated event must be run within an injection context.');
  21430. }
  21431. const { resolverToEffects } = frameworkDIDebugData;
  21432. if (!resolverToEffects.has(diResolver)) {
  21433. resolverToEffects.set(diResolver, []);
  21434. }
  21435. resolverToEffects.get(diResolver).push(effect);
  21436. }
  21437. /**
  21438. *
  21439. * Stores the injected service in frameworkDIDebugData.resolverToTokenToDependencies
  21440. * based on it's injector and token.
  21441. *
  21442. * @param context InjectorProfilerContext the injection context that this event occurred in.
  21443. * @param data InjectedService the service associated with this inject event.
  21444. *
  21445. */
  21446. function handleInjectEvent(context, data) {
  21447. const diResolver = getDIResolver(context.injector);
  21448. if (diResolver === null) {
  21449. throwError('An Inject event must be run within an injection context.');
  21450. }
  21451. const diResolverToInstantiatedToken = frameworkDIDebugData.resolverToTokenToDependencies;
  21452. if (!diResolverToInstantiatedToken.has(diResolver)) {
  21453. diResolverToInstantiatedToken.set(diResolver, new WeakMap());
  21454. }
  21455. // if token is a primitive type, ignore this event. We do this because we cannot keep track of
  21456. // non-primitive tokens in WeakMaps since they are not garbage collectable.
  21457. if (!canBeHeldWeakly(context.token)) {
  21458. return;
  21459. }
  21460. const instantiatedTokenToDependencies = diResolverToInstantiatedToken.get(diResolver);
  21461. if (!instantiatedTokenToDependencies.has(context.token)) {
  21462. instantiatedTokenToDependencies.set(context.token, []);
  21463. }
  21464. const { token, value, flags } = data;
  21465. assertDefined(context.token, 'Injector profiler context token is undefined.');
  21466. const dependencies = instantiatedTokenToDependencies.get(context.token);
  21467. assertDefined(dependencies, 'Could not resolve dependencies for token.');
  21468. if (context.injector instanceof NodeInjector) {
  21469. dependencies.push({ token, value, flags, injectedIn: getNodeInjectorContext(context.injector) });
  21470. }
  21471. else {
  21472. dependencies.push({ token, value, flags });
  21473. }
  21474. }
  21475. /**
  21476. *
  21477. * Returns the LView and TNode associated with a NodeInjector. Returns undefined if the injector
  21478. * is not a NodeInjector.
  21479. *
  21480. * @param injector
  21481. * @returns {lView: LView, tNode: TNode}|undefined
  21482. */
  21483. function getNodeInjectorContext(injector) {
  21484. if (!(injector instanceof NodeInjector)) {
  21485. throwError('getNodeInjectorContext must be called with a NodeInjector');
  21486. }
  21487. const lView = getNodeInjectorLView(injector);
  21488. const tNode = getNodeInjectorTNode(injector);
  21489. if (tNode === null) {
  21490. return;
  21491. }
  21492. assertTNodeForLView(tNode, lView);
  21493. return { lView, tNode };
  21494. }
  21495. /**
  21496. *
  21497. * If the created instance is an instance of a standalone component, maps the injector to that
  21498. * standalone component in frameworkDIDebugData.standaloneInjectorToComponent
  21499. *
  21500. * @param context InjectorProfilerContext the injection context that this event occurred in.
  21501. * @param data InjectorCreatedInstance an object containing the instance that was just created
  21502. *
  21503. */
  21504. function handleInstanceCreatedByInjectorEvent(context, data) {
  21505. const { value } = data;
  21506. if (getDIResolver(context.injector) === null) {
  21507. throwError('An InjectorCreatedInstance event must be run within an injection context.');
  21508. }
  21509. // if our value is an instance of a standalone component, map the injector of that standalone
  21510. // component to the component class. Otherwise, this event is a noop.
  21511. let standaloneComponent = undefined;
  21512. if (typeof value === 'object') {
  21513. standaloneComponent = value?.constructor;
  21514. }
  21515. // We want to also cover if `standaloneComponent === null` in addition to `undefined`
  21516. if (standaloneComponent == undefined || !isStandaloneComponent(standaloneComponent)) {
  21517. return;
  21518. }
  21519. const environmentInjector = context.injector.get(EnvironmentInjector, null, { optional: true });
  21520. // Standalone components should have an environment injector. If one cannot be
  21521. // found we may be in a test case for low level functionality that did not explicitly
  21522. // setup this injector. In those cases, we simply ignore this event.
  21523. if (environmentInjector === null) {
  21524. return;
  21525. }
  21526. const { standaloneInjectorToComponent } = frameworkDIDebugData;
  21527. // If our injector has already been mapped, as is the case
  21528. // when a standalone component imports another standalone component,
  21529. // we consider the original component (the component doing the importing)
  21530. // as the component connected to our injector.
  21531. if (standaloneInjectorToComponent.has(environmentInjector)) {
  21532. return;
  21533. }
  21534. // If our injector hasn't been mapped, then we map it to the standalone component
  21535. standaloneInjectorToComponent.set(environmentInjector, standaloneComponent);
  21536. }
  21537. function isStandaloneComponent(value) {
  21538. const def = getComponentDef(value);
  21539. return !!def?.standalone;
  21540. }
  21541. /**
  21542. *
  21543. * Stores the emitted ProviderRecords from the InjectorProfilerEventType.ProviderConfigured
  21544. * event in frameworkDIDebugData.resolverToProviders
  21545. *
  21546. * @param context InjectorProfilerContext the injection context that this event occurred in.
  21547. * @param data ProviderRecord an object containing the instance that was just created
  21548. *
  21549. */
  21550. function handleProviderConfiguredEvent(context, data) {
  21551. const { resolverToProviders } = frameworkDIDebugData;
  21552. let diResolver;
  21553. if (context?.injector instanceof NodeInjector) {
  21554. diResolver = getNodeInjectorTNode(context.injector);
  21555. }
  21556. else {
  21557. diResolver = context.injector;
  21558. }
  21559. if (diResolver === null) {
  21560. throwError('A ProviderConfigured event must be run within an injection context.');
  21561. }
  21562. if (!resolverToProviders.has(diResolver)) {
  21563. resolverToProviders.set(diResolver, []);
  21564. }
  21565. resolverToProviders.get(diResolver).push(data);
  21566. }
  21567. function getDIResolver(injector) {
  21568. let diResolver = null;
  21569. if (injector === undefined) {
  21570. return diResolver;
  21571. }
  21572. // We use the LView as the diResolver for NodeInjectors because they
  21573. // do not persist anywhere in the framework. They are simply wrappers around an LView and a TNode
  21574. // that do persist. Because of this, we rely on the LView of the NodeInjector in order to use
  21575. // as a concrete key to represent this injector. If we get the same LView back later, we know
  21576. // we're looking at the same injector.
  21577. if (injector instanceof NodeInjector) {
  21578. diResolver = getNodeInjectorLView(injector);
  21579. }
  21580. // Other injectors can be used a keys for a map because their instances
  21581. // persist
  21582. else {
  21583. diResolver = injector;
  21584. }
  21585. return diResolver;
  21586. }
  21587. // inspired by
  21588. // https://tc39.es/ecma262/multipage/executable-code-and-execution-contexts.html#sec-canbeheldweakly
  21589. function canBeHeldWeakly(value) {
  21590. // we check for value !== null here because typeof null === 'object
  21591. return (value !== null &&
  21592. (typeof value === 'object' || typeof value === 'function' || typeof value === 'symbol'));
  21593. }
  21594. /**
  21595. * Marks a component for check (in case of OnPush components) and synchronously
  21596. * performs change detection on the application this component belongs to.
  21597. *
  21598. * @param component Component to {@link /api/core/ChangeDetectorRef#markForCheck mark for check}
  21599. *
  21600. * @publicApi
  21601. */
  21602. function applyChanges(component) {
  21603. ngDevMode && assertDefined(component, 'component');
  21604. markViewDirty(getComponentViewByInstance(component), 3 /* NotificationSource.DebugApplyChanges */);
  21605. getRootComponents(component).forEach((rootComponent) => detectChanges(rootComponent));
  21606. }
  21607. /**
  21608. * Synchronously perform change detection on a component (and possibly its sub-components).
  21609. *
  21610. * This function triggers change detection in a synchronous way on a component.
  21611. *
  21612. * @param component The component which the change detection should be performed on.
  21613. */
  21614. function detectChanges(component) {
  21615. const view = getComponentViewByInstance(component);
  21616. view[FLAGS] |= 1024 /* LViewFlags.RefreshView */;
  21617. detectChangesInternal(view);
  21618. }
  21619. /**
  21620. * Retrieves all defer blocks in a given LView.
  21621. *
  21622. * @param lView lView with defer blocks
  21623. * @param deferBlocks defer block aggregator array
  21624. */
  21625. function getDeferBlocks$1(lView, deferBlocks) {
  21626. const tView = lView[TVIEW];
  21627. for (let i = HEADER_OFFSET; i < tView.bindingStartIndex; i++) {
  21628. if (isLContainer(lView[i])) {
  21629. const lContainer = lView[i];
  21630. // An LContainer may represent an instance of a defer block, in which case
  21631. // we store it as a result. Otherwise, keep iterating over LContainer views and
  21632. // look for defer blocks.
  21633. const isLast = i === tView.bindingStartIndex - 1;
  21634. if (!isLast) {
  21635. const tNode = tView.data[i];
  21636. const tDetails = getTDeferBlockDetails(tView, tNode);
  21637. if (isTDeferBlockDetails(tDetails)) {
  21638. deferBlocks.push({ lContainer, lView, tNode, tDetails });
  21639. // This LContainer represents a defer block, so we exit
  21640. // this iteration and don't inspect views in this LContainer.
  21641. continue;
  21642. }
  21643. }
  21644. for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
  21645. getDeferBlocks$1(lContainer[i], deferBlocks);
  21646. }
  21647. }
  21648. else if (isLView(lView[i])) {
  21649. // This is a component, enter the `getDeferBlocks` recursively.
  21650. getDeferBlocks$1(lView[i], deferBlocks);
  21651. }
  21652. }
  21653. }
  21654. /*!
  21655. * @license
  21656. * Copyright Google LLC All Rights Reserved.
  21657. *
  21658. * Use of this source code is governed by an MIT-style license that can be
  21659. * found in the LICENSE file at https://angular.dev/license
  21660. */
  21661. /**
  21662. * Gets all of the `@defer` blocks that are present inside the specified DOM node.
  21663. * @param node Node in which to look for `@defer` blocks.
  21664. *
  21665. * @publicApi
  21666. */
  21667. function getDeferBlocks(node) {
  21668. const results = [];
  21669. const lView = getLContext(node)?.lView;
  21670. if (lView) {
  21671. findDeferBlocks(node, lView, results);
  21672. }
  21673. return results;
  21674. }
  21675. /**
  21676. * Finds all the `@defer` blocks inside a specific node and view.
  21677. * @param node Node in which to search for blocks.
  21678. * @param lView View within the node in which to search for blocks.
  21679. * @param results Array to which to add blocks once they're found.
  21680. */
  21681. function findDeferBlocks(node, lView, results) {
  21682. const registry = lView[INJECTOR].get(DEHYDRATED_BLOCK_REGISTRY, null, { optional: true });
  21683. const blocks = [];
  21684. getDeferBlocks$1(lView, blocks);
  21685. for (const details of blocks) {
  21686. const native = getNativeByTNode(details.tNode, details.lView);
  21687. const lDetails = getLDeferBlockDetails(details.lView, details.tNode);
  21688. // The LView from `getLContext` might be the view the element is placed in.
  21689. // Filter out defer blocks that aren't inside the specified root node.
  21690. if (!node.contains(native)) {
  21691. continue;
  21692. }
  21693. const tDetails = details.tDetails;
  21694. const renderedLView = getRendererLView(details);
  21695. const rootNodes = [];
  21696. if (renderedLView !== null) {
  21697. collectNativeNodes(renderedLView[TVIEW], renderedLView, renderedLView[TVIEW].firstChild, rootNodes);
  21698. }
  21699. const data = {
  21700. state: stringifyState(lDetails[DEFER_BLOCK_STATE]),
  21701. incrementalHydrationState: inferHydrationState(tDetails, lDetails, registry),
  21702. hasErrorBlock: tDetails.errorTmplIndex !== null,
  21703. loadingBlock: {
  21704. exists: tDetails.loadingTmplIndex !== null,
  21705. minimumTime: tDetails.loadingBlockConfig?.[MINIMUM_SLOT] ?? null,
  21706. afterTime: tDetails.loadingBlockConfig?.[LOADING_AFTER_SLOT] ?? null,
  21707. },
  21708. placeholderBlock: {
  21709. exists: tDetails.placeholderTmplIndex !== null,
  21710. minimumTime: tDetails.placeholderBlockConfig?.[MINIMUM_SLOT] ?? null,
  21711. },
  21712. triggers: tDetails.debug?.triggers ? Array.from(tDetails.debug.triggers).sort() : [],
  21713. rootNodes,
  21714. };
  21715. results.push(data);
  21716. // `getDeferBlocks` does not resolve nested defer blocks so we have to recurse manually.
  21717. if (renderedLView !== null) {
  21718. findDeferBlocks(node, renderedLView, results);
  21719. }
  21720. }
  21721. }
  21722. /**
  21723. * Turns the `DeferBlockState` into a string which is more readable than the enum form.
  21724. *
  21725. * @param lDetails Information about the
  21726. * @returns
  21727. */
  21728. function stringifyState(state) {
  21729. switch (state) {
  21730. case DeferBlockState.Complete:
  21731. return 'complete';
  21732. case DeferBlockState.Loading:
  21733. return 'loading';
  21734. case DeferBlockState.Placeholder:
  21735. return 'placeholder';
  21736. case DeferBlockState.Error:
  21737. return 'error';
  21738. case DeferBlockInternalState.Initial:
  21739. return 'initial';
  21740. default:
  21741. throw new Error(`Unrecognized state ${state}`);
  21742. }
  21743. }
  21744. /**
  21745. * Infers the hydration state of a specific defer block.
  21746. * @param tDetails Static defer block information.
  21747. * @param lDetails Instance defer block information.
  21748. * @param registry Registry coordinating the hydration of defer blocks.
  21749. */
  21750. function inferHydrationState(tDetails, lDetails, registry) {
  21751. if (registry === null ||
  21752. lDetails[SSR_UNIQUE_ID] === null ||
  21753. tDetails.hydrateTriggers === null ||
  21754. tDetails.hydrateTriggers.has(7 /* DeferBlockTrigger.Never */)) {
  21755. return 'not-configured';
  21756. }
  21757. return registry.has(lDetails[SSR_UNIQUE_ID]) ? 'dehydrated' : 'hydrated';
  21758. }
  21759. /**
  21760. * Gets the current LView that is rendered out in a defer block.
  21761. * @param details Instance information about the block.
  21762. */
  21763. function getRendererLView(details) {
  21764. // Defer block containers can only ever contain one view.
  21765. // If they're empty, it means that nothing is rendered.
  21766. if (details.lContainer.length <= CONTAINER_HEADER_OFFSET) {
  21767. return null;
  21768. }
  21769. const lView = details.lContainer[CONTAINER_HEADER_OFFSET];
  21770. ngDevMode && assertLView(lView);
  21771. return lView;
  21772. }
  21773. /**
  21774. * Discovers the dependencies of an injectable instance. Provides DI information about each
  21775. * dependency that the injectable was instantiated with, including where they were provided from.
  21776. *
  21777. * @param injector An injector instance
  21778. * @param token a DI token that was constructed by the given injector instance
  21779. * @returns an object that contains the created instance of token as well as all of the dependencies
  21780. * that it was instantiated with OR undefined if the token was not created within the given
  21781. * injector.
  21782. */
  21783. function getDependenciesFromInjectable(injector, token) {
  21784. // First we check to see if the token given maps to an actual instance in the injector given.
  21785. // We use `self: true` because we only want to look at the injector we were given.
  21786. // We use `optional: true` because it's possible that the token we were given was never
  21787. // constructed by the injector we were given.
  21788. const instance = injector.get(token, null, { self: true, optional: true });
  21789. if (instance === null) {
  21790. throw new Error(`Unable to determine instance of ${token} in given injector`);
  21791. }
  21792. const unformattedDependencies = getDependenciesForTokenInInjector(token, injector);
  21793. const resolutionPath = getInjectorResolutionPath(injector);
  21794. const dependencies = unformattedDependencies.map((dep) => {
  21795. // injectedIn contains private fields, so we omit it from the response
  21796. const formattedDependency = {
  21797. value: dep.value,
  21798. };
  21799. // convert injection flags to booleans
  21800. const flags = dep.flags;
  21801. formattedDependency.flags = {
  21802. optional: (8 /* InternalInjectFlags.Optional */ & flags) === 8 /* InternalInjectFlags.Optional */,
  21803. host: (1 /* InternalInjectFlags.Host */ & flags) === 1 /* InternalInjectFlags.Host */,
  21804. self: (2 /* InternalInjectFlags.Self */ & flags) === 2 /* InternalInjectFlags.Self */,
  21805. skipSelf: (4 /* InternalInjectFlags.SkipSelf */ & flags) === 4 /* InternalInjectFlags.SkipSelf */,
  21806. };
  21807. // find the injector that provided the dependency
  21808. for (let i = 0; i < resolutionPath.length; i++) {
  21809. const injectorToCheck = resolutionPath[i];
  21810. // if skipSelf is true we skip the first injector
  21811. if (i === 0 && formattedDependency.flags.skipSelf) {
  21812. continue;
  21813. }
  21814. // host only applies to NodeInjectors
  21815. if (formattedDependency.flags.host && injectorToCheck instanceof EnvironmentInjector) {
  21816. break;
  21817. }
  21818. const instance = injectorToCheck.get(dep.token, null, {
  21819. self: true,
  21820. optional: true,
  21821. });
  21822. if (instance !== null) {
  21823. // if host flag is true we double check that we can get the service from the first element
  21824. // in the resolution path by using the host flag. This is done to make sure that we've found
  21825. // the correct providing injector, and not a node injector that is connected to our path via
  21826. // a router outlet.
  21827. if (formattedDependency.flags.host) {
  21828. const firstInjector = resolutionPath[0];
  21829. const lookupFromFirstInjector = firstInjector.get(dep.token, null, {
  21830. ...formattedDependency.flags,
  21831. optional: true,
  21832. });
  21833. if (lookupFromFirstInjector !== null) {
  21834. formattedDependency.providedIn = injectorToCheck;
  21835. }
  21836. break;
  21837. }
  21838. formattedDependency.providedIn = injectorToCheck;
  21839. break;
  21840. }
  21841. // if self is true we stop after the first injector
  21842. if (i === 0 && formattedDependency.flags.self) {
  21843. break;
  21844. }
  21845. }
  21846. if (dep.token)
  21847. formattedDependency.token = dep.token;
  21848. return formattedDependency;
  21849. });
  21850. return { instance, dependencies };
  21851. }
  21852. function getDependenciesForTokenInInjector(token, injector) {
  21853. const { resolverToTokenToDependencies } = getFrameworkDIDebugData();
  21854. if (!(injector instanceof NodeInjector)) {
  21855. return resolverToTokenToDependencies.get(injector)?.get?.(token) ?? [];
  21856. }
  21857. const lView = getNodeInjectorLView(injector);
  21858. const tokenDependencyMap = resolverToTokenToDependencies.get(lView);
  21859. const dependencies = tokenDependencyMap?.get(token) ?? [];
  21860. // In the NodeInjector case, all injections for every node are stored in the same lView.
  21861. // We use the injectedIn field of the dependency to filter out the dependencies that
  21862. // do not come from the same node as the instance we're looking at.
  21863. return dependencies.filter((dependency) => {
  21864. const dependencyNode = dependency.injectedIn?.tNode;
  21865. if (dependencyNode === undefined) {
  21866. return false;
  21867. }
  21868. const instanceNode = getNodeInjectorTNode(injector);
  21869. assertTNode(dependencyNode);
  21870. assertTNode(instanceNode);
  21871. return dependencyNode === instanceNode;
  21872. });
  21873. }
  21874. /**
  21875. * Gets the class associated with an injector that contains a provider `imports` array in it's
  21876. * definition
  21877. *
  21878. * For Module Injectors this returns the NgModule constructor.
  21879. *
  21880. * For Standalone injectors this returns the standalone component constructor.
  21881. *
  21882. * @param injector Injector an injector instance
  21883. * @returns the constructor where the `imports` array that configures this injector is located
  21884. */
  21885. function getProviderImportsContainer(injector) {
  21886. const { standaloneInjectorToComponent } = getFrameworkDIDebugData();
  21887. // standalone components configure providers through a component def, so we have to
  21888. // use the standalone component associated with this injector if Injector represents
  21889. // a standalone components EnvironmentInjector
  21890. if (standaloneInjectorToComponent.has(injector)) {
  21891. return standaloneInjectorToComponent.get(injector);
  21892. }
  21893. // Module injectors configure providers through their NgModule def, so we use the
  21894. // injector to lookup its NgModuleRef and through that grab its instance
  21895. const defTypeRef = injector.get(NgModuleRef$1, null, { self: true, optional: true });
  21896. // If we can't find an associated imports container, return null.
  21897. // This could be the case if this function is called with an R3Injector that does not represent
  21898. // a standalone component or NgModule.
  21899. if (defTypeRef === null) {
  21900. return null;
  21901. }
  21902. // In standalone applications, the root environment injector created by bootstrapApplication
  21903. // may have no associated "instance".
  21904. if (defTypeRef.instance === null) {
  21905. return null;
  21906. }
  21907. return defTypeRef.instance.constructor;
  21908. }
  21909. /**
  21910. * Gets the providers configured on a NodeInjector
  21911. *
  21912. * @param injector A NodeInjector instance
  21913. * @returns ProviderRecord[] an array of objects representing the providers configured on this
  21914. * injector
  21915. */
  21916. function getNodeInjectorProviders(injector) {
  21917. const diResolver = getNodeInjectorTNode(injector);
  21918. const { resolverToProviders } = getFrameworkDIDebugData();
  21919. return resolverToProviders.get(diResolver) ?? [];
  21920. }
  21921. /**
  21922. * Gets a mapping of providers configured on an injector to their import paths
  21923. *
  21924. * ModuleA -> imports ModuleB
  21925. * ModuleB -> imports ModuleC
  21926. * ModuleB -> provides MyServiceA
  21927. * ModuleC -> provides MyServiceB
  21928. *
  21929. * getProviderImportPaths(ModuleA)
  21930. * > Map(2) {
  21931. * MyServiceA => [ModuleA, ModuleB]
  21932. * MyServiceB => [ModuleA, ModuleB, ModuleC]
  21933. * }
  21934. *
  21935. * @param providerImportsContainer constructor of class that contains an `imports` array in it's
  21936. * definition
  21937. * @returns A Map object that maps providers to an array of constructors representing it's import
  21938. * path
  21939. *
  21940. */
  21941. function getProviderImportPaths(providerImportsContainer) {
  21942. const providerToPath = new Map();
  21943. const visitedContainers = new Set();
  21944. const visitor = walkProviderTreeToDiscoverImportPaths(providerToPath, visitedContainers);
  21945. walkProviderTree(providerImportsContainer, visitor, [], new Set());
  21946. return providerToPath;
  21947. }
  21948. /**
  21949. *
  21950. * Higher order function that returns a visitor for WalkProviderTree
  21951. *
  21952. * Takes in a Map and Set to keep track of the providers and containers
  21953. * visited, so that we can discover the import paths of these providers
  21954. * during the traversal.
  21955. *
  21956. * This visitor takes advantage of the fact that walkProviderTree performs a
  21957. * postorder traversal of the provider tree for the passed in container. Because postorder
  21958. * traversal recursively processes subtrees from leaf nodes until the traversal reaches the root,
  21959. * we write a visitor that constructs provider import paths in reverse.
  21960. *
  21961. *
  21962. * We use the visitedContainers set defined outside this visitor
  21963. * because we want to run some logic only once for
  21964. * each container in the tree. That logic can be described as:
  21965. *
  21966. *
  21967. * 1. for each discovered_provider and discovered_path in the incomplete provider paths we've
  21968. * already discovered
  21969. * 2. get the first container in discovered_path
  21970. * 3. if that first container is in the imports array of the container we're visiting
  21971. * Then the container we're visiting is also in the import path of discovered_provider, so we
  21972. * unshift discovered_path with the container we're currently visiting
  21973. *
  21974. *
  21975. * Example Run:
  21976. * ```
  21977. * ┌──────────┐
  21978. * │containerA│
  21979. * ┌─imports-─┤ ├──imports─┐
  21980. * │ │ provA │ │
  21981. * │ │ provB │ │
  21982. * │ └──────────┘ │
  21983. * │ │
  21984. * ┌▼─────────┐ ┌────────▼─┐
  21985. * │containerB│ │containerC│
  21986. * │ │ │ │
  21987. * │ provD │ │ provF │
  21988. * │ provE │ │ provG │
  21989. * └──────────┘ └──────────┘
  21990. * ```
  21991. *
  21992. * Each step of the traversal,
  21993. *
  21994. * ```
  21995. * visitor(provD, containerB)
  21996. * providerToPath === Map { provD => [containerB] }
  21997. * visitedContainers === Set { containerB }
  21998. *
  21999. * visitor(provE, containerB)
  22000. * providerToPath === Map { provD => [containerB], provE => [containerB] }
  22001. * visitedContainers === Set { containerB }
  22002. *
  22003. * visitor(provF, containerC)
  22004. * providerToPath === Map { provD => [containerB], provE => [containerB], provF => [containerC] }
  22005. * visitedContainers === Set { containerB, containerC }
  22006. *
  22007. * visitor(provG, containerC)
  22008. * providerToPath === Map {
  22009. * provD => [containerB], provE => [containerB], provF => [containerC], provG => [containerC]
  22010. * }
  22011. * visitedContainers === Set { containerB, containerC }
  22012. *
  22013. * visitor(provA, containerA)
  22014. * providerToPath === Map {
  22015. * provD => [containerA, containerB],
  22016. * provE => [containerA, containerB],
  22017. * provF => [containerA, containerC],
  22018. * provG => [containerA, containerC],
  22019. * provA => [containerA]
  22020. * }
  22021. * visitedContainers === Set { containerB, containerC, containerA }
  22022. *
  22023. * visitor(provB, containerA)
  22024. * providerToPath === Map {
  22025. * provD => [containerA, containerB],
  22026. * provE => [containerA, containerB],
  22027. * provF => [containerA, containerC],
  22028. * provG => [containerA, containerC],
  22029. * provA => [containerA]
  22030. * provB => [containerA]
  22031. * }
  22032. * visitedContainers === Set { containerB, containerC, containerA }
  22033. * ```
  22034. *
  22035. * @param providerToPath Map map of providers to paths that this function fills
  22036. * @param visitedContainers Set a set to keep track of the containers we've already visited
  22037. * @return function(provider SingleProvider, container: Type<unknown> | InjectorType<unknown>) =>
  22038. * void
  22039. */
  22040. function walkProviderTreeToDiscoverImportPaths(providerToPath, visitedContainers) {
  22041. return (provider, container) => {
  22042. // If the provider is not already in the providerToPath map,
  22043. // add an entry with the provider as the key and an array containing the current container as
  22044. // the value
  22045. if (!providerToPath.has(provider)) {
  22046. providerToPath.set(provider, [container]);
  22047. }
  22048. // This block will run exactly once for each container in the import tree.
  22049. // This is where we run the logic to check the imports array of the current
  22050. // container to see if it's the next container in the path for our currently
  22051. // discovered providers.
  22052. if (!visitedContainers.has(container)) {
  22053. // Iterate through the providers we've already seen
  22054. for (const prov of providerToPath.keys()) {
  22055. const existingImportPath = providerToPath.get(prov);
  22056. let containerDef = getInjectorDef(container);
  22057. if (!containerDef) {
  22058. const ngModule = container.ngModule;
  22059. containerDef = getInjectorDef(ngModule);
  22060. }
  22061. if (!containerDef) {
  22062. return;
  22063. }
  22064. const lastContainerAddedToPath = existingImportPath[0];
  22065. let isNextStepInPath = false;
  22066. deepForEach(containerDef.imports, (moduleImport) => {
  22067. if (isNextStepInPath) {
  22068. return;
  22069. }
  22070. isNextStepInPath =
  22071. moduleImport.ngModule === lastContainerAddedToPath ||
  22072. moduleImport === lastContainerAddedToPath;
  22073. if (isNextStepInPath) {
  22074. providerToPath.get(prov)?.unshift(container);
  22075. }
  22076. });
  22077. }
  22078. }
  22079. visitedContainers.add(container);
  22080. };
  22081. }
  22082. /**
  22083. * Gets the providers configured on an EnvironmentInjector
  22084. *
  22085. * @param injector EnvironmentInjector
  22086. * @returns an array of objects representing the providers of the given injector
  22087. */
  22088. function getEnvironmentInjectorProviders(injector) {
  22089. const providerRecordsWithoutImportPaths = getFrameworkDIDebugData().resolverToProviders.get(injector) ?? [];
  22090. // platform injector has no provider imports container so can we skip trying to
  22091. // find import paths
  22092. if (isPlatformInjector(injector)) {
  22093. return providerRecordsWithoutImportPaths;
  22094. }
  22095. const providerImportsContainer = getProviderImportsContainer(injector);
  22096. if (providerImportsContainer === null) {
  22097. // We assume that if an environment injector exists without an associated provider imports
  22098. // container, it was created without such a container. Some examples cases where this could
  22099. // happen:
  22100. // - The root injector of a standalone application
  22101. // - A router injector created by using the providers array in a lazy loaded route
  22102. // - A manually created injector that is attached to the injector tree
  22103. // Since each of these cases has no provider container, there is no concept of import paths,
  22104. // so we can simply return the provider records.
  22105. return providerRecordsWithoutImportPaths;
  22106. }
  22107. const providerToPath = getProviderImportPaths(providerImportsContainer);
  22108. const providerRecords = [];
  22109. for (const providerRecord of providerRecordsWithoutImportPaths) {
  22110. const provider = providerRecord.provider;
  22111. // Ignore these special providers for now until we have a cleaner way of
  22112. // determing when they are provided by the framework vs provided by the user.
  22113. const token = provider.provide;
  22114. if (token === ENVIRONMENT_INITIALIZER || token === INJECTOR_DEF_TYPES) {
  22115. continue;
  22116. }
  22117. let importPath = providerToPath.get(provider) ?? [];
  22118. const def = getComponentDef(providerImportsContainer);
  22119. const isStandaloneComponent = !!def?.standalone;
  22120. // We prepend the component constructor in the standalone case
  22121. // because walkProviderTree does not visit this constructor during it's traversal
  22122. if (isStandaloneComponent) {
  22123. importPath = [providerImportsContainer, ...importPath];
  22124. }
  22125. providerRecords.push({ ...providerRecord, importPath });
  22126. }
  22127. return providerRecords;
  22128. }
  22129. function isPlatformInjector(injector) {
  22130. return injector instanceof R3Injector && injector.scopes.has('platform');
  22131. }
  22132. /**
  22133. * Gets the providers configured on an injector.
  22134. *
  22135. * @param injector the injector to lookup the providers of
  22136. * @returns ProviderRecord[] an array of objects representing the providers of the given injector
  22137. */
  22138. function getInjectorProviders(injector) {
  22139. if (injector instanceof NodeInjector) {
  22140. return getNodeInjectorProviders(injector);
  22141. }
  22142. else if (injector instanceof EnvironmentInjector) {
  22143. return getEnvironmentInjectorProviders(injector);
  22144. }
  22145. throwError('getInjectorProviders only supports NodeInjector and EnvironmentInjector');
  22146. }
  22147. /**
  22148. *
  22149. * Given an injector, this function will return
  22150. * an object containing the type and source of the injector.
  22151. *
  22152. * | | type | source |
  22153. * |--------------|-------------|-------------------------------------------------------------|
  22154. * | NodeInjector | element | DOM element that created this injector |
  22155. * | R3Injector | environment | `injector.source` |
  22156. * | NullInjector | null | null |
  22157. *
  22158. * @param injector the Injector to get metadata for
  22159. * @returns an object containing the type and source of the given injector. If the injector metadata
  22160. * cannot be determined, returns null.
  22161. */
  22162. function getInjectorMetadata(injector) {
  22163. if (injector instanceof NodeInjector) {
  22164. const lView = getNodeInjectorLView(injector);
  22165. const tNode = getNodeInjectorTNode(injector);
  22166. assertTNodeForLView(tNode, lView);
  22167. return { type: 'element', source: getNativeByTNode(tNode, lView) };
  22168. }
  22169. if (injector instanceof R3Injector) {
  22170. return { type: 'environment', source: injector.source ?? null };
  22171. }
  22172. if (injector instanceof NullInjector) {
  22173. return { type: 'null', source: null };
  22174. }
  22175. return null;
  22176. }
  22177. function getInjectorResolutionPath(injector) {
  22178. const resolutionPath = [injector];
  22179. getInjectorResolutionPathHelper(injector, resolutionPath);
  22180. return resolutionPath;
  22181. }
  22182. function getInjectorResolutionPathHelper(injector, resolutionPath) {
  22183. const parent = getInjectorParent(injector);
  22184. // if getInjectorParent can't find a parent, then we've either reached the end
  22185. // of the path, or we need to move from the Element Injector tree to the
  22186. // module injector tree using the first injector in our path as the connection point.
  22187. if (parent === null) {
  22188. if (injector instanceof NodeInjector) {
  22189. const firstInjector = resolutionPath[0];
  22190. if (firstInjector instanceof NodeInjector) {
  22191. const moduleInjector = getModuleInjectorOfNodeInjector(firstInjector);
  22192. if (moduleInjector === null) {
  22193. throwError('NodeInjector must have some connection to the module injector tree');
  22194. }
  22195. resolutionPath.push(moduleInjector);
  22196. getInjectorResolutionPathHelper(moduleInjector, resolutionPath);
  22197. }
  22198. return resolutionPath;
  22199. }
  22200. }
  22201. else {
  22202. resolutionPath.push(parent);
  22203. getInjectorResolutionPathHelper(parent, resolutionPath);
  22204. }
  22205. return resolutionPath;
  22206. }
  22207. /**
  22208. * Gets the parent of an injector.
  22209. *
  22210. * This function is not able to make the jump from the Element Injector Tree to the Module
  22211. * injector tree. This is because the "parent" (the next step in the reoslution path)
  22212. * of a root NodeInjector is dependent on which NodeInjector ancestor initiated
  22213. * the DI lookup. See getInjectorResolutionPath for a function that can make this jump.
  22214. *
  22215. * In the below diagram:
  22216. * ```ts
  22217. * getInjectorParent(NodeInjectorB)
  22218. * > NodeInjectorA
  22219. * getInjectorParent(NodeInjectorA) // or getInjectorParent(getInjectorParent(NodeInjectorB))
  22220. * > null // cannot jump to ModuleInjector tree
  22221. * ```
  22222. *
  22223. * ```
  22224. * ┌───────┐ ┌───────────────────┐
  22225. * ┌───────────┤ModuleA├───Injector────►│EnvironmentInjector│
  22226. * │ └───┬───┘ └───────────────────┘
  22227. * │ │
  22228. * │ bootstraps
  22229. * │ │
  22230. * │ │
  22231. * │ ┌────▼─────┐ ┌─────────────┐
  22232. * declares │ComponentA├────Injector────►│NodeInjectorA│
  22233. * │ └────┬─────┘ └─────▲───────┘
  22234. * │ │ │
  22235. * │ renders parent
  22236. * │ │ │
  22237. * │ ┌────▼─────┐ ┌─────┴───────┐
  22238. * └─────────►│ComponentB├────Injector────►│NodeInjectorB│
  22239. * └──────────┘ └─────────────┘
  22240. *```
  22241. *
  22242. * @param injector an Injector to get the parent of
  22243. * @returns Injector the parent of the given injector
  22244. */
  22245. function getInjectorParent(injector) {
  22246. if (injector instanceof R3Injector) {
  22247. return injector.parent;
  22248. }
  22249. let tNode;
  22250. let lView;
  22251. if (injector instanceof NodeInjector) {
  22252. tNode = getNodeInjectorTNode(injector);
  22253. lView = getNodeInjectorLView(injector);
  22254. }
  22255. else if (injector instanceof NullInjector) {
  22256. return null;
  22257. }
  22258. else if (injector instanceof ChainedInjector) {
  22259. return injector.parentInjector;
  22260. }
  22261. else {
  22262. throwError('getInjectorParent only support injectors of type R3Injector, NodeInjector, NullInjector');
  22263. }
  22264. const parentLocation = getParentInjectorLocation(tNode, lView);
  22265. if (hasParentInjector(parentLocation)) {
  22266. const parentInjectorIndex = getParentInjectorIndex(parentLocation);
  22267. const parentLView = getParentInjectorView(parentLocation, lView);
  22268. const parentTView = parentLView[TVIEW];
  22269. const parentTNode = parentTView.data[parentInjectorIndex + 8 /* NodeInjectorOffset.TNODE */];
  22270. return new NodeInjector(parentTNode, parentLView);
  22271. }
  22272. else {
  22273. const chainedInjector = lView[INJECTOR];
  22274. // Case where chainedInjector.injector is an OutletInjector and chainedInjector.injector.parent
  22275. // is a NodeInjector.
  22276. // todo(aleksanderbodurri): ideally nothing in packages/core should deal
  22277. // directly with router concerns. Refactor this so that we can make the jump from
  22278. // NodeInjector -> OutletInjector -> NodeInjector
  22279. // without explicitly relying on types contracts from packages/router
  22280. const injectorParent = chainedInjector.injector?.parent;
  22281. if (injectorParent instanceof NodeInjector) {
  22282. return injectorParent;
  22283. }
  22284. }
  22285. return null;
  22286. }
  22287. /**
  22288. * Gets the module injector of a NodeInjector.
  22289. *
  22290. * @param injector NodeInjector to get module injector of
  22291. * @returns Injector representing module injector of the given NodeInjector
  22292. */
  22293. function getModuleInjectorOfNodeInjector(injector) {
  22294. let lView;
  22295. if (injector instanceof NodeInjector) {
  22296. lView = getNodeInjectorLView(injector);
  22297. }
  22298. else {
  22299. throwError('getModuleInjectorOfNodeInjector must be called with a NodeInjector');
  22300. }
  22301. const inj = lView[INJECTOR];
  22302. const moduleInjector = inj instanceof ChainedInjector ? inj.parentInjector : inj.parent;
  22303. if (!moduleInjector) {
  22304. throwError('NodeInjector must have some connection to the module injector tree');
  22305. }
  22306. return moduleInjector;
  22307. }
  22308. function isComputedNode(node) {
  22309. return node.kind === 'computed';
  22310. }
  22311. function isTemplateEffectNode(node) {
  22312. return node.kind === 'template';
  22313. }
  22314. function isEffectNode(node) {
  22315. return node.kind === 'effect';
  22316. }
  22317. function isSignalNode(node) {
  22318. return node.kind === 'signal';
  22319. }
  22320. /**
  22321. *
  22322. * @param injector
  22323. * @returns Template consumer of given NodeInjector
  22324. */
  22325. function getTemplateConsumer(injector) {
  22326. const tNode = getNodeInjectorTNode(injector);
  22327. assertTNode(tNode);
  22328. const lView = getNodeInjectorLView(injector);
  22329. assertLView(lView);
  22330. const templateLView = lView[tNode.index];
  22331. assertLView(templateLView);
  22332. return templateLView[REACTIVE_TEMPLATE_CONSUMER];
  22333. }
  22334. function getNodesAndEdgesFromSignalMap(signalMap) {
  22335. const nodes = Array.from(signalMap.keys());
  22336. const debugSignalGraphNodes = [];
  22337. const edges = [];
  22338. for (const [consumer, producers] of signalMap.entries()) {
  22339. const consumerIndex = nodes.indexOf(consumer);
  22340. // collect node
  22341. if (isComputedNode(consumer) || isSignalNode(consumer)) {
  22342. debugSignalGraphNodes.push({
  22343. label: consumer.debugName,
  22344. value: consumer.value,
  22345. kind: consumer.kind,
  22346. });
  22347. }
  22348. else if (isTemplateEffectNode(consumer)) {
  22349. debugSignalGraphNodes.push({
  22350. label: consumer.debugName ?? consumer.lView?.[HOST]?.tagName?.toLowerCase?.(),
  22351. kind: consumer.kind,
  22352. });
  22353. }
  22354. else if (isEffectNode(consumer)) {
  22355. debugSignalGraphNodes.push({
  22356. label: consumer.debugName,
  22357. kind: consumer.kind,
  22358. });
  22359. }
  22360. else {
  22361. debugSignalGraphNodes.push({
  22362. label: consumer.debugName,
  22363. kind: consumer.kind,
  22364. });
  22365. }
  22366. // collect edges for node
  22367. for (const producer of producers) {
  22368. edges.push({ consumer: consumerIndex, producer: nodes.indexOf(producer) });
  22369. }
  22370. }
  22371. return { nodes: debugSignalGraphNodes, edges };
  22372. }
  22373. function extractEffectsFromInjector(injector) {
  22374. let diResolver = injector;
  22375. if (injector instanceof NodeInjector) {
  22376. const lView = getNodeInjectorLView(injector);
  22377. diResolver = lView;
  22378. }
  22379. const resolverToEffects = getFrameworkDIDebugData().resolverToEffects;
  22380. const effects = resolverToEffects.get(diResolver) ?? [];
  22381. return effects.map((effect) => effect[SIGNAL]);
  22382. }
  22383. function extractSignalNodesAndEdgesFromRoots(nodes, signalDependenciesMap = new Map()) {
  22384. for (const node of nodes) {
  22385. if (signalDependenciesMap.has(node)) {
  22386. continue;
  22387. }
  22388. const producerNodes = (node.producerNode ?? []);
  22389. signalDependenciesMap.set(node, producerNodes);
  22390. extractSignalNodesAndEdgesFromRoots(producerNodes, signalDependenciesMap);
  22391. }
  22392. return signalDependenciesMap;
  22393. }
  22394. /**
  22395. * Returns a debug representation of the signal graph for the given injector.
  22396. *
  22397. * Currently only supports element injectors. Starts by discovering the consumer nodes
  22398. * and then traverses their producer nodes to build the signal graph.
  22399. *
  22400. * @param injector The injector to get the signal graph for.
  22401. * @returns A debug representation of the signal graph.
  22402. * @throws If the injector is an environment injector.
  22403. */
  22404. function getSignalGraph(injector) {
  22405. let templateConsumer = null;
  22406. if (!(injector instanceof NodeInjector) && !(injector instanceof R3Injector)) {
  22407. return throwError('getSignalGraph must be called with a NodeInjector or R3Injector');
  22408. }
  22409. if (injector instanceof NodeInjector) {
  22410. templateConsumer = getTemplateConsumer(injector);
  22411. }
  22412. const nonTemplateEffectNodes = extractEffectsFromInjector(injector);
  22413. const signalNodes = templateConsumer
  22414. ? [templateConsumer, ...nonTemplateEffectNodes]
  22415. : nonTemplateEffectNodes;
  22416. const signalDependenciesMap = extractSignalNodesAndEdgesFromRoots(signalNodes);
  22417. return getNodesAndEdgesFromSignalMap(signalDependenciesMap);
  22418. }
  22419. /// <reference path="../../../../goog.d.ts" />
  22420. /**
  22421. * This file introduces series of globally accessible debug tools
  22422. * to allow for the Angular debugging story to function.
  22423. *
  22424. * To see this in action run the following command:
  22425. *
  22426. * bazel run //packages/core/test/bundling/todo:devserver
  22427. *
  22428. * Then load `localhost:5432` and start using the console tools.
  22429. */
  22430. /**
  22431. * This value reflects the property on the window where the dev
  22432. * tools are patched (window.ng).
  22433. * */
  22434. const GLOBAL_PUBLISH_EXPANDO_KEY = 'ng';
  22435. const globalUtilsFunctions = {
  22436. /**
  22437. * Warning: functions that start with `ɵ` are considered *INTERNAL* and should not be relied upon
  22438. * in application's code. The contract of those functions might be changed in any release and/or a
  22439. * function can be removed completely.
  22440. */
  22441. 'ɵgetDependenciesFromInjectable': getDependenciesFromInjectable,
  22442. 'ɵgetInjectorProviders': getInjectorProviders,
  22443. 'ɵgetInjectorResolutionPath': getInjectorResolutionPath,
  22444. 'ɵgetInjectorMetadata': getInjectorMetadata,
  22445. 'ɵsetProfiler': setProfiler,
  22446. 'ɵgetSignalGraph': getSignalGraph,
  22447. 'ɵgetDeferBlocks': getDeferBlocks,
  22448. 'getDirectiveMetadata': getDirectiveMetadata$1,
  22449. 'getComponent': getComponent,
  22450. 'getContext': getContext,
  22451. 'getListeners': getListeners,
  22452. 'getOwningComponent': getOwningComponent,
  22453. 'getHostElement': getHostElement,
  22454. 'getInjector': getInjector,
  22455. 'getRootComponents': getRootComponents,
  22456. 'getDirectives': getDirectives,
  22457. 'applyChanges': applyChanges,
  22458. 'isSignal': isSignal,
  22459. };
  22460. let _published = false;
  22461. /**
  22462. * Publishes a collection of default debug tools onto`window.ng`.
  22463. *
  22464. * These functions are available globally when Angular is in development
  22465. * mode and are automatically stripped away from prod mode is on.
  22466. */
  22467. function publishDefaultGlobalUtils$1() {
  22468. if (!_published) {
  22469. _published = true;
  22470. if (typeof window !== 'undefined') {
  22471. // Only configure the injector profiler when running in the browser.
  22472. setupFrameworkInjectorProfiler();
  22473. }
  22474. for (const [methodName, method] of Object.entries(globalUtilsFunctions)) {
  22475. publishGlobalUtil(methodName, method);
  22476. }
  22477. }
  22478. }
  22479. /**
  22480. * Publishes the given function to `window.ng` so that it can be
  22481. * used from the browser console when an application is not in production.
  22482. */
  22483. function publishGlobalUtil(name, fn) {
  22484. publishUtil(name, fn);
  22485. }
  22486. /**
  22487. * Publishes the given function to `window.ng` from package other than @angular/core
  22488. * So that it can be used from the browser console when an application is not in production.
  22489. */
  22490. function publishExternalGlobalUtil(name, fn) {
  22491. publishUtil(name, fn);
  22492. }
  22493. function publishUtil(name, fn) {
  22494. if (typeof COMPILED === 'undefined' || !COMPILED) {
  22495. // Note: we can't export `ng` when using closure enhanced optimization as:
  22496. // - closure declares globals itself for minified names, which sometimes clobber our `ng` global
  22497. // - we can't declare a closure extern as the namespace `ng` is already used within Google
  22498. // for typings for AngularJS (via `goog.provide('ng....')`).
  22499. const w = _global;
  22500. ngDevMode && assertDefined(fn, 'function not defined');
  22501. w[GLOBAL_PUBLISH_EXPANDO_KEY] ??= {};
  22502. w[GLOBAL_PUBLISH_EXPANDO_KEY][name] = fn;
  22503. }
  22504. }
  22505. /**
  22506. * Internal injection token that can used to access an instance of a Testability class.
  22507. *
  22508. * This token acts as a bridge between the core bootstrap code and the `Testability` class. This is
  22509. * needed to ensure that there are no direct references to the `Testability` class, so it can be
  22510. * tree-shaken away (if not referenced). For the environments/setups when the `Testability` class
  22511. * should be available, this token is used to add a provider that references the `Testability`
  22512. * class. Otherwise, only this token is retained in a bundle, but the `Testability` class is not.
  22513. */
  22514. const TESTABILITY = new InjectionToken('');
  22515. /**
  22516. * Internal injection token to retrieve Testability getter class instance.
  22517. */
  22518. const TESTABILITY_GETTER = new InjectionToken('');
  22519. /**
  22520. * The Testability service provides testing hooks that can be accessed from
  22521. * the browser.
  22522. *
  22523. * Angular applications bootstrapped using an NgModule (via `@NgModule.bootstrap` field) will also
  22524. * instantiate Testability by default (in both development and production modes).
  22525. *
  22526. * For applications bootstrapped using the `bootstrapApplication` function, Testability is not
  22527. * included by default. You can include it into your applications by getting the list of necessary
  22528. * providers using the `provideProtractorTestingSupport()` function and adding them into the
  22529. * `options.providers` array. Example:
  22530. *
  22531. * ```ts
  22532. * import {provideProtractorTestingSupport} from '@angular/platform-browser';
  22533. *
  22534. * await bootstrapApplication(RootComponent, providers: [provideProtractorTestingSupport()]);
  22535. * ```
  22536. *
  22537. * @publicApi
  22538. */
  22539. class Testability {
  22540. _ngZone;
  22541. registry;
  22542. _isZoneStable = true;
  22543. _callbacks = [];
  22544. _taskTrackingZone = null;
  22545. _destroyRef;
  22546. constructor(_ngZone, registry, testabilityGetter) {
  22547. this._ngZone = _ngZone;
  22548. this.registry = registry;
  22549. // Attempt to retrieve a `DestroyRef` optionally.
  22550. // For backwards compatibility reasons, this cannot be required.
  22551. if (isInInjectionContext()) {
  22552. this._destroyRef = inject(DestroyRef, { optional: true }) ?? undefined;
  22553. }
  22554. // If there was no Testability logic registered in the global scope
  22555. // before, register the current testability getter as a global one.
  22556. if (!_testabilityGetter) {
  22557. setTestabilityGetter(testabilityGetter);
  22558. testabilityGetter.addToWindow(registry);
  22559. }
  22560. this._watchAngularEvents();
  22561. _ngZone.run(() => {
  22562. this._taskTrackingZone =
  22563. typeof Zone == 'undefined' ? null : Zone.current.get('TaskTrackingZone');
  22564. });
  22565. }
  22566. _watchAngularEvents() {
  22567. const onUnstableSubscription = this._ngZone.onUnstable.subscribe({
  22568. next: () => {
  22569. this._isZoneStable = false;
  22570. },
  22571. });
  22572. const onStableSubscription = this._ngZone.runOutsideAngular(() => this._ngZone.onStable.subscribe({
  22573. next: () => {
  22574. NgZone.assertNotInAngularZone();
  22575. queueMicrotask(() => {
  22576. this._isZoneStable = true;
  22577. this._runCallbacksIfReady();
  22578. });
  22579. },
  22580. }));
  22581. this._destroyRef?.onDestroy(() => {
  22582. onUnstableSubscription.unsubscribe();
  22583. onStableSubscription.unsubscribe();
  22584. });
  22585. }
  22586. /**
  22587. * Whether an associated application is stable
  22588. */
  22589. isStable() {
  22590. return this._isZoneStable && !this._ngZone.hasPendingMacrotasks;
  22591. }
  22592. _runCallbacksIfReady() {
  22593. if (this.isStable()) {
  22594. // Schedules the call backs in a new frame so that it is always async.
  22595. queueMicrotask(() => {
  22596. while (this._callbacks.length !== 0) {
  22597. let cb = this._callbacks.pop();
  22598. clearTimeout(cb.timeoutId);
  22599. cb.doneCb();
  22600. }
  22601. });
  22602. }
  22603. else {
  22604. // Still not stable, send updates.
  22605. let pending = this.getPendingTasks();
  22606. this._callbacks = this._callbacks.filter((cb) => {
  22607. if (cb.updateCb && cb.updateCb(pending)) {
  22608. clearTimeout(cb.timeoutId);
  22609. return false;
  22610. }
  22611. return true;
  22612. });
  22613. }
  22614. }
  22615. getPendingTasks() {
  22616. if (!this._taskTrackingZone) {
  22617. return [];
  22618. }
  22619. // Copy the tasks data so that we don't leak tasks.
  22620. return this._taskTrackingZone.macroTasks.map((t) => {
  22621. return {
  22622. source: t.source,
  22623. // From TaskTrackingZone:
  22624. // https://github.com/angular/zone.js/blob/master/lib/zone-spec/task-tracking.ts#L40
  22625. creationLocation: t.creationLocation,
  22626. data: t.data,
  22627. };
  22628. });
  22629. }
  22630. addCallback(cb, timeout, updateCb) {
  22631. let timeoutId = -1;
  22632. if (timeout && timeout > 0) {
  22633. timeoutId = setTimeout(() => {
  22634. this._callbacks = this._callbacks.filter((cb) => cb.timeoutId !== timeoutId);
  22635. cb();
  22636. }, timeout);
  22637. }
  22638. this._callbacks.push({ doneCb: cb, timeoutId: timeoutId, updateCb: updateCb });
  22639. }
  22640. /**
  22641. * Wait for the application to be stable with a timeout. If the timeout is reached before that
  22642. * happens, the callback receives a list of the macro tasks that were pending, otherwise null.
  22643. *
  22644. * @param doneCb The callback to invoke when Angular is stable or the timeout expires
  22645. * whichever comes first.
  22646. * @param timeout Optional. The maximum time to wait for Angular to become stable. If not
  22647. * specified, whenStable() will wait forever.
  22648. * @param updateCb Optional. If specified, this callback will be invoked whenever the set of
  22649. * pending macrotasks changes. If this callback returns true doneCb will not be invoked
  22650. * and no further updates will be issued.
  22651. */
  22652. whenStable(doneCb, timeout, updateCb) {
  22653. if (updateCb && !this._taskTrackingZone) {
  22654. throw new Error('Task tracking zone is required when passing an update callback to ' +
  22655. 'whenStable(). Is "zone.js/plugins/task-tracking" loaded?');
  22656. }
  22657. this.addCallback(doneCb, timeout, updateCb);
  22658. this._runCallbacksIfReady();
  22659. }
  22660. /**
  22661. * Registers an application with a testability hook so that it can be tracked.
  22662. * @param token token of application, root element
  22663. *
  22664. * @internal
  22665. */
  22666. registerApplication(token) {
  22667. this.registry.registerApplication(token, this);
  22668. }
  22669. /**
  22670. * Unregisters an application.
  22671. * @param token token of application, root element
  22672. *
  22673. * @internal
  22674. */
  22675. unregisterApplication(token) {
  22676. this.registry.unregisterApplication(token);
  22677. }
  22678. /**
  22679. * Find providers by name
  22680. * @param using The root element to search from
  22681. * @param provider The name of binding variable
  22682. * @param exactMatch Whether using exactMatch
  22683. */
  22684. findProviders(using, provider, exactMatch) {
  22685. // TODO(juliemr): implement.
  22686. return [];
  22687. }
  22688. static ɵfac = function Testability_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || Testability)(ɵɵinject(NgZone), ɵɵinject(TestabilityRegistry), ɵɵinject(TESTABILITY_GETTER)); };
  22689. static ɵprov = /*@__PURE__*/ ɵɵdefineInjectable({ token: Testability, factory: Testability.ɵfac });
  22690. }
  22691. (() => { (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(Testability, [{
  22692. type: Injectable
  22693. }], () => [{ type: NgZone }, { type: TestabilityRegistry }, { type: undefined, decorators: [{
  22694. type: Inject,
  22695. args: [TESTABILITY_GETTER]
  22696. }] }], null); })();
  22697. /**
  22698. * A global registry of {@link Testability} instances for specific elements.
  22699. * @publicApi
  22700. */
  22701. class TestabilityRegistry {
  22702. /** @internal */
  22703. _applications = new Map();
  22704. /**
  22705. * Registers an application with a testability hook so that it can be tracked
  22706. * @param token token of application, root element
  22707. * @param testability Testability hook
  22708. */
  22709. registerApplication(token, testability) {
  22710. this._applications.set(token, testability);
  22711. }
  22712. /**
  22713. * Unregisters an application.
  22714. * @param token token of application, root element
  22715. */
  22716. unregisterApplication(token) {
  22717. this._applications.delete(token);
  22718. }
  22719. /**
  22720. * Unregisters all applications
  22721. */
  22722. unregisterAllApplications() {
  22723. this._applications.clear();
  22724. }
  22725. /**
  22726. * Get a testability hook associated with the application
  22727. * @param elem root element
  22728. */
  22729. getTestability(elem) {
  22730. return this._applications.get(elem) || null;
  22731. }
  22732. /**
  22733. * Get all registered testabilities
  22734. */
  22735. getAllTestabilities() {
  22736. return Array.from(this._applications.values());
  22737. }
  22738. /**
  22739. * Get all registered applications(root elements)
  22740. */
  22741. getAllRootElements() {
  22742. return Array.from(this._applications.keys());
  22743. }
  22744. /**
  22745. * Find testability of a node in the Tree
  22746. * @param elem node
  22747. * @param findInAncestors whether finding testability in ancestors if testability was not found in
  22748. * current node
  22749. */
  22750. findTestabilityInTree(elem, findInAncestors = true) {
  22751. return _testabilityGetter?.findTestabilityInTree(this, elem, findInAncestors) ?? null;
  22752. }
  22753. static ɵfac = function TestabilityRegistry_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || TestabilityRegistry)(); };
  22754. static ɵprov = /*@__PURE__*/ ɵɵdefineInjectable({ token: TestabilityRegistry, factory: TestabilityRegistry.ɵfac, providedIn: 'platform' });
  22755. }
  22756. (() => { (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(TestabilityRegistry, [{
  22757. type: Injectable,
  22758. args: [{ providedIn: 'platform' }]
  22759. }], null, null); })();
  22760. /**
  22761. * Set the {@link GetTestability} implementation used by the Angular testing framework.
  22762. * @publicApi
  22763. */
  22764. function setTestabilityGetter(getter) {
  22765. _testabilityGetter = getter;
  22766. }
  22767. let _testabilityGetter;
  22768. /**
  22769. * A scheduler which manages the execution of effects.
  22770. */
  22771. class EffectScheduler {
  22772. /** @nocollapse */
  22773. static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
  22774. token: EffectScheduler,
  22775. providedIn: 'root',
  22776. factory: () => new ZoneAwareEffectScheduler(),
  22777. });
  22778. }
  22779. /**
  22780. * A wrapper around `ZoneAwareQueueingScheduler` that schedules flushing via the microtask queue
  22781. * when.
  22782. */
  22783. class ZoneAwareEffectScheduler {
  22784. queuedEffectCount = 0;
  22785. queues = new Map();
  22786. schedule(handle) {
  22787. this.enqueue(handle);
  22788. }
  22789. remove(handle) {
  22790. const zone = handle.zone;
  22791. const queue = this.queues.get(zone);
  22792. if (!queue.has(handle)) {
  22793. return;
  22794. }
  22795. queue.delete(handle);
  22796. this.queuedEffectCount--;
  22797. }
  22798. enqueue(handle) {
  22799. const zone = handle.zone;
  22800. if (!this.queues.has(zone)) {
  22801. this.queues.set(zone, new Set());
  22802. }
  22803. const queue = this.queues.get(zone);
  22804. if (queue.has(handle)) {
  22805. return;
  22806. }
  22807. this.queuedEffectCount++;
  22808. queue.add(handle);
  22809. }
  22810. /**
  22811. * Run all scheduled effects.
  22812. *
  22813. * Execution order of effects within the same zone is guaranteed to be FIFO, but there is no
  22814. * ordering guarantee between effects scheduled in different zones.
  22815. */
  22816. flush() {
  22817. while (this.queuedEffectCount > 0) {
  22818. for (const [zone, queue] of this.queues) {
  22819. // `zone` here must be defined.
  22820. if (zone === null) {
  22821. this.flushQueue(queue);
  22822. }
  22823. else {
  22824. zone.run(() => this.flushQueue(queue));
  22825. }
  22826. }
  22827. }
  22828. }
  22829. flushQueue(queue) {
  22830. for (const handle of queue) {
  22831. queue.delete(handle);
  22832. this.queuedEffectCount--;
  22833. // TODO: what happens if this throws an error?
  22834. handle.run();
  22835. }
  22836. }
  22837. }
  22838. /**
  22839. * Determine if the argument is shaped like a Promise
  22840. */
  22841. function isPromise(obj) {
  22842. // allow any Promise/A+ compliant thenable.
  22843. // It's up to the caller to ensure that obj.then conforms to the spec
  22844. return !!obj && typeof obj.then === 'function';
  22845. }
  22846. /**
  22847. * Determine if the argument is a Subscribable
  22848. */
  22849. function isSubscribable(obj) {
  22850. return !!obj && typeof obj.subscribe === 'function';
  22851. }
  22852. /**
  22853. * A DI token that you can use to provide
  22854. * one or more initialization functions.
  22855. *
  22856. * The provided functions are injected at application startup and executed during
  22857. * app initialization. If any of these functions returns a Promise or an Observable, initialization
  22858. * does not complete until the Promise is resolved or the Observable is completed.
  22859. *
  22860. * You can, for example, create a factory function that loads language data
  22861. * or an external configuration, and provide that function to the `APP_INITIALIZER` token.
  22862. * The function is executed during the application bootstrap process,
  22863. * and the needed data is available on startup.
  22864. *
  22865. * Note that the provided initializer is run in the injection context.
  22866. *
  22867. * @deprecated from v19.0.0, use provideAppInitializer instead
  22868. *
  22869. * @see {@link ApplicationInitStatus}
  22870. * @see {@link provideAppInitializer}
  22871. *
  22872. * @usageNotes
  22873. *
  22874. * The following example illustrates how to configure a multi-provider using `APP_INITIALIZER` token
  22875. * and a function returning a promise.
  22876. * ### Example with NgModule-based application
  22877. * ```ts
  22878. * function initializeApp(): Promise<any> {
  22879. * const http = inject(HttpClient);
  22880. * return firstValueFrom(
  22881. * http
  22882. * .get("https://someUrl.com/api/user")
  22883. * .pipe(tap(user => { ... }))
  22884. * );
  22885. * }
  22886. *
  22887. * @NgModule({
  22888. * imports: [BrowserModule],
  22889. * declarations: [AppComponent],
  22890. * bootstrap: [AppComponent],
  22891. * providers: [{
  22892. * provide: APP_INITIALIZER,
  22893. * useValue: initializeApp,
  22894. * multi: true,
  22895. * }]
  22896. * })
  22897. * export class AppModule {}
  22898. * ```
  22899. *
  22900. * ### Example with standalone application
  22901. * ```ts
  22902. * function initializeApp() {
  22903. * const http = inject(HttpClient);
  22904. * return firstValueFrom(
  22905. * http
  22906. * .get("https://someUrl.com/api/user")
  22907. * .pipe(tap(user => { ... }))
  22908. * );
  22909. * }
  22910. *
  22911. * bootstrapApplication(App, {
  22912. * providers: [
  22913. * provideHttpClient(),
  22914. * {
  22915. * provide: APP_INITIALIZER,
  22916. * useValue: initializeApp,
  22917. * multi: true,
  22918. * },
  22919. * ],
  22920. * });
  22921. * ```
  22922. *
  22923. *
  22924. * It's also possible to configure a multi-provider using `APP_INITIALIZER` token and a function
  22925. * returning an observable, see an example below. Note: the `HttpClient` in this example is used for
  22926. * demo purposes to illustrate how the factory function can work with other providers available
  22927. * through DI.
  22928. *
  22929. * ### Example with NgModule-based application
  22930. * ```ts
  22931. * function initializeApp() {
  22932. * const http = inject(HttpClient);
  22933. * return firstValueFrom(
  22934. * http
  22935. * .get("https://someUrl.com/api/user")
  22936. * .pipe(tap(user => { ... }))
  22937. * );
  22938. * }
  22939. *
  22940. * @NgModule({
  22941. * imports: [BrowserModule, HttpClientModule],
  22942. * declarations: [AppComponent],
  22943. * bootstrap: [AppComponent],
  22944. * providers: [{
  22945. * provide: APP_INITIALIZER,
  22946. * useValue: initializeApp,
  22947. * multi: true,
  22948. * }]
  22949. * })
  22950. * export class AppModule {}
  22951. * ```
  22952. *
  22953. * ### Example with standalone application
  22954. * ```ts
  22955. * function initializeApp() {
  22956. * const http = inject(HttpClient);
  22957. * return firstValueFrom(
  22958. * http
  22959. * .get("https://someUrl.com/api/user")
  22960. * .pipe(tap(user => { ... }))
  22961. * );
  22962. * }
  22963. *
  22964. * bootstrapApplication(App, {
  22965. * providers: [
  22966. * provideHttpClient(),
  22967. * {
  22968. * provide: APP_INITIALIZER,
  22969. * useValue: initializeApp,
  22970. * multi: true,
  22971. * },
  22972. * ],
  22973. * });
  22974. * ```
  22975. *
  22976. * @publicApi
  22977. */
  22978. const APP_INITIALIZER = new InjectionToken(ngDevMode ? 'Application Initializer' : '');
  22979. /**
  22980. * @description
  22981. * The provided function is injected at application startup and executed during
  22982. * app initialization. If the function returns a Promise or an Observable, initialization
  22983. * does not complete until the Promise is resolved or the Observable is completed.
  22984. *
  22985. * You can, for example, create a function that loads language data
  22986. * or an external configuration, and provide that function using `provideAppInitializer()`.
  22987. * The function is executed during the application bootstrap process,
  22988. * and the needed data is available on startup.
  22989. *
  22990. * Note that the provided initializer is run in the injection context.
  22991. *
  22992. * Previously, this was achieved using the `APP_INITIALIZER` token which is now deprecated.
  22993. *
  22994. * @see {@link APP_INITIALIZER}
  22995. *
  22996. * @usageNotes
  22997. * The following example illustrates how to configure an initialization function using
  22998. * `provideAppInitializer()`
  22999. * ```ts
  23000. * bootstrapApplication(App, {
  23001. * providers: [
  23002. * provideAppInitializer(() => {
  23003. * const http = inject(HttpClient);
  23004. * return firstValueFrom(
  23005. * http
  23006. * .get("https://someUrl.com/api/user")
  23007. * .pipe(tap(user => { ... }))
  23008. * );
  23009. * }),
  23010. * provideHttpClient(),
  23011. * ],
  23012. * });
  23013. * ```
  23014. *
  23015. * @publicApi
  23016. */
  23017. function provideAppInitializer(initializerFn) {
  23018. return makeEnvironmentProviders([
  23019. {
  23020. provide: APP_INITIALIZER,
  23021. multi: true,
  23022. useValue: initializerFn,
  23023. },
  23024. ]);
  23025. }
  23026. /**
  23027. * A class that reflects the state of running {@link APP_INITIALIZER} functions.
  23028. *
  23029. * @publicApi
  23030. */
  23031. class ApplicationInitStatus {
  23032. // Using non null assertion, these fields are defined below
  23033. // within the `new Promise` callback (synchronously).
  23034. resolve;
  23035. reject;
  23036. initialized = false;
  23037. done = false;
  23038. donePromise = new Promise((res, rej) => {
  23039. this.resolve = res;
  23040. this.reject = rej;
  23041. });
  23042. appInits = inject(APP_INITIALIZER, { optional: true }) ?? [];
  23043. injector = inject(Injector);
  23044. constructor() {
  23045. if ((typeof ngDevMode === 'undefined' || ngDevMode) && !Array.isArray(this.appInits)) {
  23046. throw new RuntimeError(-209 /* RuntimeErrorCode.INVALID_MULTI_PROVIDER */, 'Unexpected type of the `APP_INITIALIZER` token value ' +
  23047. `(expected an array, but got ${typeof this.appInits}). ` +
  23048. 'Please check that the `APP_INITIALIZER` token is configured as a ' +
  23049. '`multi: true` provider.');
  23050. }
  23051. }
  23052. /** @internal */
  23053. runInitializers() {
  23054. if (this.initialized) {
  23055. return;
  23056. }
  23057. const asyncInitPromises = [];
  23058. for (const appInits of this.appInits) {
  23059. const initResult = runInInjectionContext(this.injector, appInits);
  23060. if (isPromise(initResult)) {
  23061. asyncInitPromises.push(initResult);
  23062. }
  23063. else if (isSubscribable(initResult)) {
  23064. const observableAsPromise = new Promise((resolve, reject) => {
  23065. initResult.subscribe({ complete: resolve, error: reject });
  23066. });
  23067. asyncInitPromises.push(observableAsPromise);
  23068. }
  23069. }
  23070. const complete = () => {
  23071. // @ts-expect-error overwriting a readonly
  23072. this.done = true;
  23073. this.resolve();
  23074. };
  23075. Promise.all(asyncInitPromises)
  23076. .then(() => {
  23077. complete();
  23078. })
  23079. .catch((e) => {
  23080. this.reject(e);
  23081. });
  23082. if (asyncInitPromises.length === 0) {
  23083. complete();
  23084. }
  23085. this.initialized = true;
  23086. }
  23087. static ɵfac = function ApplicationInitStatus_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || ApplicationInitStatus)(); };
  23088. static ɵprov = /*@__PURE__*/ ɵɵdefineInjectable({ token: ApplicationInitStatus, factory: ApplicationInitStatus.ɵfac, providedIn: 'root' });
  23089. }
  23090. (() => { (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(ApplicationInitStatus, [{
  23091. type: Injectable,
  23092. args: [{ providedIn: 'root' }]
  23093. }], () => [], null); })();
  23094. /**
  23095. * A DI token that provides a set of callbacks to
  23096. * be called for every component that is bootstrapped.
  23097. *
  23098. * Each callback must take a `ComponentRef` instance and return nothing.
  23099. *
  23100. * `(componentRef: ComponentRef) => void`
  23101. *
  23102. * @publicApi
  23103. */
  23104. const APP_BOOTSTRAP_LISTENER = new InjectionToken(ngDevMode ? 'appBootstrapListener' : '');
  23105. function publishDefaultGlobalUtils() {
  23106. ngDevMode && publishDefaultGlobalUtils$1();
  23107. }
  23108. /**
  23109. * Sets the error for an invalid write to a signal to be an Angular `RuntimeError`.
  23110. */
  23111. function publishSignalConfiguration() {
  23112. setThrowInvalidWriteToSignalError(() => {
  23113. throw new RuntimeError(600 /* RuntimeErrorCode.SIGNAL_WRITE_FROM_ILLEGAL_CONTEXT */, ngDevMode && 'Writing to signals is not allowed in a `computed`.');
  23114. });
  23115. }
  23116. function isBoundToModule(cf) {
  23117. return cf.isBoundToModule;
  23118. }
  23119. /**
  23120. * A token for third-party components that can register themselves with NgProbe.
  23121. *
  23122. * @deprecated
  23123. * @publicApi
  23124. */
  23125. class NgProbeToken {
  23126. name;
  23127. token;
  23128. constructor(name, token) {
  23129. this.name = name;
  23130. this.token = token;
  23131. }
  23132. }
  23133. /** Maximum number of times ApplicationRef will refresh all attached views in a single tick. */
  23134. const MAXIMUM_REFRESH_RERUNS = 10;
  23135. function optionsReducer(dst, objs) {
  23136. if (Array.isArray(objs)) {
  23137. return objs.reduce(optionsReducer, dst);
  23138. }
  23139. return { ...dst, ...objs };
  23140. }
  23141. /**
  23142. * A reference to an Angular application running on a page.
  23143. *
  23144. * @usageNotes
  23145. * ### isStable examples and caveats
  23146. *
  23147. * Note two important points about `isStable`, demonstrated in the examples below:
  23148. * - the application will never be stable if you start any kind
  23149. * of recurrent asynchronous task when the application starts
  23150. * (for example for a polling process, started with a `setInterval`, a `setTimeout`
  23151. * or using RxJS operators like `interval`);
  23152. * - the `isStable` Observable runs outside of the Angular zone.
  23153. *
  23154. * Let's imagine that you start a recurrent task
  23155. * (here incrementing a counter, using RxJS `interval`),
  23156. * and at the same time subscribe to `isStable`.
  23157. *
  23158. * ```ts
  23159. * constructor(appRef: ApplicationRef) {
  23160. * appRef.isStable.pipe(
  23161. * filter(stable => stable)
  23162. * ).subscribe(() => console.log('App is stable now');
  23163. * interval(1000).subscribe(counter => console.log(counter));
  23164. * }
  23165. * ```
  23166. * In this example, `isStable` will never emit `true`,
  23167. * and the trace "App is stable now" will never get logged.
  23168. *
  23169. * If you want to execute something when the app is stable,
  23170. * you have to wait for the application to be stable
  23171. * before starting your polling process.
  23172. *
  23173. * ```ts
  23174. * constructor(appRef: ApplicationRef) {
  23175. * appRef.isStable.pipe(
  23176. * first(stable => stable),
  23177. * tap(stable => console.log('App is stable now')),
  23178. * switchMap(() => interval(1000))
  23179. * ).subscribe(counter => console.log(counter));
  23180. * }
  23181. * ```
  23182. * In this example, the trace "App is stable now" will be logged
  23183. * and then the counter starts incrementing every second.
  23184. *
  23185. * Note also that this Observable runs outside of the Angular zone,
  23186. * which means that the code in the subscription
  23187. * to this Observable will not trigger the change detection.
  23188. *
  23189. * Let's imagine that instead of logging the counter value,
  23190. * you update a field of your component
  23191. * and display it in its template.
  23192. *
  23193. * ```ts
  23194. * constructor(appRef: ApplicationRef) {
  23195. * appRef.isStable.pipe(
  23196. * first(stable => stable),
  23197. * switchMap(() => interval(1000))
  23198. * ).subscribe(counter => this.value = counter);
  23199. * }
  23200. * ```
  23201. * As the `isStable` Observable runs outside the zone,
  23202. * the `value` field will be updated properly,
  23203. * but the template will not be refreshed!
  23204. *
  23205. * You'll have to manually trigger the change detection to update the template.
  23206. *
  23207. * ```ts
  23208. * constructor(appRef: ApplicationRef, cd: ChangeDetectorRef) {
  23209. * appRef.isStable.pipe(
  23210. * first(stable => stable),
  23211. * switchMap(() => interval(1000))
  23212. * ).subscribe(counter => {
  23213. * this.value = counter;
  23214. * cd.detectChanges();
  23215. * });
  23216. * }
  23217. * ```
  23218. *
  23219. * Or make the subscription callback run inside the zone.
  23220. *
  23221. * ```ts
  23222. * constructor(appRef: ApplicationRef, zone: NgZone) {
  23223. * appRef.isStable.pipe(
  23224. * first(stable => stable),
  23225. * switchMap(() => interval(1000))
  23226. * ).subscribe(counter => zone.run(() => this.value = counter));
  23227. * }
  23228. * ```
  23229. *
  23230. * @publicApi
  23231. */
  23232. class ApplicationRef {
  23233. /** @internal */
  23234. _runningTick = false;
  23235. _destroyed = false;
  23236. _destroyListeners = [];
  23237. /** @internal */
  23238. _views = [];
  23239. internalErrorHandler = inject(INTERNAL_APPLICATION_ERROR_HANDLER);
  23240. afterRenderManager = inject(AfterRenderManager);
  23241. zonelessEnabled = inject(ZONELESS_ENABLED);
  23242. rootEffectScheduler = inject(EffectScheduler);
  23243. /**
  23244. * Current dirty state of the application across a number of dimensions (views, afterRender hooks,
  23245. * etc).
  23246. *
  23247. * A flag set here means that `tick()` will attempt to resolve the dirtiness when executed.
  23248. *
  23249. * @internal
  23250. */
  23251. dirtyFlags = 0 /* ApplicationRefDirtyFlags.None */;
  23252. /**
  23253. * Most recent snapshot from the `TracingService`, if any.
  23254. *
  23255. * This snapshot attempts to capture the context when `tick()` was first
  23256. * scheduled. It then runs wrapped in this context.
  23257. *
  23258. * @internal
  23259. */
  23260. tracingSnapshot = null;
  23261. // Needed for ComponentFixture temporarily during migration of autoDetect behavior
  23262. // Eventually the hostView of the fixture should just attach to ApplicationRef.
  23263. externalTestViews = new Set();
  23264. /** @internal */
  23265. afterTick = new Subject();
  23266. /** @internal */
  23267. get allViews() {
  23268. return [...this.externalTestViews.keys(), ...this._views];
  23269. }
  23270. /**
  23271. * Indicates whether this instance was destroyed.
  23272. */
  23273. get destroyed() {
  23274. return this._destroyed;
  23275. }
  23276. /**
  23277. * Get a list of component types registered to this application.
  23278. * This list is populated even before the component is created.
  23279. */
  23280. componentTypes = [];
  23281. /**
  23282. * Get a list of components registered to this application.
  23283. */
  23284. components = [];
  23285. /**
  23286. * Returns an Observable that indicates when the application is stable or unstable.
  23287. */
  23288. isStable = inject(PendingTasksInternal).hasPendingTasks.pipe(map((pending) => !pending));
  23289. constructor() {
  23290. // Inject the tracing service to initialize it.
  23291. inject(TracingService, { optional: true });
  23292. }
  23293. /**
  23294. * @returns A promise that resolves when the application becomes stable
  23295. */
  23296. whenStable() {
  23297. let subscription;
  23298. return new Promise((resolve) => {
  23299. subscription = this.isStable.subscribe({
  23300. next: (stable) => {
  23301. if (stable) {
  23302. resolve();
  23303. }
  23304. },
  23305. });
  23306. }).finally(() => {
  23307. subscription.unsubscribe();
  23308. });
  23309. }
  23310. _injector = inject(EnvironmentInjector);
  23311. _rendererFactory = null;
  23312. /**
  23313. * The `EnvironmentInjector` used to create this application.
  23314. */
  23315. get injector() {
  23316. return this._injector;
  23317. }
  23318. /**
  23319. * Bootstrap a component onto the element identified by its selector or, optionally, to a
  23320. * specified element.
  23321. *
  23322. * @usageNotes
  23323. * ### Bootstrap process
  23324. *
  23325. * When bootstrapping a component, Angular mounts it onto a target DOM element
  23326. * and kicks off automatic change detection. The target DOM element can be
  23327. * provided using the `rootSelectorOrNode` argument.
  23328. *
  23329. * If the target DOM element is not provided, Angular tries to find one on a page
  23330. * using the `selector` of the component that is being bootstrapped
  23331. * (first matched element is used).
  23332. *
  23333. * ### Example
  23334. *
  23335. * Generally, we define the component to bootstrap in the `bootstrap` array of `NgModule`,
  23336. * but it requires us to know the component while writing the application code.
  23337. *
  23338. * Imagine a situation where we have to wait for an API call to decide about the component to
  23339. * bootstrap. We can use the `ngDoBootstrap` hook of the `NgModule` and call this method to
  23340. * dynamically bootstrap a component.
  23341. *
  23342. * {@example core/ts/platform/platform.ts region='componentSelector'}
  23343. *
  23344. * Optionally, a component can be mounted onto a DOM element that does not match the
  23345. * selector of the bootstrapped component.
  23346. *
  23347. * In the following example, we are providing a CSS selector to match the target element.
  23348. *
  23349. * {@example core/ts/platform/platform.ts region='cssSelector'}
  23350. *
  23351. * While in this example, we are providing reference to a DOM node.
  23352. *
  23353. * {@example core/ts/platform/platform.ts region='domNode'}
  23354. */
  23355. bootstrap(componentOrFactory, rootSelectorOrNode) {
  23356. return this.bootstrapImpl(componentOrFactory, rootSelectorOrNode);
  23357. }
  23358. bootstrapImpl(componentOrFactory, rootSelectorOrNode, injector = Injector.NULL) {
  23359. profiler(10 /* ProfilerEvent.BootstrapComponentStart */);
  23360. (typeof ngDevMode === 'undefined' || ngDevMode) && warnIfDestroyed(this._destroyed);
  23361. const isComponentFactory = componentOrFactory instanceof ComponentFactory$1;
  23362. const initStatus = this._injector.get(ApplicationInitStatus);
  23363. if (!initStatus.done) {
  23364. let errorMessage = '';
  23365. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  23366. const standalone = !isComponentFactory && isStandalone(componentOrFactory);
  23367. errorMessage =
  23368. 'Cannot bootstrap as there are still asynchronous initializers running.' +
  23369. (standalone
  23370. ? ''
  23371. : ' Bootstrap components in the `ngDoBootstrap` method of the root module.');
  23372. }
  23373. throw new RuntimeError(405 /* RuntimeErrorCode.ASYNC_INITIALIZERS_STILL_RUNNING */, errorMessage);
  23374. }
  23375. let componentFactory;
  23376. if (isComponentFactory) {
  23377. componentFactory = componentOrFactory;
  23378. }
  23379. else {
  23380. const resolver = this._injector.get(ComponentFactoryResolver$1);
  23381. componentFactory = resolver.resolveComponentFactory(componentOrFactory);
  23382. }
  23383. this.componentTypes.push(componentFactory.componentType);
  23384. // Create a factory associated with the current module if it's not bound to some other
  23385. const ngModule = isBoundToModule(componentFactory)
  23386. ? undefined
  23387. : this._injector.get(NgModuleRef$1);
  23388. const selectorOrNode = rootSelectorOrNode || componentFactory.selector;
  23389. const compRef = componentFactory.create(injector, [], selectorOrNode, ngModule);
  23390. const nativeElement = compRef.location.nativeElement;
  23391. const testability = compRef.injector.get(TESTABILITY, null);
  23392. testability?.registerApplication(nativeElement);
  23393. compRef.onDestroy(() => {
  23394. this.detachView(compRef.hostView);
  23395. remove(this.components, compRef);
  23396. testability?.unregisterApplication(nativeElement);
  23397. });
  23398. this._loadComponent(compRef);
  23399. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  23400. const _console = this._injector.get(Console);
  23401. _console.log(`Angular is running in development mode.`);
  23402. }
  23403. profiler(11 /* ProfilerEvent.BootstrapComponentEnd */, compRef);
  23404. return compRef;
  23405. }
  23406. /**
  23407. * Invoke this method to explicitly process change detection and its side-effects.
  23408. *
  23409. * In development mode, `tick()` also performs a second change detection cycle to ensure that no
  23410. * further changes are detected. If additional changes are picked up during this second cycle,
  23411. * bindings in the app have side-effects that cannot be resolved in a single change detection
  23412. * pass.
  23413. * In this case, Angular throws an error, since an Angular application can only have one change
  23414. * detection pass during which all change detection must complete.
  23415. */
  23416. tick() {
  23417. if (!this.zonelessEnabled) {
  23418. this.dirtyFlags |= 1 /* ApplicationRefDirtyFlags.ViewTreeGlobal */;
  23419. }
  23420. this._tick();
  23421. }
  23422. /** @internal */
  23423. _tick() {
  23424. profiler(12 /* ProfilerEvent.ChangeDetectionStart */);
  23425. if (this.tracingSnapshot !== null) {
  23426. // Ensure we always run `tickImpl()` in the context of the most recent snapshot,
  23427. // if one exists. Snapshots may be reference counted by the implementation so
  23428. // we want to ensure that if we request a snapshot that we use it.
  23429. this.tracingSnapshot.run(TracingAction.CHANGE_DETECTION, this.tickImpl);
  23430. }
  23431. else {
  23432. this.tickImpl();
  23433. }
  23434. }
  23435. tickImpl = () => {
  23436. (typeof ngDevMode === 'undefined' || ngDevMode) && warnIfDestroyed(this._destroyed);
  23437. if (this._runningTick) {
  23438. throw new RuntimeError(101 /* RuntimeErrorCode.RECURSIVE_APPLICATION_REF_TICK */, ngDevMode && 'ApplicationRef.tick is called recursively');
  23439. }
  23440. const prevConsumer = setActiveConsumer$1(null);
  23441. try {
  23442. this._runningTick = true;
  23443. this.synchronize();
  23444. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  23445. for (let view of this.allViews) {
  23446. view.checkNoChanges();
  23447. }
  23448. }
  23449. }
  23450. catch (e) {
  23451. // Attention: Don't rethrow as it could cancel subscriptions to Observables!
  23452. this.internalErrorHandler(e);
  23453. }
  23454. finally {
  23455. this._runningTick = false;
  23456. this.tracingSnapshot?.dispose();
  23457. this.tracingSnapshot = null;
  23458. setActiveConsumer$1(prevConsumer);
  23459. this.afterTick.next();
  23460. profiler(13 /* ProfilerEvent.ChangeDetectionEnd */);
  23461. }
  23462. };
  23463. /**
  23464. * Performs the core work of synchronizing the application state with the UI, resolving any
  23465. * pending dirtiness (potentially in a loop).
  23466. */
  23467. synchronize() {
  23468. if (this._rendererFactory === null && !this._injector.destroyed) {
  23469. this._rendererFactory = this._injector.get(RendererFactory2, null, { optional: true });
  23470. }
  23471. let runs = 0;
  23472. while (this.dirtyFlags !== 0 /* ApplicationRefDirtyFlags.None */ && runs++ < MAXIMUM_REFRESH_RERUNS) {
  23473. profiler(14 /* ProfilerEvent.ChangeDetectionSyncStart */);
  23474. this.synchronizeOnce();
  23475. profiler(15 /* ProfilerEvent.ChangeDetectionSyncEnd */);
  23476. }
  23477. if ((typeof ngDevMode === 'undefined' || ngDevMode) && runs >= MAXIMUM_REFRESH_RERUNS) {
  23478. throw new RuntimeError(103 /* RuntimeErrorCode.INFINITE_CHANGE_DETECTION */, ngDevMode &&
  23479. 'Infinite change detection while refreshing application views. ' +
  23480. 'Ensure views are not calling `markForCheck` on every template execution or ' +
  23481. 'that afterRender hooks always mark views for check.');
  23482. }
  23483. }
  23484. /**
  23485. * Perform a single synchronization pass.
  23486. */
  23487. synchronizeOnce() {
  23488. // First, process any dirty root effects.
  23489. if (this.dirtyFlags & 16 /* ApplicationRefDirtyFlags.RootEffects */) {
  23490. this.dirtyFlags &= -17 /* ApplicationRefDirtyFlags.RootEffects */;
  23491. this.rootEffectScheduler.flush();
  23492. }
  23493. // First check dirty views, if there are any.
  23494. if (this.dirtyFlags & 7 /* ApplicationRefDirtyFlags.ViewTreeAny */) {
  23495. // Change detection on views starts in targeted mode (only check components if they're
  23496. // marked as dirty) unless global checking is specifically requested via APIs like
  23497. // `ApplicationRef.tick()` and the `NgZone` integration.
  23498. const useGlobalCheck = Boolean(this.dirtyFlags & 1 /* ApplicationRefDirtyFlags.ViewTreeGlobal */);
  23499. // Clear the view-related dirty flags.
  23500. this.dirtyFlags &= -8 /* ApplicationRefDirtyFlags.ViewTreeAny */;
  23501. // Set the AfterRender bit, as we're checking views and will need to run afterRender hooks.
  23502. this.dirtyFlags |= 8 /* ApplicationRefDirtyFlags.AfterRender */;
  23503. // Check all potentially dirty views.
  23504. for (let { _lView, notifyErrorHandler } of this.allViews) {
  23505. detectChangesInViewIfRequired(_lView, notifyErrorHandler, useGlobalCheck, this.zonelessEnabled);
  23506. }
  23507. // If `markForCheck()` was called during view checking, it will have set the `ViewTreeCheck`
  23508. // flag. We clear the flag here because, for backwards compatibility, `markForCheck()`
  23509. // during view checking doesn't cause the view to be re-checked.
  23510. this.dirtyFlags &= -5 /* ApplicationRefDirtyFlags.ViewTreeCheck */;
  23511. // Check if any views are still dirty after checking and we need to loop back.
  23512. this.syncDirtyFlagsWithViews();
  23513. if (this.dirtyFlags &
  23514. (7 /* ApplicationRefDirtyFlags.ViewTreeAny */ | 16 /* ApplicationRefDirtyFlags.RootEffects */)) {
  23515. // If any views or effects are still dirty after checking, loop back before running render
  23516. // hooks.
  23517. return;
  23518. }
  23519. }
  23520. else {
  23521. // If we skipped refreshing views above, there might still be unflushed animations
  23522. // because we never called `detectChangesInternal` on the views.
  23523. this._rendererFactory?.begin?.();
  23524. this._rendererFactory?.end?.();
  23525. }
  23526. // Even if there were no dirty views, afterRender hooks might still be dirty.
  23527. if (this.dirtyFlags & 8 /* ApplicationRefDirtyFlags.AfterRender */) {
  23528. this.dirtyFlags &= -9 /* ApplicationRefDirtyFlags.AfterRender */;
  23529. this.afterRenderManager.execute();
  23530. // afterRender hooks might influence dirty flags.
  23531. }
  23532. this.syncDirtyFlagsWithViews();
  23533. }
  23534. /**
  23535. * Checks `allViews` for views which require refresh/traversal, and updates `dirtyFlags`
  23536. * accordingly, with two potential behaviors:
  23537. *
  23538. * 1. If any of our views require updating, then this adds the `ViewTreeTraversal` dirty flag.
  23539. * This _should_ be a no-op, since the scheduler should've added the flag at the same time the
  23540. * view was marked as needing updating.
  23541. *
  23542. * TODO(alxhub): figure out if this behavior is still needed for edge cases.
  23543. *
  23544. * 2. If none of our views require updating, then clear the view-related `dirtyFlag`s. This
  23545. * happens when the scheduler is notified of a view becoming dirty, but the view itself isn't
  23546. * reachable through traversal from our roots (e.g. it's detached from the CD tree).
  23547. */
  23548. syncDirtyFlagsWithViews() {
  23549. if (this.allViews.some(({ _lView }) => requiresRefreshOrTraversal(_lView))) {
  23550. // If after running all afterRender callbacks new views are dirty, ensure we loop back.
  23551. this.dirtyFlags |= 2 /* ApplicationRefDirtyFlags.ViewTreeTraversal */;
  23552. return;
  23553. }
  23554. else {
  23555. // Even though this flag may be set, none of _our_ views require traversal, and so the
  23556. // `ApplicationRef` doesn't require any repeated checking.
  23557. this.dirtyFlags &= -8 /* ApplicationRefDirtyFlags.ViewTreeAny */;
  23558. }
  23559. }
  23560. /**
  23561. * Attaches a view so that it will be dirty checked.
  23562. * The view will be automatically detached when it is destroyed.
  23563. * This will throw if the view is already attached to a ViewContainer.
  23564. */
  23565. attachView(viewRef) {
  23566. (typeof ngDevMode === 'undefined' || ngDevMode) && warnIfDestroyed(this._destroyed);
  23567. const view = viewRef;
  23568. this._views.push(view);
  23569. view.attachToAppRef(this);
  23570. }
  23571. /**
  23572. * Detaches a view from dirty checking again.
  23573. */
  23574. detachView(viewRef) {
  23575. (typeof ngDevMode === 'undefined' || ngDevMode) && warnIfDestroyed(this._destroyed);
  23576. const view = viewRef;
  23577. remove(this._views, view);
  23578. view.detachFromAppRef();
  23579. }
  23580. _loadComponent(componentRef) {
  23581. this.attachView(componentRef.hostView);
  23582. this.tick();
  23583. this.components.push(componentRef);
  23584. // Get the listeners lazily to prevent DI cycles.
  23585. const listeners = this._injector.get(APP_BOOTSTRAP_LISTENER, []);
  23586. if (ngDevMode && !Array.isArray(listeners)) {
  23587. throw new RuntimeError(-209 /* RuntimeErrorCode.INVALID_MULTI_PROVIDER */, 'Unexpected type of the `APP_BOOTSTRAP_LISTENER` token value ' +
  23588. `(expected an array, but got ${typeof listeners}). ` +
  23589. 'Please check that the `APP_BOOTSTRAP_LISTENER` token is configured as a ' +
  23590. '`multi: true` provider.');
  23591. }
  23592. listeners.forEach((listener) => listener(componentRef));
  23593. }
  23594. /** @internal */
  23595. ngOnDestroy() {
  23596. if (this._destroyed)
  23597. return;
  23598. try {
  23599. // Call all the lifecycle hooks.
  23600. this._destroyListeners.forEach((listener) => listener());
  23601. // Destroy all registered views.
  23602. this._views.slice().forEach((view) => view.destroy());
  23603. }
  23604. finally {
  23605. // Indicate that this instance is destroyed.
  23606. this._destroyed = true;
  23607. // Release all references.
  23608. this._views = [];
  23609. this._destroyListeners = [];
  23610. }
  23611. }
  23612. /**
  23613. * Registers a listener to be called when an instance is destroyed.
  23614. *
  23615. * @param callback A callback function to add as a listener.
  23616. * @returns A function which unregisters a listener.
  23617. */
  23618. onDestroy(callback) {
  23619. (typeof ngDevMode === 'undefined' || ngDevMode) && warnIfDestroyed(this._destroyed);
  23620. this._destroyListeners.push(callback);
  23621. return () => remove(this._destroyListeners, callback);
  23622. }
  23623. /**
  23624. * Destroys an Angular application represented by this `ApplicationRef`. Calling this function
  23625. * will destroy the associated environment injectors as well as all the bootstrapped components
  23626. * with their views.
  23627. */
  23628. destroy() {
  23629. if (this._destroyed) {
  23630. throw new RuntimeError(406 /* RuntimeErrorCode.APPLICATION_REF_ALREADY_DESTROYED */, ngDevMode && 'This instance of the `ApplicationRef` has already been destroyed.');
  23631. }
  23632. const injector = this._injector;
  23633. // Check that this injector instance supports destroy operation.
  23634. if (injector.destroy && !injector.destroyed) {
  23635. // Destroying an underlying injector will trigger the `ngOnDestroy` lifecycle
  23636. // hook, which invokes the remaining cleanup actions.
  23637. injector.destroy();
  23638. }
  23639. }
  23640. /**
  23641. * Returns the number of attached views.
  23642. */
  23643. get viewCount() {
  23644. return this._views.length;
  23645. }
  23646. static ɵfac = function ApplicationRef_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || ApplicationRef)(); };
  23647. static ɵprov = /*@__PURE__*/ ɵɵdefineInjectable({ token: ApplicationRef, factory: ApplicationRef.ɵfac, providedIn: 'root' });
  23648. }
  23649. (() => { (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(ApplicationRef, [{
  23650. type: Injectable,
  23651. args: [{ providedIn: 'root' }]
  23652. }], () => [], null); })();
  23653. function warnIfDestroyed(destroyed) {
  23654. if (destroyed) {
  23655. console.warn(formatRuntimeError(406 /* RuntimeErrorCode.APPLICATION_REF_ALREADY_DESTROYED */, 'This instance of the `ApplicationRef` has already been destroyed.'));
  23656. }
  23657. }
  23658. function remove(list, el) {
  23659. const index = list.indexOf(el);
  23660. if (index > -1) {
  23661. list.splice(index, 1);
  23662. }
  23663. }
  23664. function detectChangesInViewIfRequired(lView, notifyErrorHandler, isFirstPass, zonelessEnabled) {
  23665. // When re-checking, only check views which actually need it.
  23666. if (!isFirstPass && !requiresRefreshOrTraversal(lView)) {
  23667. return;
  23668. }
  23669. const mode = isFirstPass && !zonelessEnabled
  23670. ? // The first pass is always in Global mode, which includes `CheckAlways` views.
  23671. 0 /* ChangeDetectionMode.Global */
  23672. : // Only refresh views with the `RefreshView` flag or views is a changed signal
  23673. 1 /* ChangeDetectionMode.Targeted */;
  23674. detectChangesInternal(lView, notifyErrorHandler, mode);
  23675. }
  23676. /**
  23677. * Schedules triggering of a defer block for `on idle` and `on timer` conditions.
  23678. */
  23679. function scheduleDelayedTrigger(scheduleFn) {
  23680. const lView = getLView();
  23681. const tNode = getCurrentTNode();
  23682. renderPlaceholder(lView, tNode);
  23683. // Exit early to avoid invoking `scheduleFn`, which would
  23684. // add `setTimeout` call and potentially delay serialization
  23685. // on the server unnecessarily.
  23686. if (!shouldTriggerDeferBlock(0 /* TriggerType.Regular */, lView))
  23687. return;
  23688. const injector = lView[INJECTOR];
  23689. const lDetails = getLDeferBlockDetails(lView, tNode);
  23690. const cleanupFn = scheduleFn(() => triggerDeferBlock(0 /* TriggerType.Regular */, lView, tNode), injector);
  23691. storeTriggerCleanupFn(0 /* TriggerType.Regular */, lDetails, cleanupFn);
  23692. }
  23693. /**
  23694. * Schedules prefetching for `on idle` and `on timer` triggers.
  23695. *
  23696. * @param scheduleFn A function that does the scheduling.
  23697. */
  23698. function scheduleDelayedPrefetching(scheduleFn, trigger) {
  23699. if (typeof ngServerMode !== 'undefined' && ngServerMode)
  23700. return;
  23701. const lView = getLView();
  23702. const injector = lView[INJECTOR];
  23703. // Only trigger the scheduled trigger on the browser
  23704. // since we don't want to delay the server response.
  23705. const tNode = getCurrentTNode();
  23706. const tView = lView[TVIEW];
  23707. const tDetails = getTDeferBlockDetails(tView, tNode);
  23708. if (tDetails.loadingState === DeferDependenciesLoadingState.NOT_STARTED) {
  23709. const lDetails = getLDeferBlockDetails(lView, tNode);
  23710. const prefetch = () => triggerPrefetching(tDetails, lView, tNode);
  23711. const cleanupFn = scheduleFn(prefetch, injector);
  23712. storeTriggerCleanupFn(1 /* TriggerType.Prefetch */, lDetails, cleanupFn);
  23713. }
  23714. }
  23715. /**
  23716. * Schedules hydration triggering of a defer block for `on idle` and `on timer` conditions.
  23717. */
  23718. function scheduleDelayedHydrating(scheduleFn, lView, tNode) {
  23719. if (typeof ngServerMode !== 'undefined' && ngServerMode)
  23720. return;
  23721. // Only trigger the scheduled trigger on the browser
  23722. // since we don't want to delay the server response.
  23723. const injector = lView[INJECTOR];
  23724. const lDetails = getLDeferBlockDetails(lView, tNode);
  23725. const ssrUniqueId = lDetails[SSR_UNIQUE_ID];
  23726. ngDevMode && assertSsrIdDefined(ssrUniqueId);
  23727. const cleanupFn = scheduleFn(() => triggerHydrationFromBlockName(injector, ssrUniqueId), injector);
  23728. storeTriggerCleanupFn(2 /* TriggerType.Hydrate */, lDetails, cleanupFn);
  23729. }
  23730. /**
  23731. * Trigger prefetching of dependencies for a defer block.
  23732. *
  23733. * @param tDetails Static information about this defer block.
  23734. * @param lView LView of a host view.
  23735. * @param tNode TNode that represents a defer block.
  23736. */
  23737. function triggerPrefetching(tDetails, lView, tNode) {
  23738. triggerResourceLoading(tDetails, lView, tNode);
  23739. }
  23740. /**
  23741. * Trigger loading of defer block dependencies if the process hasn't started yet.
  23742. *
  23743. * @param tDetails Static information about this defer block.
  23744. * @param lView LView of a host view.
  23745. */
  23746. function triggerResourceLoading(tDetails, lView, tNode) {
  23747. const injector = lView[INJECTOR];
  23748. const tView = lView[TVIEW];
  23749. if (tDetails.loadingState !== DeferDependenciesLoadingState.NOT_STARTED) {
  23750. // If the loading status is different from initial one, it means that
  23751. // the loading of dependencies is in progress and there is nothing to do
  23752. // in this function. All details can be obtained from the `tDetails` object.
  23753. return tDetails.loadingPromise ?? Promise.resolve();
  23754. }
  23755. const lDetails = getLDeferBlockDetails(lView, tNode);
  23756. const primaryBlockTNode = getPrimaryBlockTNode(tView, tDetails);
  23757. // Switch from NOT_STARTED -> IN_PROGRESS state.
  23758. tDetails.loadingState = DeferDependenciesLoadingState.IN_PROGRESS;
  23759. // Prefetching is triggered, cleanup all registered prefetch triggers.
  23760. invokeTriggerCleanupFns(1 /* TriggerType.Prefetch */, lDetails);
  23761. let dependenciesFn = tDetails.dependencyResolverFn;
  23762. if (ngDevMode) {
  23763. // Check if dependency function interceptor is configured.
  23764. const deferDependencyInterceptor = injector.get(DEFER_BLOCK_DEPENDENCY_INTERCEPTOR, null, {
  23765. optional: true,
  23766. });
  23767. if (deferDependencyInterceptor) {
  23768. dependenciesFn = deferDependencyInterceptor.intercept(dependenciesFn);
  23769. }
  23770. }
  23771. // Indicate that an application is not stable and has a pending task.
  23772. const removeTask = injector.get(PendingTasks).add();
  23773. // The `dependenciesFn` might be `null` when all dependencies within
  23774. // a given defer block were eagerly referenced elsewhere in a file,
  23775. // thus no dynamic `import()`s were produced.
  23776. if (!dependenciesFn) {
  23777. tDetails.loadingPromise = Promise.resolve().then(() => {
  23778. tDetails.loadingPromise = null;
  23779. tDetails.loadingState = DeferDependenciesLoadingState.COMPLETE;
  23780. removeTask();
  23781. });
  23782. return tDetails.loadingPromise;
  23783. }
  23784. // Start downloading of defer block dependencies.
  23785. tDetails.loadingPromise = Promise.allSettled(dependenciesFn()).then((results) => {
  23786. let failed = false;
  23787. const directiveDefs = [];
  23788. const pipeDefs = [];
  23789. for (const result of results) {
  23790. if (result.status === 'fulfilled') {
  23791. const dependency = result.value;
  23792. const directiveDef = getComponentDef(dependency) || getDirectiveDef(dependency);
  23793. if (directiveDef) {
  23794. directiveDefs.push(directiveDef);
  23795. }
  23796. else {
  23797. const pipeDef = getPipeDef$1(dependency);
  23798. if (pipeDef) {
  23799. pipeDefs.push(pipeDef);
  23800. }
  23801. }
  23802. }
  23803. else {
  23804. failed = true;
  23805. break;
  23806. }
  23807. }
  23808. if (failed) {
  23809. tDetails.loadingState = DeferDependenciesLoadingState.FAILED;
  23810. if (tDetails.errorTmplIndex === null) {
  23811. const templateLocation = ngDevMode ? getTemplateLocationDetails(lView) : '';
  23812. const error = new RuntimeError(-750 /* RuntimeErrorCode.DEFER_LOADING_FAILED */, ngDevMode &&
  23813. 'Loading dependencies for `@defer` block failed, ' +
  23814. `but no \`@error\` block was configured${templateLocation}. ` +
  23815. 'Consider using the `@error` block to render an error state.');
  23816. handleError$1(lView, error);
  23817. }
  23818. }
  23819. else {
  23820. tDetails.loadingState = DeferDependenciesLoadingState.COMPLETE;
  23821. // Update directive and pipe registries to add newly downloaded dependencies.
  23822. const primaryBlockTView = primaryBlockTNode.tView;
  23823. if (directiveDefs.length > 0) {
  23824. primaryBlockTView.directiveRegistry = addDepsToRegistry(primaryBlockTView.directiveRegistry, directiveDefs);
  23825. // Extract providers from all NgModules imported by standalone components
  23826. // used within this defer block.
  23827. const directiveTypes = directiveDefs.map((def) => def.type);
  23828. const providers = internalImportProvidersFrom(false, ...directiveTypes);
  23829. tDetails.providers = providers;
  23830. }
  23831. if (pipeDefs.length > 0) {
  23832. primaryBlockTView.pipeRegistry = addDepsToRegistry(primaryBlockTView.pipeRegistry, pipeDefs);
  23833. }
  23834. }
  23835. });
  23836. return tDetails.loadingPromise.finally(() => {
  23837. // Loading is completed, we no longer need the loading Promise
  23838. // and a pending task should also be removed.
  23839. tDetails.loadingPromise = null;
  23840. removeTask();
  23841. });
  23842. }
  23843. /**
  23844. * Defines whether we should proceed with triggering a given defer block.
  23845. */
  23846. function shouldTriggerDeferBlock(triggerType, lView) {
  23847. // prevents triggering regular triggers when on the server.
  23848. if (triggerType === 0 /* TriggerType.Regular */ && typeof ngServerMode !== 'undefined' && ngServerMode) {
  23849. return false;
  23850. }
  23851. // prevents triggering in the case of a test run with manual defer block configuration.
  23852. const injector = lView[INJECTOR];
  23853. const config = injector.get(DEFER_BLOCK_CONFIG, null, { optional: true });
  23854. if (config?.behavior === DeferBlockBehavior.Manual) {
  23855. return false;
  23856. }
  23857. return true;
  23858. }
  23859. /**
  23860. * Attempts to trigger loading of defer block dependencies.
  23861. * If the block is already in a loading, completed or an error state -
  23862. * no additional actions are taken.
  23863. */
  23864. function triggerDeferBlock(triggerType, lView, tNode) {
  23865. const tView = lView[TVIEW];
  23866. const lContainer = lView[tNode.index];
  23867. ngDevMode && assertLContainer(lContainer);
  23868. if (!shouldTriggerDeferBlock(triggerType, lView))
  23869. return;
  23870. const lDetails = getLDeferBlockDetails(lView, tNode);
  23871. const tDetails = getTDeferBlockDetails(tView, tNode);
  23872. // Defer block is triggered, cleanup all registered trigger functions.
  23873. invokeAllTriggerCleanupFns(lDetails);
  23874. switch (tDetails.loadingState) {
  23875. case DeferDependenciesLoadingState.NOT_STARTED:
  23876. renderDeferBlockState(DeferBlockState.Loading, tNode, lContainer);
  23877. triggerResourceLoading(tDetails, lView, tNode);
  23878. // The `loadingState` might have changed to "loading".
  23879. if (tDetails.loadingState ===
  23880. DeferDependenciesLoadingState.IN_PROGRESS) {
  23881. renderDeferStateAfterResourceLoading(tDetails, tNode, lContainer);
  23882. }
  23883. break;
  23884. case DeferDependenciesLoadingState.IN_PROGRESS:
  23885. renderDeferBlockState(DeferBlockState.Loading, tNode, lContainer);
  23886. renderDeferStateAfterResourceLoading(tDetails, tNode, lContainer);
  23887. break;
  23888. case DeferDependenciesLoadingState.COMPLETE:
  23889. ngDevMode && assertDeferredDependenciesLoaded(tDetails);
  23890. renderDeferBlockState(DeferBlockState.Complete, tNode, lContainer);
  23891. break;
  23892. case DeferDependenciesLoadingState.FAILED:
  23893. renderDeferBlockState(DeferBlockState.Error, tNode, lContainer);
  23894. break;
  23895. default:
  23896. if (ngDevMode) {
  23897. throwError('Unknown defer block state');
  23898. }
  23899. }
  23900. }
  23901. /**
  23902. * The core mechanism for incremental hydration. This triggers or
  23903. * queues hydration for all the blocks in the tree that need to be hydrated
  23904. * and keeps track of all those blocks that were hydrated along the way.
  23905. *
  23906. * Note: the `replayQueuedEventsFn` is only provided when hydration is invoked
  23907. * as a result of an event replay (via JsAction). When hydration is invoked from
  23908. * an instruction set (e.g. `deferOnImmediate`) - there is no need to replay any
  23909. * events.
  23910. */
  23911. async function triggerHydrationFromBlockName(injector, blockName, replayQueuedEventsFn) {
  23912. const dehydratedBlockRegistry = injector.get(DEHYDRATED_BLOCK_REGISTRY);
  23913. const blocksBeingHydrated = dehydratedBlockRegistry.hydrating;
  23914. // Make sure we don't hydrate/trigger the same thing multiple times
  23915. if (blocksBeingHydrated.has(blockName)) {
  23916. return;
  23917. }
  23918. // Trigger resource loading and hydration for the blocks in the queue in the order of highest block
  23919. // to lowest block. Once a block has finished resource loading, after next render fires after hydration
  23920. // finishes. The new block will have its defer instruction called and will be in the registry.
  23921. // Due to timing related to potential nested control flow, this has to be scheduled after the next render.
  23922. const { parentBlockPromise, hydrationQueue } = getParentBlockHydrationQueue(blockName, injector);
  23923. if (hydrationQueue.length === 0)
  23924. return;
  23925. // It's possible that the hydrationQueue topmost item is actually in the process of hydrating and has
  23926. // a promise already. In that case, we don't want to destroy that promise and queue it again.
  23927. if (parentBlockPromise !== null) {
  23928. hydrationQueue.shift();
  23929. }
  23930. // The hydrating map in the registry prevents re-triggering hydration for a block that's already in
  23931. // the hydration queue. Here we generate promises for each of the blocks about to be hydrated
  23932. populateHydratingStateForQueue(dehydratedBlockRegistry, hydrationQueue);
  23933. // We await this after populating the hydration state so we can prevent re-triggering hydration for
  23934. // the same blocks while this promise is being awaited.
  23935. if (parentBlockPromise !== null) {
  23936. await parentBlockPromise;
  23937. }
  23938. const topmostParentBlock = hydrationQueue[0];
  23939. if (dehydratedBlockRegistry.has(topmostParentBlock)) {
  23940. // the topmost parent block is already in the registry and we can proceed
  23941. // with hydration.
  23942. await triggerHydrationForBlockQueue(injector, hydrationQueue, replayQueuedEventsFn);
  23943. }
  23944. else {
  23945. // the topmost parent block is not yet in the registry, which may mean
  23946. // a lazy loaded route, a control flow branch was taken, a route has
  23947. // been navigated, etc. So we need to queue up the hydration process
  23948. // so that it can be finished after the top block has had its defer
  23949. // instruction executed.
  23950. dehydratedBlockRegistry.awaitParentBlock(topmostParentBlock, async () => await triggerHydrationForBlockQueue(injector, hydrationQueue, replayQueuedEventsFn));
  23951. }
  23952. }
  23953. /**
  23954. * The core mechanism for incremental hydration. This triggers
  23955. * hydration for all the blocks in the tree that need to be hydrated
  23956. * and keeps track of all those blocks that were hydrated along the way.
  23957. *
  23958. * Note: the `replayQueuedEventsFn` is only provided when hydration is invoked
  23959. * as a result of an event replay (via JsAction). When hydration is invoked from
  23960. * an instruction set (e.g. `deferOnImmediate`) - there is no need to replay any
  23961. * events.
  23962. */
  23963. async function triggerHydrationForBlockQueue(injector, hydrationQueue, replayQueuedEventsFn) {
  23964. const dehydratedBlockRegistry = injector.get(DEHYDRATED_BLOCK_REGISTRY);
  23965. const blocksBeingHydrated = dehydratedBlockRegistry.hydrating;
  23966. // Indicate that we have some pending async work.
  23967. const pendingTasks = injector.get(PendingTasksInternal);
  23968. const taskId = pendingTasks.add();
  23969. // Actually do the triggering and hydration of the queue of blocks
  23970. for (let blockQueueIdx = 0; blockQueueIdx < hydrationQueue.length; blockQueueIdx++) {
  23971. const dehydratedBlockId = hydrationQueue[blockQueueIdx];
  23972. const dehydratedDeferBlock = dehydratedBlockRegistry.get(dehydratedBlockId);
  23973. if (dehydratedDeferBlock != null) {
  23974. // trigger the block resources and await next render for hydration. This should result
  23975. // in the next block ɵɵdefer instruction being called and that block being added to the dehydrated registry.
  23976. await triggerResourceLoadingForHydration(dehydratedDeferBlock);
  23977. await nextRender(injector);
  23978. // if the content has changed since server rendering, we need to check for the expected block
  23979. // being in the registry or if errors occurred. In that case, we need to clean up the remaining expected
  23980. // content that won't be rendered or fetched.
  23981. if (deferBlockHasErrored(dehydratedDeferBlock)) {
  23982. // Either the expected block has not yet had its ɵɵdefer instruction called or the block errored out when fetching
  23983. // resources. In the former case, either we're hydrating too soon or the client and server differ. In both cases,
  23984. // we need to clean up child content and promises.
  23985. removeDehydratedViewList(dehydratedDeferBlock);
  23986. cleanupRemainingHydrationQueue(hydrationQueue.slice(blockQueueIdx), dehydratedBlockRegistry);
  23987. break;
  23988. }
  23989. // The defer block has not errored and we've finished fetching resources and rendering.
  23990. // At this point it is safe to resolve the hydration promise.
  23991. blocksBeingHydrated.get(dehydratedBlockId).resolve();
  23992. }
  23993. else {
  23994. // The expected block has not yet had its ɵɵdefer instruction called. This is likely due to content changing between
  23995. // client and server. We need to clean up the dehydrated DOM in the container since it no longer is valid.
  23996. cleanupParentContainer(blockQueueIdx, hydrationQueue, dehydratedBlockRegistry);
  23997. cleanupRemainingHydrationQueue(hydrationQueue.slice(blockQueueIdx), dehydratedBlockRegistry);
  23998. break;
  23999. }
  24000. }
  24001. const lastBlockName = hydrationQueue[hydrationQueue.length - 1];
  24002. // Await hydration completion for the last block.
  24003. await blocksBeingHydrated.get(lastBlockName)?.promise;
  24004. // All async work is done, remove the taskId from the registry.
  24005. pendingTasks.remove(taskId);
  24006. // Replay any queued events, if any exist and the replay operation was requested.
  24007. if (replayQueuedEventsFn) {
  24008. replayQueuedEventsFn(hydrationQueue);
  24009. }
  24010. // Cleanup after hydration of all affected defer blocks.
  24011. cleanupHydratedDeferBlocks(dehydratedBlockRegistry.get(lastBlockName), hydrationQueue, dehydratedBlockRegistry, injector.get(ApplicationRef));
  24012. }
  24013. function deferBlockHasErrored(deferBlock) {
  24014. return (getLDeferBlockDetails(deferBlock.lView, deferBlock.tNode)[DEFER_BLOCK_STATE] ===
  24015. DeferBlockState.Error);
  24016. }
  24017. /**
  24018. * Clean up the parent container of a block where content changed between server and client.
  24019. * The parent of a block going through `triggerHydrationFromBlockName` will contain the
  24020. * dehydrated content that needs to be cleaned up. So we have to do the clean up from that location
  24021. * in the tree.
  24022. */
  24023. function cleanupParentContainer(currentBlockIdx, hydrationQueue, dehydratedBlockRegistry) {
  24024. // If a parent block exists, it's in the hydration queue in front of the current block.
  24025. const parentDeferBlockIdx = currentBlockIdx - 1;
  24026. const parentDeferBlock = parentDeferBlockIdx > -1
  24027. ? dehydratedBlockRegistry.get(hydrationQueue[parentDeferBlockIdx])
  24028. : null;
  24029. if (parentDeferBlock) {
  24030. cleanupLContainer(parentDeferBlock.lContainer);
  24031. }
  24032. }
  24033. function cleanupRemainingHydrationQueue(hydrationQueue, dehydratedBlockRegistry) {
  24034. const blocksBeingHydrated = dehydratedBlockRegistry.hydrating;
  24035. for (const dehydratedBlockId in hydrationQueue) {
  24036. blocksBeingHydrated.get(dehydratedBlockId)?.reject();
  24037. }
  24038. dehydratedBlockRegistry.cleanup(hydrationQueue);
  24039. }
  24040. /**
  24041. * Generates a new promise for every defer block in the hydrating queue
  24042. */
  24043. function populateHydratingStateForQueue(registry, queue) {
  24044. for (let blockId of queue) {
  24045. registry.hydrating.set(blockId, Promise.withResolvers());
  24046. }
  24047. }
  24048. // Waits for the next render cycle to complete
  24049. function nextRender(injector) {
  24050. return new Promise((resolveFn) => afterNextRender(resolveFn, { injector }));
  24051. }
  24052. async function triggerResourceLoadingForHydration(dehydratedBlock) {
  24053. const { tNode, lView } = dehydratedBlock;
  24054. const lDetails = getLDeferBlockDetails(lView, tNode);
  24055. return new Promise((resolve) => {
  24056. onDeferBlockCompletion(lDetails, resolve);
  24057. triggerDeferBlock(2 /* TriggerType.Hydrate */, lView, tNode);
  24058. });
  24059. }
  24060. /**
  24061. * Registers cleanup functions for a defer block when the block has finished
  24062. * fetching and rendering
  24063. */
  24064. function onDeferBlockCompletion(lDetails, callback) {
  24065. if (!Array.isArray(lDetails[ON_COMPLETE_FNS])) {
  24066. lDetails[ON_COMPLETE_FNS] = [];
  24067. }
  24068. lDetails[ON_COMPLETE_FNS].push(callback);
  24069. }
  24070. /**
  24071. * Determines whether specific trigger types should be attached during an instruction firing
  24072. * to ensure the proper triggers for a given type are used.
  24073. */
  24074. function shouldAttachTrigger(triggerType, lView, tNode) {
  24075. if (triggerType === 0 /* TriggerType.Regular */) {
  24076. return shouldAttachRegularTrigger(lView, tNode);
  24077. }
  24078. else if (triggerType === 2 /* TriggerType.Hydrate */) {
  24079. return !shouldAttachRegularTrigger(lView, tNode);
  24080. }
  24081. // TriggerType.Prefetch is active only on the client
  24082. return !(typeof ngServerMode !== 'undefined' && ngServerMode);
  24083. }
  24084. /**
  24085. * Defines whether a regular trigger logic (e.g. "on viewport") should be attached
  24086. * to a defer block. This function defines a condition, which mutually excludes
  24087. * `deferOn*` and `deferHydrateOn*` triggers, to make sure only one of the trigger
  24088. * types is active for a block with the current state.
  24089. */
  24090. function shouldAttachRegularTrigger(lView, tNode) {
  24091. const injector = lView[INJECTOR];
  24092. const tDetails = getTDeferBlockDetails(lView[TVIEW], tNode);
  24093. const incrementalHydrationEnabled = isIncrementalHydrationEnabled(injector);
  24094. const hasHydrateTriggers = tDetails.flags !== null &&
  24095. (tDetails.flags & 1 /* TDeferDetailsFlags.HasHydrateTriggers */) ===
  24096. 1 /* TDeferDetailsFlags.HasHydrateTriggers */;
  24097. // On the server:
  24098. if (typeof ngServerMode !== 'undefined' && ngServerMode) {
  24099. // Regular triggers are activated on the server when:
  24100. // - Either Incremental Hydration is *not* enabled
  24101. // - Or Incremental Hydration is enabled, but a given block doesn't have "hydrate" triggers
  24102. return !incrementalHydrationEnabled || !hasHydrateTriggers;
  24103. }
  24104. // On the client:
  24105. const lDetails = getLDeferBlockDetails(lView, tNode);
  24106. const wasServerSideRendered = lDetails[SSR_UNIQUE_ID] !== null;
  24107. if (hasHydrateTriggers && wasServerSideRendered && incrementalHydrationEnabled) {
  24108. return false;
  24109. }
  24110. return true;
  24111. }
  24112. /**
  24113. * Retrives a Defer Block's list of hydration triggers
  24114. */
  24115. function getHydrateTriggers(tView, tNode) {
  24116. const tDetails = getTDeferBlockDetails(tView, tNode);
  24117. return (tDetails.hydrateTriggers ??= new Map());
  24118. }
  24119. /**
  24120. * Loops through all defer block summaries and ensures all the blocks triggers are
  24121. * properly initialized
  24122. */
  24123. function processAndInitTriggers(injector, blockData, nodes) {
  24124. const idleElements = [];
  24125. const timerElements = [];
  24126. const viewportElements = [];
  24127. const immediateElements = [];
  24128. for (let [blockId, blockSummary] of blockData) {
  24129. const commentNode = nodes.get(blockId);
  24130. if (commentNode !== undefined) {
  24131. const numRootNodes = blockSummary.data[NUM_ROOT_NODES];
  24132. let currentNode = commentNode;
  24133. for (let i = 0; i < numRootNodes; i++) {
  24134. currentNode = currentNode.previousSibling;
  24135. if (currentNode.nodeType !== Node.ELEMENT_NODE) {
  24136. continue;
  24137. }
  24138. const elementTrigger = { el: currentNode, blockName: blockId };
  24139. // hydrate
  24140. if (blockSummary.hydrate.idle) {
  24141. idleElements.push(elementTrigger);
  24142. }
  24143. if (blockSummary.hydrate.immediate) {
  24144. immediateElements.push(elementTrigger);
  24145. }
  24146. if (blockSummary.hydrate.timer !== null) {
  24147. elementTrigger.delay = blockSummary.hydrate.timer;
  24148. timerElements.push(elementTrigger);
  24149. }
  24150. if (blockSummary.hydrate.viewport) {
  24151. viewportElements.push(elementTrigger);
  24152. }
  24153. }
  24154. }
  24155. }
  24156. setIdleTriggers(injector, idleElements);
  24157. setImmediateTriggers(injector, immediateElements);
  24158. setViewportTriggers(injector, viewportElements);
  24159. setTimerTriggers(injector, timerElements);
  24160. }
  24161. function setIdleTriggers(injector, elementTriggers) {
  24162. for (const elementTrigger of elementTriggers) {
  24163. const registry = injector.get(DEHYDRATED_BLOCK_REGISTRY);
  24164. const onInvoke = () => triggerHydrationFromBlockName(injector, elementTrigger.blockName);
  24165. const cleanupFn = onIdle(onInvoke, injector);
  24166. registry.addCleanupFn(elementTrigger.blockName, cleanupFn);
  24167. }
  24168. }
  24169. function setViewportTriggers(injector, elementTriggers) {
  24170. if (elementTriggers.length > 0) {
  24171. const registry = injector.get(DEHYDRATED_BLOCK_REGISTRY);
  24172. for (let elementTrigger of elementTriggers) {
  24173. const cleanupFn = onViewport(elementTrigger.el, () => triggerHydrationFromBlockName(injector, elementTrigger.blockName), injector);
  24174. registry.addCleanupFn(elementTrigger.blockName, cleanupFn);
  24175. }
  24176. }
  24177. }
  24178. function setTimerTriggers(injector, elementTriggers) {
  24179. for (const elementTrigger of elementTriggers) {
  24180. const registry = injector.get(DEHYDRATED_BLOCK_REGISTRY);
  24181. const onInvoke = () => triggerHydrationFromBlockName(injector, elementTrigger.blockName);
  24182. const timerFn = onTimer(elementTrigger.delay);
  24183. const cleanupFn = timerFn(onInvoke, injector);
  24184. registry.addCleanupFn(elementTrigger.blockName, cleanupFn);
  24185. }
  24186. }
  24187. function setImmediateTriggers(injector, elementTriggers) {
  24188. for (const elementTrigger of elementTriggers) {
  24189. // Note: we intentionally avoid awaiting each call and instead kick off
  24190. // the hydration process simultaneously for all defer blocks with this trigger;
  24191. triggerHydrationFromBlockName(injector, elementTrigger.blockName);
  24192. }
  24193. }
  24194. /**
  24195. * Indicates whether we've already produced a warning,
  24196. * prevents the logic from producing it multiple times.
  24197. */
  24198. let _hmrWarningProduced = false;
  24199. /**
  24200. * Logs a message into the console to indicate that `@defer` block
  24201. * dependencies are loaded eagerly when the HMR mode is enabled.
  24202. */
  24203. function logHmrWarning(injector) {
  24204. if (!_hmrWarningProduced) {
  24205. _hmrWarningProduced = true;
  24206. const console = injector.get(Console);
  24207. // tslint:disable-next-line:no-console
  24208. console.log(formatRuntimeError(-751 /* RuntimeErrorCode.DEFER_IN_HMR_MODE */, 'Angular has detected that this application contains `@defer` blocks ' +
  24209. 'and the hot module replacement (HMR) mode is enabled. All `@defer` ' +
  24210. 'block dependencies will be loaded eagerly.'));
  24211. }
  24212. }
  24213. /**
  24214. * Creates runtime data structures for defer blocks.
  24215. *
  24216. * @param index Index of the `defer` instruction.
  24217. * @param primaryTmplIndex Index of the template with the primary block content.
  24218. * @param dependencyResolverFn Function that contains dependencies for this defer block.
  24219. * @param loadingTmplIndex Index of the template with the loading block content.
  24220. * @param placeholderTmplIndex Index of the template with the placeholder block content.
  24221. * @param errorTmplIndex Index of the template with the error block content.
  24222. * @param loadingConfigIndex Index in the constants array of the configuration of the loading.
  24223. * block.
  24224. * @param placeholderConfigIndex Index in the constants array of the configuration of the
  24225. * placeholder block.
  24226. * @param enableTimerScheduling Function that enables timer-related scheduling if `after`
  24227. * or `minimum` parameters are setup on the `@loading` or `@placeholder` blocks.
  24228. * @param flags A set of flags to define a particular behavior (e.g. to indicate that
  24229. * hydrate triggers are present and regular triggers should be deactivated
  24230. * in certain scenarios).
  24231. *
  24232. * @codeGenApi
  24233. */
  24234. function ɵɵdefer(index, primaryTmplIndex, dependencyResolverFn, loadingTmplIndex, placeholderTmplIndex, errorTmplIndex, loadingConfigIndex, placeholderConfigIndex, enableTimerScheduling, flags) {
  24235. const lView = getLView();
  24236. const tView = getTView();
  24237. const adjustedIndex = index + HEADER_OFFSET;
  24238. const tNode = declareTemplate(lView, tView, index, null, 0, 0);
  24239. const injector = lView[INJECTOR];
  24240. if (tView.firstCreatePass) {
  24241. performanceMarkFeature('NgDefer');
  24242. if (ngDevMode && typeof ngHmrMode !== 'undefined' && ngHmrMode) {
  24243. logHmrWarning(injector);
  24244. }
  24245. const tDetails = {
  24246. primaryTmplIndex,
  24247. loadingTmplIndex: loadingTmplIndex ?? null,
  24248. placeholderTmplIndex: placeholderTmplIndex ?? null,
  24249. errorTmplIndex: errorTmplIndex ?? null,
  24250. placeholderBlockConfig: null,
  24251. loadingBlockConfig: null,
  24252. dependencyResolverFn: dependencyResolverFn ?? null,
  24253. loadingState: DeferDependenciesLoadingState.NOT_STARTED,
  24254. loadingPromise: null,
  24255. providers: null,
  24256. hydrateTriggers: null,
  24257. debug: null,
  24258. flags: flags ?? 0 /* TDeferDetailsFlags.Default */,
  24259. };
  24260. enableTimerScheduling?.(tView, tDetails, placeholderConfigIndex, loadingConfigIndex);
  24261. setTDeferBlockDetails(tView, adjustedIndex, tDetails);
  24262. }
  24263. const lContainer = lView[adjustedIndex];
  24264. // If hydration is enabled, looks up dehydrated views in the DOM
  24265. // using hydration annotation info and stores those views on LContainer.
  24266. // In client-only mode, this function is a noop.
  24267. populateDehydratedViewsInLContainer(lContainer, tNode, lView);
  24268. let ssrBlockState = null;
  24269. let ssrUniqueId = null;
  24270. if (lContainer[DEHYDRATED_VIEWS]?.length > 0) {
  24271. const info = lContainer[DEHYDRATED_VIEWS][0].data;
  24272. ssrUniqueId = info[DEFER_BLOCK_ID] ?? null;
  24273. ssrBlockState = info[DEFER_BLOCK_STATE$1];
  24274. }
  24275. // Init instance-specific defer details and store it.
  24276. const lDetails = [
  24277. null, // NEXT_DEFER_BLOCK_STATE
  24278. DeferBlockInternalState.Initial, // DEFER_BLOCK_STATE
  24279. null, // STATE_IS_FROZEN_UNTIL
  24280. null, // LOADING_AFTER_CLEANUP_FN
  24281. null, // TRIGGER_CLEANUP_FNS
  24282. null, // PREFETCH_TRIGGER_CLEANUP_FNS
  24283. ssrUniqueId, // SSR_UNIQUE_ID
  24284. ssrBlockState, // SSR_BLOCK_STATE
  24285. null, // ON_COMPLETE_FNS
  24286. null, // HYDRATE_TRIGGER_CLEANUP_FNS
  24287. ];
  24288. setLDeferBlockDetails(lView, adjustedIndex, lDetails);
  24289. let registry = null;
  24290. if (ssrUniqueId !== null) {
  24291. ngDevMode && assertIncrementalHydrationIsConfigured(injector);
  24292. // Store this defer block in the registry, to have an access to
  24293. // internal data structures from hydration runtime code.
  24294. registry = injector.get(DEHYDRATED_BLOCK_REGISTRY);
  24295. registry.add(ssrUniqueId, { lView, tNode, lContainer });
  24296. }
  24297. const onLViewDestroy = () => {
  24298. invokeAllTriggerCleanupFns(lDetails);
  24299. if (ssrUniqueId !== null) {
  24300. registry?.cleanup([ssrUniqueId]);
  24301. }
  24302. };
  24303. // When defer block is triggered - unsubscribe from LView destroy cleanup.
  24304. storeTriggerCleanupFn(0 /* TriggerType.Regular */, lDetails, () => removeLViewOnDestroy(lView, onLViewDestroy));
  24305. storeLViewOnDestroy(lView, onLViewDestroy);
  24306. }
  24307. /**
  24308. * Loads defer block dependencies when a trigger value becomes truthy.
  24309. * @codeGenApi
  24310. */
  24311. function ɵɵdeferWhen(rawValue) {
  24312. const lView = getLView();
  24313. const tNode = getSelectedTNode();
  24314. if (ngDevMode) {
  24315. trackTriggerForDebugging(lView[TVIEW], tNode, 'when <expression>');
  24316. }
  24317. if (!shouldAttachTrigger(0 /* TriggerType.Regular */, lView, tNode))
  24318. return;
  24319. const bindingIndex = nextBindingIndex();
  24320. if (bindingUpdated(lView, bindingIndex, rawValue)) {
  24321. const prevConsumer = setActiveConsumer$1(null);
  24322. try {
  24323. const value = Boolean(rawValue); // handle truthy or falsy values
  24324. const lDetails = getLDeferBlockDetails(lView, tNode);
  24325. const renderedState = lDetails[DEFER_BLOCK_STATE];
  24326. if (value === false && renderedState === DeferBlockInternalState.Initial) {
  24327. // If nothing is rendered yet, render a placeholder (if defined).
  24328. renderPlaceholder(lView, tNode);
  24329. }
  24330. else if (value === true &&
  24331. (renderedState === DeferBlockInternalState.Initial ||
  24332. renderedState === DeferBlockState.Placeholder)) {
  24333. triggerDeferBlock(0 /* TriggerType.Regular */, lView, tNode);
  24334. }
  24335. }
  24336. finally {
  24337. setActiveConsumer$1(prevConsumer);
  24338. }
  24339. }
  24340. }
  24341. /**
  24342. * Prefetches the deferred content when a value becomes truthy.
  24343. * @codeGenApi
  24344. */
  24345. function ɵɵdeferPrefetchWhen(rawValue) {
  24346. const lView = getLView();
  24347. const tNode = getSelectedTNode();
  24348. if (ngDevMode) {
  24349. trackTriggerForDebugging(lView[TVIEW], tNode, 'prefetch when <expression>');
  24350. }
  24351. if (!shouldAttachTrigger(1 /* TriggerType.Prefetch */, lView, tNode))
  24352. return;
  24353. const bindingIndex = nextBindingIndex();
  24354. if (bindingUpdated(lView, bindingIndex, rawValue)) {
  24355. const prevConsumer = setActiveConsumer$1(null);
  24356. try {
  24357. const value = Boolean(rawValue); // handle truthy or falsy values
  24358. const tView = lView[TVIEW];
  24359. const tNode = getSelectedTNode();
  24360. const tDetails = getTDeferBlockDetails(tView, tNode);
  24361. if (value === true && tDetails.loadingState === DeferDependenciesLoadingState.NOT_STARTED) {
  24362. // If loading has not been started yet, trigger it now.
  24363. triggerPrefetching(tDetails, lView, tNode);
  24364. }
  24365. }
  24366. finally {
  24367. setActiveConsumer$1(prevConsumer);
  24368. }
  24369. }
  24370. }
  24371. /**
  24372. * Hydrates the deferred content when a value becomes truthy.
  24373. * @codeGenApi
  24374. */
  24375. function ɵɵdeferHydrateWhen(rawValue) {
  24376. const lView = getLView();
  24377. const tNode = getSelectedTNode();
  24378. if (ngDevMode) {
  24379. trackTriggerForDebugging(lView[TVIEW], tNode, 'hydrate when <expression>');
  24380. }
  24381. if (!shouldAttachTrigger(2 /* TriggerType.Hydrate */, lView, tNode))
  24382. return;
  24383. // TODO(incremental-hydration): audit all defer instructions to reduce unnecessary work by
  24384. // moving function calls inside their relevant control flow blocks
  24385. const bindingIndex = nextBindingIndex();
  24386. const tView = getTView();
  24387. const hydrateTriggers = getHydrateTriggers(tView, tNode);
  24388. hydrateTriggers.set(6 /* DeferBlockTrigger.When */, null);
  24389. if (bindingUpdated(lView, bindingIndex, rawValue)) {
  24390. if (typeof ngServerMode !== 'undefined' && ngServerMode) {
  24391. // We are on the server and SSR for defer blocks is enabled.
  24392. triggerDeferBlock(2 /* TriggerType.Hydrate */, lView, tNode);
  24393. }
  24394. else {
  24395. const injector = lView[INJECTOR];
  24396. const prevConsumer = setActiveConsumer$1(null);
  24397. try {
  24398. const value = Boolean(rawValue); // handle truthy or falsy values
  24399. if (value === true) {
  24400. // The `when` condition has changed to `true`, trigger defer block loading
  24401. // if the block is either in initial (nothing is rendered) or a placeholder
  24402. // state.
  24403. const lDetails = getLDeferBlockDetails(lView, tNode);
  24404. const ssrUniqueId = lDetails[SSR_UNIQUE_ID];
  24405. ngDevMode && assertSsrIdDefined(ssrUniqueId);
  24406. triggerHydrationFromBlockName(injector, ssrUniqueId);
  24407. }
  24408. }
  24409. finally {
  24410. setActiveConsumer$1(prevConsumer);
  24411. }
  24412. }
  24413. }
  24414. }
  24415. /**
  24416. * Specifies that hydration never occurs.
  24417. * @codeGenApi
  24418. */
  24419. function ɵɵdeferHydrateNever() {
  24420. const lView = getLView();
  24421. const tNode = getCurrentTNode();
  24422. if (ngDevMode) {
  24423. trackTriggerForDebugging(lView[TVIEW], tNode, 'hydrate never');
  24424. }
  24425. if (!shouldAttachTrigger(2 /* TriggerType.Hydrate */, lView, tNode))
  24426. return;
  24427. const hydrateTriggers = getHydrateTriggers(getTView(), tNode);
  24428. hydrateTriggers.set(7 /* DeferBlockTrigger.Never */, null);
  24429. if (typeof ngServerMode !== 'undefined' && ngServerMode) {
  24430. // We are on the server and SSR for defer blocks is enabled.
  24431. triggerDeferBlock(2 /* TriggerType.Hydrate */, lView, tNode);
  24432. }
  24433. }
  24434. /**
  24435. * Sets up logic to handle the `on idle` deferred trigger.
  24436. * @codeGenApi
  24437. */
  24438. function ɵɵdeferOnIdle() {
  24439. const lView = getLView();
  24440. const tNode = getCurrentTNode();
  24441. if (ngDevMode) {
  24442. trackTriggerForDebugging(lView[TVIEW], tNode, 'on idle');
  24443. }
  24444. if (!shouldAttachTrigger(0 /* TriggerType.Regular */, lView, tNode))
  24445. return;
  24446. scheduleDelayedTrigger(onIdle);
  24447. }
  24448. /**
  24449. * Sets up logic to handle the `prefetch on idle` deferred trigger.
  24450. * @codeGenApi
  24451. */
  24452. function ɵɵdeferPrefetchOnIdle() {
  24453. const lView = getLView();
  24454. const tNode = getCurrentTNode();
  24455. if (ngDevMode) {
  24456. trackTriggerForDebugging(lView[TVIEW], tNode, 'prefetch on idle');
  24457. }
  24458. if (!shouldAttachTrigger(1 /* TriggerType.Prefetch */, lView, tNode))
  24459. return;
  24460. scheduleDelayedPrefetching(onIdle);
  24461. }
  24462. /**
  24463. * Sets up logic to handle the `on idle` deferred trigger.
  24464. * @codeGenApi
  24465. */
  24466. function ɵɵdeferHydrateOnIdle() {
  24467. const lView = getLView();
  24468. const tNode = getCurrentTNode();
  24469. if (ngDevMode) {
  24470. trackTriggerForDebugging(lView[TVIEW], tNode, 'hydrate on idle');
  24471. }
  24472. if (!shouldAttachTrigger(2 /* TriggerType.Hydrate */, lView, tNode))
  24473. return;
  24474. const hydrateTriggers = getHydrateTriggers(getTView(), tNode);
  24475. hydrateTriggers.set(0 /* DeferBlockTrigger.Idle */, null);
  24476. if (typeof ngServerMode !== 'undefined' && ngServerMode) {
  24477. // We are on the server and SSR for defer blocks is enabled.
  24478. triggerDeferBlock(2 /* TriggerType.Hydrate */, lView, tNode);
  24479. }
  24480. else {
  24481. scheduleDelayedHydrating(onIdle, lView, tNode);
  24482. }
  24483. }
  24484. /**
  24485. * Sets up logic to handle the `on immediate` deferred trigger.
  24486. * @codeGenApi
  24487. */
  24488. function ɵɵdeferOnImmediate() {
  24489. const lView = getLView();
  24490. const tNode = getCurrentTNode();
  24491. if (ngDevMode) {
  24492. trackTriggerForDebugging(lView[TVIEW], tNode, 'on immediate');
  24493. }
  24494. if (!shouldAttachTrigger(0 /* TriggerType.Regular */, lView, tNode))
  24495. return;
  24496. // Render placeholder block only if loading template is not present and we're on
  24497. // the client to avoid content flickering, since it would be immediately replaced
  24498. // by the loading block.
  24499. const tDetails = getTDeferBlockDetails(lView[TVIEW], tNode);
  24500. if (tDetails.loadingTmplIndex === null) {
  24501. renderPlaceholder(lView, tNode);
  24502. }
  24503. triggerDeferBlock(0 /* TriggerType.Regular */, lView, tNode);
  24504. }
  24505. /**
  24506. * Sets up logic to handle the `prefetch on immediate` deferred trigger.
  24507. * @codeGenApi
  24508. */
  24509. function ɵɵdeferPrefetchOnImmediate() {
  24510. const lView = getLView();
  24511. const tNode = getCurrentTNode();
  24512. if (ngDevMode) {
  24513. trackTriggerForDebugging(lView[TVIEW], tNode, 'prefetch on immediate');
  24514. }
  24515. if (!shouldAttachTrigger(1 /* TriggerType.Prefetch */, lView, tNode))
  24516. return;
  24517. const tView = lView[TVIEW];
  24518. const tDetails = getTDeferBlockDetails(tView, tNode);
  24519. if (tDetails.loadingState === DeferDependenciesLoadingState.NOT_STARTED) {
  24520. triggerResourceLoading(tDetails, lView, tNode);
  24521. }
  24522. }
  24523. /**
  24524. * Sets up logic to handle the `on immediate` hydrate trigger.
  24525. * @codeGenApi
  24526. */
  24527. function ɵɵdeferHydrateOnImmediate() {
  24528. const lView = getLView();
  24529. const tNode = getCurrentTNode();
  24530. if (ngDevMode) {
  24531. trackTriggerForDebugging(lView[TVIEW], tNode, 'hydrate on immediate');
  24532. }
  24533. if (!shouldAttachTrigger(2 /* TriggerType.Hydrate */, lView, tNode))
  24534. return;
  24535. const hydrateTriggers = getHydrateTriggers(getTView(), tNode);
  24536. hydrateTriggers.set(1 /* DeferBlockTrigger.Immediate */, null);
  24537. if (typeof ngServerMode !== 'undefined' && ngServerMode) {
  24538. triggerDeferBlock(2 /* TriggerType.Hydrate */, lView, tNode);
  24539. }
  24540. else {
  24541. const injector = lView[INJECTOR];
  24542. const lDetails = getLDeferBlockDetails(lView, tNode);
  24543. const ssrUniqueId = lDetails[SSR_UNIQUE_ID];
  24544. ngDevMode && assertSsrIdDefined(ssrUniqueId);
  24545. triggerHydrationFromBlockName(injector, ssrUniqueId);
  24546. }
  24547. }
  24548. /**
  24549. * Creates runtime data structures for the `on timer` deferred trigger.
  24550. * @param delay Amount of time to wait before loading the content.
  24551. * @codeGenApi
  24552. */
  24553. function ɵɵdeferOnTimer(delay) {
  24554. const lView = getLView();
  24555. const tNode = getCurrentTNode();
  24556. if (ngDevMode) {
  24557. trackTriggerForDebugging(lView[TVIEW], tNode, `on timer(${delay}ms)`);
  24558. }
  24559. if (!shouldAttachTrigger(0 /* TriggerType.Regular */, lView, tNode))
  24560. return;
  24561. scheduleDelayedTrigger(onTimer(delay));
  24562. }
  24563. /**
  24564. * Creates runtime data structures for the `prefetch on timer` deferred trigger.
  24565. * @param delay Amount of time to wait before prefetching the content.
  24566. * @codeGenApi
  24567. */
  24568. function ɵɵdeferPrefetchOnTimer(delay) {
  24569. const lView = getLView();
  24570. const tNode = getCurrentTNode();
  24571. if (ngDevMode) {
  24572. trackTriggerForDebugging(lView[TVIEW], tNode, `prefetch on timer(${delay}ms)`);
  24573. }
  24574. if (!shouldAttachTrigger(1 /* TriggerType.Prefetch */, lView, tNode))
  24575. return;
  24576. scheduleDelayedPrefetching(onTimer(delay));
  24577. }
  24578. /**
  24579. * Creates runtime data structures for the `on timer` hydrate trigger.
  24580. * @param delay Amount of time to wait before loading the content.
  24581. * @codeGenApi
  24582. */
  24583. function ɵɵdeferHydrateOnTimer(delay) {
  24584. const lView = getLView();
  24585. const tNode = getCurrentTNode();
  24586. if (ngDevMode) {
  24587. trackTriggerForDebugging(lView[TVIEW], tNode, `hydrate on timer(${delay}ms)`);
  24588. }
  24589. if (!shouldAttachTrigger(2 /* TriggerType.Hydrate */, lView, tNode))
  24590. return;
  24591. const hydrateTriggers = getHydrateTriggers(getTView(), tNode);
  24592. hydrateTriggers.set(5 /* DeferBlockTrigger.Timer */, { delay });
  24593. if (typeof ngServerMode !== 'undefined' && ngServerMode) {
  24594. // We are on the server and SSR for defer blocks is enabled.
  24595. triggerDeferBlock(2 /* TriggerType.Hydrate */, lView, tNode);
  24596. }
  24597. else {
  24598. scheduleDelayedHydrating(onTimer(delay), lView, tNode);
  24599. }
  24600. }
  24601. /**
  24602. * Creates runtime data structures for the `on hover` deferred trigger.
  24603. * @param triggerIndex Index at which to find the trigger element.
  24604. * @param walkUpTimes Number of times to walk up/down the tree hierarchy to find the trigger.
  24605. * @codeGenApi
  24606. */
  24607. function ɵɵdeferOnHover(triggerIndex, walkUpTimes) {
  24608. const lView = getLView();
  24609. const tNode = getCurrentTNode();
  24610. if (ngDevMode) {
  24611. trackTriggerForDebugging(lView[TVIEW], tNode, `on hover${walkUpTimes === -1 ? '' : '(<target>)'}`);
  24612. }
  24613. if (!shouldAttachTrigger(0 /* TriggerType.Regular */, lView, tNode))
  24614. return;
  24615. renderPlaceholder(lView, tNode);
  24616. // Avoid adding event listeners when this instruction is invoked on the server.
  24617. if (!(typeof ngServerMode !== 'undefined' && ngServerMode)) {
  24618. registerDomTrigger(lView, tNode, triggerIndex, walkUpTimes, onHover, () => triggerDeferBlock(0 /* TriggerType.Regular */, lView, tNode), 0 /* TriggerType.Regular */);
  24619. }
  24620. }
  24621. /**
  24622. * Creates runtime data structures for the `prefetch on hover` deferred trigger.
  24623. * @param triggerIndex Index at which to find the trigger element.
  24624. * @param walkUpTimes Number of times to walk up/down the tree hierarchy to find the trigger.
  24625. * @codeGenApi
  24626. */
  24627. function ɵɵdeferPrefetchOnHover(triggerIndex, walkUpTimes) {
  24628. const lView = getLView();
  24629. const tNode = getCurrentTNode();
  24630. if (ngDevMode) {
  24631. trackTriggerForDebugging(lView[TVIEW], tNode, `prefetch on hover${walkUpTimes === -1 ? '' : '(<target>)'}`);
  24632. }
  24633. if (!shouldAttachTrigger(1 /* TriggerType.Prefetch */, lView, tNode))
  24634. return;
  24635. const tView = lView[TVIEW];
  24636. const tDetails = getTDeferBlockDetails(tView, tNode);
  24637. if (tDetails.loadingState === DeferDependenciesLoadingState.NOT_STARTED) {
  24638. registerDomTrigger(lView, tNode, triggerIndex, walkUpTimes, onHover, () => triggerPrefetching(tDetails, lView, tNode), 1 /* TriggerType.Prefetch */);
  24639. }
  24640. }
  24641. /**
  24642. * Creates runtime data structures for the `on hover` hydrate trigger.
  24643. * @codeGenApi
  24644. */
  24645. function ɵɵdeferHydrateOnHover() {
  24646. const lView = getLView();
  24647. const tNode = getCurrentTNode();
  24648. if (ngDevMode) {
  24649. trackTriggerForDebugging(lView[TVIEW], tNode, 'hydrate on hover');
  24650. }
  24651. if (!shouldAttachTrigger(2 /* TriggerType.Hydrate */, lView, tNode))
  24652. return;
  24653. const hydrateTriggers = getHydrateTriggers(getTView(), tNode);
  24654. hydrateTriggers.set(4 /* DeferBlockTrigger.Hover */, null);
  24655. if (typeof ngServerMode !== 'undefined' && ngServerMode) {
  24656. // We are on the server and SSR for defer blocks is enabled.
  24657. triggerDeferBlock(2 /* TriggerType.Hydrate */, lView, tNode);
  24658. }
  24659. // The actual triggering of hydration on hover is handled by JSAction in
  24660. // event_replay.ts.
  24661. }
  24662. /**
  24663. * Creates runtime data structures for the `on interaction` deferred trigger.
  24664. * @param triggerIndex Index at which to find the trigger element.
  24665. * @param walkUpTimes Number of times to walk up/down the tree hierarchy to find the trigger.
  24666. * @codeGenApi
  24667. */
  24668. function ɵɵdeferOnInteraction(triggerIndex, walkUpTimes) {
  24669. const lView = getLView();
  24670. const tNode = getCurrentTNode();
  24671. if (ngDevMode) {
  24672. trackTriggerForDebugging(lView[TVIEW], tNode, `on interaction${walkUpTimes === -1 ? '' : '(<target>)'}`);
  24673. }
  24674. if (!shouldAttachTrigger(0 /* TriggerType.Regular */, lView, tNode))
  24675. return;
  24676. renderPlaceholder(lView, tNode);
  24677. // Avoid adding event listeners when this instruction is invoked on the server.
  24678. if (!(typeof ngServerMode !== 'undefined' && ngServerMode)) {
  24679. registerDomTrigger(lView, tNode, triggerIndex, walkUpTimes, onInteraction, () => triggerDeferBlock(0 /* TriggerType.Regular */, lView, tNode), 0 /* TriggerType.Regular */);
  24680. }
  24681. }
  24682. /**
  24683. * Creates runtime data structures for the `prefetch on interaction` deferred trigger.
  24684. * @param triggerIndex Index at which to find the trigger element.
  24685. * @param walkUpTimes Number of times to walk up/down the tree hierarchy to find the trigger.
  24686. * @codeGenApi
  24687. */
  24688. function ɵɵdeferPrefetchOnInteraction(triggerIndex, walkUpTimes) {
  24689. const lView = getLView();
  24690. const tNode = getCurrentTNode();
  24691. if (ngDevMode) {
  24692. trackTriggerForDebugging(lView[TVIEW], tNode, `prefetch on interaction${walkUpTimes === -1 ? '' : '(<target>)'}`);
  24693. }
  24694. if (!shouldAttachTrigger(1 /* TriggerType.Prefetch */, lView, tNode))
  24695. return;
  24696. const tView = lView[TVIEW];
  24697. const tDetails = getTDeferBlockDetails(tView, tNode);
  24698. if (tDetails.loadingState === DeferDependenciesLoadingState.NOT_STARTED) {
  24699. registerDomTrigger(lView, tNode, triggerIndex, walkUpTimes, onInteraction, () => triggerPrefetching(tDetails, lView, tNode), 1 /* TriggerType.Prefetch */);
  24700. }
  24701. }
  24702. /**
  24703. * Creates runtime data structures for the `on interaction` hydrate trigger.
  24704. * @codeGenApi
  24705. */
  24706. function ɵɵdeferHydrateOnInteraction() {
  24707. const lView = getLView();
  24708. const tNode = getCurrentTNode();
  24709. if (ngDevMode) {
  24710. trackTriggerForDebugging(lView[TVIEW], tNode, 'hydrate on interaction');
  24711. }
  24712. if (!shouldAttachTrigger(2 /* TriggerType.Hydrate */, lView, tNode))
  24713. return;
  24714. const hydrateTriggers = getHydrateTriggers(getTView(), tNode);
  24715. hydrateTriggers.set(3 /* DeferBlockTrigger.Interaction */, null);
  24716. if (typeof ngServerMode !== 'undefined' && ngServerMode) {
  24717. // We are on the server and SSR for defer blocks is enabled.
  24718. triggerDeferBlock(2 /* TriggerType.Hydrate */, lView, tNode);
  24719. }
  24720. // The actual triggering of hydration on interaction is handled by JSAction in
  24721. // event_replay.ts.
  24722. }
  24723. /**
  24724. * Creates runtime data structures for the `on viewport` deferred trigger.
  24725. * @param triggerIndex Index at which to find the trigger element.
  24726. * @param walkUpTimes Number of times to walk up/down the tree hierarchy to find the trigger.
  24727. * @codeGenApi
  24728. */
  24729. function ɵɵdeferOnViewport(triggerIndex, walkUpTimes) {
  24730. const lView = getLView();
  24731. const tNode = getCurrentTNode();
  24732. if (ngDevMode) {
  24733. trackTriggerForDebugging(lView[TVIEW], tNode, `on viewport${walkUpTimes === -1 ? '' : '(<target>)'}`);
  24734. }
  24735. if (!shouldAttachTrigger(0 /* TriggerType.Regular */, lView, tNode))
  24736. return;
  24737. renderPlaceholder(lView, tNode);
  24738. // Avoid adding event listeners when this instruction is invoked on the server.
  24739. if (!(typeof ngServerMode !== 'undefined' && ngServerMode)) {
  24740. registerDomTrigger(lView, tNode, triggerIndex, walkUpTimes, onViewport, () => triggerDeferBlock(0 /* TriggerType.Regular */, lView, tNode), 0 /* TriggerType.Regular */);
  24741. }
  24742. }
  24743. /**
  24744. * Creates runtime data structures for the `prefetch on viewport` deferred trigger.
  24745. * @param triggerIndex Index at which to find the trigger element.
  24746. * @param walkUpTimes Number of times to walk up/down the tree hierarchy to find the trigger.
  24747. * @codeGenApi
  24748. */
  24749. function ɵɵdeferPrefetchOnViewport(triggerIndex, walkUpTimes) {
  24750. const lView = getLView();
  24751. const tNode = getCurrentTNode();
  24752. if (ngDevMode) {
  24753. trackTriggerForDebugging(lView[TVIEW], tNode, `prefetch on viewport${walkUpTimes === -1 ? '' : '(<target>)'}`);
  24754. }
  24755. if (!shouldAttachTrigger(1 /* TriggerType.Prefetch */, lView, tNode))
  24756. return;
  24757. const tView = lView[TVIEW];
  24758. const tDetails = getTDeferBlockDetails(tView, tNode);
  24759. if (tDetails.loadingState === DeferDependenciesLoadingState.NOT_STARTED) {
  24760. registerDomTrigger(lView, tNode, triggerIndex, walkUpTimes, onViewport, () => triggerPrefetching(tDetails, lView, tNode), 1 /* TriggerType.Prefetch */);
  24761. }
  24762. }
  24763. /**
  24764. * Creates runtime data structures for the `on viewport` hydrate trigger.
  24765. * @codeGenApi
  24766. */
  24767. function ɵɵdeferHydrateOnViewport() {
  24768. const lView = getLView();
  24769. const tNode = getCurrentTNode();
  24770. if (ngDevMode) {
  24771. trackTriggerForDebugging(lView[TVIEW], tNode, 'hydrate on viewport');
  24772. }
  24773. if (!shouldAttachTrigger(2 /* TriggerType.Hydrate */, lView, tNode))
  24774. return;
  24775. const hydrateTriggers = getHydrateTriggers(getTView(), tNode);
  24776. hydrateTriggers.set(2 /* DeferBlockTrigger.Viewport */, null);
  24777. if (typeof ngServerMode !== 'undefined' && ngServerMode) {
  24778. // We are on the server and SSR for defer blocks is enabled.
  24779. triggerDeferBlock(2 /* TriggerType.Hydrate */, lView, tNode);
  24780. }
  24781. // The actual triggering of hydration on viewport happens in triggering.ts,
  24782. // since these instructions won't exist for dehydrated content.
  24783. }
  24784. /**
  24785. * Updates the value of or removes a bound attribute on an Element.
  24786. *
  24787. * Used in the case of `[attr.title]="value"`
  24788. *
  24789. * @param name name The name of the attribute.
  24790. * @param value value The attribute is removed when value is `null` or `undefined`.
  24791. * Otherwise the attribute value is set to the stringified value.
  24792. * @param sanitizer An optional function used to sanitize the value.
  24793. * @param namespace Optional namespace to use when setting the attribute.
  24794. *
  24795. * @codeGenApi
  24796. */
  24797. function ɵɵattribute(name, value, sanitizer, namespace) {
  24798. const lView = getLView();
  24799. const bindingIndex = nextBindingIndex();
  24800. if (bindingUpdated(lView, bindingIndex, value)) {
  24801. const tView = getTView();
  24802. const tNode = getSelectedTNode();
  24803. elementAttributeInternal(tNode, lView, name, value, sanitizer, namespace);
  24804. ngDevMode && storePropertyBindingMetadata(tView.data, tNode, 'attr.' + name, bindingIndex);
  24805. }
  24806. return ɵɵattribute;
  24807. }
  24808. /**
  24809. * Create interpolation bindings with a variable number of expressions.
  24810. *
  24811. * If there are 1 to 8 expressions `interpolation1()` to `interpolation8()` should be used instead.
  24812. * Those are faster because there is no need to create an array of expressions and iterate over it.
  24813. *
  24814. * `values`:
  24815. * - has static text at even indexes,
  24816. * - has evaluated expressions at odd indexes.
  24817. *
  24818. * Returns the concatenated string when any of the arguments changes, `NO_CHANGE` otherwise.
  24819. */
  24820. function interpolationV(lView, values) {
  24821. ngDevMode && assertLessThan(2, values.length, 'should have at least 3 values');
  24822. ngDevMode && assertEqual(values.length % 2, 1, 'should have an odd number of values');
  24823. let isBindingUpdated = false;
  24824. let bindingIndex = getBindingIndex();
  24825. for (let i = 1; i < values.length; i += 2) {
  24826. // Check if bindings (odd indexes) have changed
  24827. isBindingUpdated = bindingUpdated(lView, bindingIndex++, values[i]) || isBindingUpdated;
  24828. }
  24829. setBindingIndex(bindingIndex);
  24830. if (!isBindingUpdated) {
  24831. return NO_CHANGE;
  24832. }
  24833. // Build the updated content
  24834. let content = values[0];
  24835. for (let i = 1; i < values.length; i += 2) {
  24836. content += renderStringify(values[i]) + values[i + 1];
  24837. }
  24838. return content;
  24839. }
  24840. /**
  24841. * Creates an interpolation binding with 1 expression.
  24842. *
  24843. * @param prefix static value used for concatenation only.
  24844. * @param v0 value checked for change.
  24845. * @param suffix static value used for concatenation only.
  24846. */
  24847. function interpolation1(lView, prefix, v0, suffix) {
  24848. const different = bindingUpdated(lView, nextBindingIndex(), v0);
  24849. return different ? prefix + renderStringify(v0) + suffix : NO_CHANGE;
  24850. }
  24851. /**
  24852. * Creates an interpolation binding with 2 expressions.
  24853. */
  24854. function interpolation2(lView, prefix, v0, i0, v1, suffix) {
  24855. const bindingIndex = getBindingIndex();
  24856. const different = bindingUpdated2(lView, bindingIndex, v0, v1);
  24857. incrementBindingIndex(2);
  24858. return different ? prefix + renderStringify(v0) + i0 + renderStringify(v1) + suffix : NO_CHANGE;
  24859. }
  24860. /**
  24861. * Creates an interpolation binding with 3 expressions.
  24862. */
  24863. function interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix) {
  24864. const bindingIndex = getBindingIndex();
  24865. const different = bindingUpdated3(lView, bindingIndex, v0, v1, v2);
  24866. incrementBindingIndex(3);
  24867. return different
  24868. ? prefix + renderStringify(v0) + i0 + renderStringify(v1) + i1 + renderStringify(v2) + suffix
  24869. : NO_CHANGE;
  24870. }
  24871. /**
  24872. * Create an interpolation binding with 4 expressions.
  24873. */
  24874. function interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix) {
  24875. const bindingIndex = getBindingIndex();
  24876. const different = bindingUpdated4(lView, bindingIndex, v0, v1, v2, v3);
  24877. incrementBindingIndex(4);
  24878. return different
  24879. ? prefix +
  24880. renderStringify(v0) +
  24881. i0 +
  24882. renderStringify(v1) +
  24883. i1 +
  24884. renderStringify(v2) +
  24885. i2 +
  24886. renderStringify(v3) +
  24887. suffix
  24888. : NO_CHANGE;
  24889. }
  24890. /**
  24891. * Creates an interpolation binding with 5 expressions.
  24892. */
  24893. function interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix) {
  24894. const bindingIndex = getBindingIndex();
  24895. let different = bindingUpdated4(lView, bindingIndex, v0, v1, v2, v3);
  24896. different = bindingUpdated(lView, bindingIndex + 4, v4) || different;
  24897. incrementBindingIndex(5);
  24898. return different
  24899. ? prefix +
  24900. renderStringify(v0) +
  24901. i0 +
  24902. renderStringify(v1) +
  24903. i1 +
  24904. renderStringify(v2) +
  24905. i2 +
  24906. renderStringify(v3) +
  24907. i3 +
  24908. renderStringify(v4) +
  24909. suffix
  24910. : NO_CHANGE;
  24911. }
  24912. /**
  24913. * Creates an interpolation binding with 6 expressions.
  24914. */
  24915. function interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix) {
  24916. const bindingIndex = getBindingIndex();
  24917. let different = bindingUpdated4(lView, bindingIndex, v0, v1, v2, v3);
  24918. different = bindingUpdated2(lView, bindingIndex + 4, v4, v5) || different;
  24919. incrementBindingIndex(6);
  24920. return different
  24921. ? prefix +
  24922. renderStringify(v0) +
  24923. i0 +
  24924. renderStringify(v1) +
  24925. i1 +
  24926. renderStringify(v2) +
  24927. i2 +
  24928. renderStringify(v3) +
  24929. i3 +
  24930. renderStringify(v4) +
  24931. i4 +
  24932. renderStringify(v5) +
  24933. suffix
  24934. : NO_CHANGE;
  24935. }
  24936. /**
  24937. * Creates an interpolation binding with 7 expressions.
  24938. */
  24939. function interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix) {
  24940. const bindingIndex = getBindingIndex();
  24941. let different = bindingUpdated4(lView, bindingIndex, v0, v1, v2, v3);
  24942. different = bindingUpdated3(lView, bindingIndex + 4, v4, v5, v6) || different;
  24943. incrementBindingIndex(7);
  24944. return different
  24945. ? prefix +
  24946. renderStringify(v0) +
  24947. i0 +
  24948. renderStringify(v1) +
  24949. i1 +
  24950. renderStringify(v2) +
  24951. i2 +
  24952. renderStringify(v3) +
  24953. i3 +
  24954. renderStringify(v4) +
  24955. i4 +
  24956. renderStringify(v5) +
  24957. i5 +
  24958. renderStringify(v6) +
  24959. suffix
  24960. : NO_CHANGE;
  24961. }
  24962. /**
  24963. * Creates an interpolation binding with 8 expressions.
  24964. */
  24965. function interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix) {
  24966. const bindingIndex = getBindingIndex();
  24967. let different = bindingUpdated4(lView, bindingIndex, v0, v1, v2, v3);
  24968. different = bindingUpdated4(lView, bindingIndex + 4, v4, v5, v6, v7) || different;
  24969. incrementBindingIndex(8);
  24970. return different
  24971. ? prefix +
  24972. renderStringify(v0) +
  24973. i0 +
  24974. renderStringify(v1) +
  24975. i1 +
  24976. renderStringify(v2) +
  24977. i2 +
  24978. renderStringify(v3) +
  24979. i3 +
  24980. renderStringify(v4) +
  24981. i4 +
  24982. renderStringify(v5) +
  24983. i5 +
  24984. renderStringify(v6) +
  24985. i6 +
  24986. renderStringify(v7) +
  24987. suffix
  24988. : NO_CHANGE;
  24989. }
  24990. /**
  24991. *
  24992. * Update an interpolated attribute on an element with single bound value surrounded by text.
  24993. *
  24994. * Used when the value passed to a property has 1 interpolated value in it:
  24995. *
  24996. * ```html
  24997. * <div attr.title="prefix{{v0}}suffix"></div>
  24998. * ```
  24999. *
  25000. * Its compiled representation is::
  25001. *
  25002. * ```ts
  25003. * ɵɵattributeInterpolate1('title', 'prefix', v0, 'suffix');
  25004. * ```
  25005. *
  25006. * @param attrName The name of the attribute to update
  25007. * @param prefix Static value used for concatenation only.
  25008. * @param v0 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 ɵɵattributeInterpolate1(attrName, prefix, v0, suffix, sanitizer, namespace) {
  25015. const lView = getLView();
  25016. const interpolatedValue = interpolation1(lView, prefix, v0, 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() - 1, prefix, suffix);
  25022. }
  25023. return ɵɵattributeInterpolate1;
  25024. }
  25025. /**
  25026. *
  25027. * Update an interpolated attribute on an element with 2 bound values surrounded by text.
  25028. *
  25029. * Used when the value passed to a property has 2 interpolated values in it:
  25030. *
  25031. * ```html
  25032. * <div attr.title="prefix{{v0}}-{{v1}}suffix"></div>
  25033. * ```
  25034. *
  25035. * Its compiled representation is::
  25036. *
  25037. * ```ts
  25038. * ɵɵattributeInterpolate2('title', 'prefix', v0, '-', v1, 'suffix');
  25039. * ```
  25040. *
  25041. * @param attrName The name of the attribute to update
  25042. * @param prefix Static value used for concatenation only.
  25043. * @param v0 Value checked for change.
  25044. * @param i0 Static value used for concatenation only.
  25045. * @param v1 Value checked for change.
  25046. * @param suffix Static value used for concatenation only.
  25047. * @param sanitizer An optional sanitizer function
  25048. * @returns itself, so that it may be chained.
  25049. * @codeGenApi
  25050. */
  25051. function ɵɵattributeInterpolate2(attrName, prefix, v0, i0, v1, suffix, sanitizer, namespace) {
  25052. const lView = getLView();
  25053. const interpolatedValue = interpolation2(lView, prefix, v0, i0, v1, suffix);
  25054. if (interpolatedValue !== NO_CHANGE) {
  25055. const tNode = getSelectedTNode();
  25056. elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
  25057. ngDevMode &&
  25058. storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 2, prefix, i0, suffix);
  25059. }
  25060. return ɵɵattributeInterpolate2;
  25061. }
  25062. /**
  25063. *
  25064. * Update an interpolated attribute on an element with 3 bound values surrounded by text.
  25065. *
  25066. * Used when the value passed to a property has 3 interpolated values in it:
  25067. *
  25068. * ```html
  25069. * <div attr.title="prefix{{v0}}-{{v1}}-{{v2}}suffix"></div>
  25070. * ```
  25071. *
  25072. * Its compiled representation is::
  25073. *
  25074. * ```ts
  25075. * ɵɵattributeInterpolate3(
  25076. * 'title', 'prefix', v0, '-', v1, '-', v2, 'suffix');
  25077. * ```
  25078. *
  25079. * @param attrName The name of the attribute to update
  25080. * @param prefix Static value used for concatenation only.
  25081. * @param v0 Value checked for change.
  25082. * @param i0 Static value used for concatenation only.
  25083. * @param v1 Value checked for change.
  25084. * @param i1 Static value used for concatenation only.
  25085. * @param v2 Value checked for change.
  25086. * @param suffix Static value used for concatenation only.
  25087. * @param sanitizer An optional sanitizer function
  25088. * @returns itself, so that it may be chained.
  25089. * @codeGenApi
  25090. */
  25091. function ɵɵattributeInterpolate3(attrName, prefix, v0, i0, v1, i1, v2, suffix, sanitizer, namespace) {
  25092. const lView = getLView();
  25093. const interpolatedValue = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix);
  25094. if (interpolatedValue !== NO_CHANGE) {
  25095. const tNode = getSelectedTNode();
  25096. elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
  25097. ngDevMode &&
  25098. storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 3, prefix, i0, i1, suffix);
  25099. }
  25100. return ɵɵattributeInterpolate3;
  25101. }
  25102. /**
  25103. *
  25104. * Update an interpolated attribute on an element with 4 bound values surrounded by text.
  25105. *
  25106. * Used when the value passed to a property has 4 interpolated values in it:
  25107. *
  25108. * ```html
  25109. * <div attr.title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}suffix"></div>
  25110. * ```
  25111. *
  25112. * Its compiled representation is::
  25113. *
  25114. * ```ts
  25115. * ɵɵattributeInterpolate4(
  25116. * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, 'suffix');
  25117. * ```
  25118. *
  25119. * @param attrName The name of the attribute to update
  25120. * @param prefix Static value used for concatenation only.
  25121. * @param v0 Value checked for change.
  25122. * @param i0 Static value used for concatenation only.
  25123. * @param v1 Value checked for change.
  25124. * @param i1 Static value used for concatenation only.
  25125. * @param v2 Value checked for change.
  25126. * @param i2 Static value used for concatenation only.
  25127. * @param v3 Value checked for change.
  25128. * @param suffix Static value used for concatenation only.
  25129. * @param sanitizer An optional sanitizer function
  25130. * @returns itself, so that it may be chained.
  25131. * @codeGenApi
  25132. */
  25133. function ɵɵattributeInterpolate4(attrName, prefix, v0, i0, v1, i1, v2, i2, v3, suffix, sanitizer, namespace) {
  25134. const lView = getLView();
  25135. const interpolatedValue = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix);
  25136. if (interpolatedValue !== NO_CHANGE) {
  25137. const tNode = getSelectedTNode();
  25138. elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
  25139. ngDevMode &&
  25140. storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 4, prefix, i0, i1, i2, suffix);
  25141. }
  25142. return ɵɵattributeInterpolate4;
  25143. }
  25144. /**
  25145. *
  25146. * Update an interpolated attribute on an element with 5 bound values surrounded by text.
  25147. *
  25148. * Used when the value passed to a property has 5 interpolated values in it:
  25149. *
  25150. * ```html
  25151. * <div attr.title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}suffix"></div>
  25152. * ```
  25153. *
  25154. * Its compiled representation is::
  25155. *
  25156. * ```ts
  25157. * ɵɵattributeInterpolate5(
  25158. * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, 'suffix');
  25159. * ```
  25160. *
  25161. * @param attrName The name of the attribute to update
  25162. * @param prefix Static value used for concatenation only.
  25163. * @param v0 Value checked for change.
  25164. * @param i0 Static value used for concatenation only.
  25165. * @param v1 Value checked for change.
  25166. * @param i1 Static value used for concatenation only.
  25167. * @param v2 Value checked for change.
  25168. * @param i2 Static value used for concatenation only.
  25169. * @param v3 Value checked for change.
  25170. * @param i3 Static value used for concatenation only.
  25171. * @param v4 Value checked for change.
  25172. * @param suffix Static value used for concatenation only.
  25173. * @param sanitizer An optional sanitizer function
  25174. * @returns itself, so that it may be chained.
  25175. * @codeGenApi
  25176. */
  25177. function ɵɵattributeInterpolate5(attrName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix, sanitizer, namespace) {
  25178. const lView = getLView();
  25179. const interpolatedValue = interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix);
  25180. if (interpolatedValue !== NO_CHANGE) {
  25181. const tNode = getSelectedTNode();
  25182. elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
  25183. ngDevMode &&
  25184. storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 5, prefix, i0, i1, i2, i3, suffix);
  25185. }
  25186. return ɵɵattributeInterpolate5;
  25187. }
  25188. /**
  25189. *
  25190. * Update an interpolated attribute on an element with 6 bound values surrounded by text.
  25191. *
  25192. * Used when the value passed to a property has 6 interpolated values in it:
  25193. *
  25194. * ```html
  25195. * <div attr.title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}suffix"></div>
  25196. * ```
  25197. *
  25198. * Its compiled representation is::
  25199. *
  25200. * ```ts
  25201. * ɵɵattributeInterpolate6(
  25202. * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, 'suffix');
  25203. * ```
  25204. *
  25205. * @param attrName The name of the attribute to update
  25206. * @param prefix Static value used for concatenation only.
  25207. * @param v0 Value checked for change.
  25208. * @param i0 Static value used for concatenation only.
  25209. * @param v1 Value checked for change.
  25210. * @param i1 Static value used for concatenation only.
  25211. * @param v2 Value checked for change.
  25212. * @param i2 Static value used for concatenation only.
  25213. * @param v3 Value checked for change.
  25214. * @param i3 Static value used for concatenation only.
  25215. * @param v4 Value checked for change.
  25216. * @param i4 Static value used for concatenation only.
  25217. * @param v5 Value checked for change.
  25218. * @param suffix Static value used for concatenation only.
  25219. * @param sanitizer An optional sanitizer function
  25220. * @returns itself, so that it may be chained.
  25221. * @codeGenApi
  25222. */
  25223. function ɵɵattributeInterpolate6(attrName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix, sanitizer, namespace) {
  25224. const lView = getLView();
  25225. const interpolatedValue = interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix);
  25226. if (interpolatedValue !== NO_CHANGE) {
  25227. const tNode = getSelectedTNode();
  25228. elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
  25229. ngDevMode &&
  25230. storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 6, prefix, i0, i1, i2, i3, i4, suffix);
  25231. }
  25232. return ɵɵattributeInterpolate6;
  25233. }
  25234. /**
  25235. *
  25236. * Update an interpolated attribute on an element with 7 bound values surrounded by text.
  25237. *
  25238. * Used when the value passed to a property has 7 interpolated values in it:
  25239. *
  25240. * ```html
  25241. * <div attr.title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}suffix"></div>
  25242. * ```
  25243. *
  25244. * Its compiled representation is::
  25245. *
  25246. * ```ts
  25247. * ɵɵattributeInterpolate7(
  25248. * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, 'suffix');
  25249. * ```
  25250. *
  25251. * @param attrName The name of the attribute to update
  25252. * @param prefix Static value used for concatenation only.
  25253. * @param v0 Value checked for change.
  25254. * @param i0 Static value used for concatenation only.
  25255. * @param v1 Value checked for change.
  25256. * @param i1 Static value used for concatenation only.
  25257. * @param v2 Value checked for change.
  25258. * @param i2 Static value used for concatenation only.
  25259. * @param v3 Value checked for change.
  25260. * @param i3 Static value used for concatenation only.
  25261. * @param v4 Value checked for change.
  25262. * @param i4 Static value used for concatenation only.
  25263. * @param v5 Value checked for change.
  25264. * @param i5 Static value used for concatenation only.
  25265. * @param v6 Value checked for change.
  25266. * @param suffix Static value used for concatenation only.
  25267. * @param sanitizer An optional sanitizer function
  25268. * @returns itself, so that it may be chained.
  25269. * @codeGenApi
  25270. */
  25271. function ɵɵattributeInterpolate7(attrName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix, sanitizer, namespace) {
  25272. const lView = getLView();
  25273. const interpolatedValue = interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix);
  25274. if (interpolatedValue !== NO_CHANGE) {
  25275. const tNode = getSelectedTNode();
  25276. elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
  25277. ngDevMode &&
  25278. storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 7, prefix, i0, i1, i2, i3, i4, i5, suffix);
  25279. }
  25280. return ɵɵattributeInterpolate7;
  25281. }
  25282. /**
  25283. *
  25284. * Update an interpolated attribute on an element with 8 bound values surrounded by text.
  25285. *
  25286. * Used when the value passed to a property has 8 interpolated values in it:
  25287. *
  25288. * ```html
  25289. * <div attr.title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}suffix"></div>
  25290. * ```
  25291. *
  25292. * Its compiled representation is::
  25293. *
  25294. * ```ts
  25295. * ɵɵattributeInterpolate8(
  25296. * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, 'suffix');
  25297. * ```
  25298. *
  25299. * @param attrName The name of the attribute to update
  25300. * @param prefix Static value used for concatenation only.
  25301. * @param v0 Value checked for change.
  25302. * @param i0 Static value used for concatenation only.
  25303. * @param v1 Value checked for change.
  25304. * @param i1 Static value used for concatenation only.
  25305. * @param v2 Value checked for change.
  25306. * @param i2 Static value used for concatenation only.
  25307. * @param v3 Value checked for change.
  25308. * @param i3 Static value used for concatenation only.
  25309. * @param v4 Value checked for change.
  25310. * @param i4 Static value used for concatenation only.
  25311. * @param v5 Value checked for change.
  25312. * @param i5 Static value used for concatenation only.
  25313. * @param v6 Value checked for change.
  25314. * @param i6 Static value used for concatenation only.
  25315. * @param v7 Value checked for change.
  25316. * @param suffix Static value used for concatenation only.
  25317. * @param sanitizer An optional sanitizer function
  25318. * @returns itself, so that it may be chained.
  25319. * @codeGenApi
  25320. */
  25321. function ɵɵattributeInterpolate8(attrName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix, sanitizer, namespace) {
  25322. const lView = getLView();
  25323. const interpolatedValue = interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix);
  25324. if (interpolatedValue !== NO_CHANGE) {
  25325. const tNode = getSelectedTNode();
  25326. elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
  25327. ngDevMode &&
  25328. storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 8, prefix, i0, i1, i2, i3, i4, i5, i6, suffix);
  25329. }
  25330. return ɵɵattributeInterpolate8;
  25331. }
  25332. /**
  25333. * Update an interpolated attribute on an element with 9 or more bound values surrounded by text.
  25334. *
  25335. * Used when the number of interpolated values exceeds 8.
  25336. *
  25337. * ```html
  25338. * <div
  25339. * title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}-{{v8}}-{{v9}}suffix"></div>
  25340. * ```
  25341. *
  25342. * Its compiled representation is::
  25343. *
  25344. * ```ts
  25345. * ɵɵattributeInterpolateV(
  25346. * 'title', ['prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, '-', v9,
  25347. * 'suffix']);
  25348. * ```
  25349. *
  25350. * @param attrName The name of the attribute to update.
  25351. * @param values The collection of values and the strings in-between those values, beginning with
  25352. * a string prefix and ending with a string suffix.
  25353. * (e.g. `['prefix', value0, '-', value1, '-', value2, ..., value99, 'suffix']`)
  25354. * @param sanitizer An optional sanitizer function
  25355. * @returns itself, so that it may be chained.
  25356. * @codeGenApi
  25357. */
  25358. function ɵɵattributeInterpolateV(attrName, values, sanitizer, namespace) {
  25359. const lView = getLView();
  25360. const interpolated = interpolationV(lView, values);
  25361. if (interpolated !== NO_CHANGE) {
  25362. const tNode = getSelectedTNode();
  25363. elementAttributeInternal(tNode, lView, attrName, interpolated, sanitizer, namespace);
  25364. if (ngDevMode) {
  25365. const interpolationInBetween = [values[0]]; // prefix
  25366. for (let i = 2; i < values.length; i += 2) {
  25367. interpolationInBetween.push(values[i]);
  25368. }
  25369. storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - interpolationInBetween.length + 1, ...interpolationInBetween);
  25370. }
  25371. }
  25372. return ɵɵattributeInterpolateV;
  25373. }
  25374. function toTStylingRange(prev, next) {
  25375. ngDevMode && assertNumberInRange(prev, 0, 32767 /* StylingRange.UNSIGNED_MASK */);
  25376. ngDevMode && assertNumberInRange(next, 0, 32767 /* StylingRange.UNSIGNED_MASK */);
  25377. return ((prev << 17 /* StylingRange.PREV_SHIFT */) | (next << 2 /* StylingRange.NEXT_SHIFT */));
  25378. }
  25379. function getTStylingRangePrev(tStylingRange) {
  25380. ngDevMode && assertNumber(tStylingRange, 'expected number');
  25381. return (tStylingRange >> 17 /* StylingRange.PREV_SHIFT */) & 32767 /* StylingRange.UNSIGNED_MASK */;
  25382. }
  25383. function getTStylingRangePrevDuplicate(tStylingRange) {
  25384. ngDevMode && assertNumber(tStylingRange, 'expected number');
  25385. return (tStylingRange & 2 /* StylingRange.PREV_DUPLICATE */) == 2 /* StylingRange.PREV_DUPLICATE */;
  25386. }
  25387. function setTStylingRangePrev(tStylingRange, previous) {
  25388. ngDevMode && assertNumber(tStylingRange, 'expected number');
  25389. ngDevMode && assertNumberInRange(previous, 0, 32767 /* StylingRange.UNSIGNED_MASK */);
  25390. return ((tStylingRange & 131071 /* StylingRange.PREV_MASK */) |
  25391. (previous << 17 /* StylingRange.PREV_SHIFT */));
  25392. }
  25393. function setTStylingRangePrevDuplicate(tStylingRange) {
  25394. ngDevMode && assertNumber(tStylingRange, 'expected number');
  25395. return (tStylingRange | 2 /* StylingRange.PREV_DUPLICATE */);
  25396. }
  25397. function getTStylingRangeNext(tStylingRange) {
  25398. ngDevMode && assertNumber(tStylingRange, 'expected number');
  25399. return (tStylingRange & 131068 /* StylingRange.NEXT_MASK */) >> 2 /* StylingRange.NEXT_SHIFT */;
  25400. }
  25401. function setTStylingRangeNext(tStylingRange, next) {
  25402. ngDevMode && assertNumber(tStylingRange, 'expected number');
  25403. ngDevMode && assertNumberInRange(next, 0, 32767 /* StylingRange.UNSIGNED_MASK */);
  25404. return ((tStylingRange & -131069 /* StylingRange.NEXT_MASK */) | //
  25405. (next << 2 /* StylingRange.NEXT_SHIFT */));
  25406. }
  25407. function getTStylingRangeNextDuplicate(tStylingRange) {
  25408. ngDevMode && assertNumber(tStylingRange, 'expected number');
  25409. return (tStylingRange & 1 /* StylingRange.NEXT_DUPLICATE */) === 1 /* StylingRange.NEXT_DUPLICATE */;
  25410. }
  25411. function setTStylingRangeNextDuplicate(tStylingRange) {
  25412. ngDevMode && assertNumber(tStylingRange, 'expected number');
  25413. return (tStylingRange | 1 /* StylingRange.NEXT_DUPLICATE */);
  25414. }
  25415. /**
  25416. * Insert new `tStyleValue` at `TData` and link existing style bindings such that we maintain linked
  25417. * list of styles and compute the duplicate flag.
  25418. *
  25419. * Note: this function is executed during `firstUpdatePass` only to populate the `TView.data`.
  25420. *
  25421. * The function works by keeping track of `tStylingRange` which contains two pointers pointing to
  25422. * the head/tail of the template portion of the styles.
  25423. * - if `isHost === false` (we are template) then insertion is at tail of `TStylingRange`
  25424. * - if `isHost === true` (we are host binding) then insertion is at head of `TStylingRange`
  25425. *
  25426. * @param tData The `TData` to insert into.
  25427. * @param tNode `TNode` associated with the styling element.
  25428. * @param tStylingKey See `TStylingKey`.
  25429. * @param index location of where `tStyleValue` should be stored (and linked into list.)
  25430. * @param isHostBinding `true` if the insertion is for a `hostBinding`. (insertion is in front of
  25431. * template.)
  25432. * @param isClassBinding True if the associated `tStylingKey` as a `class` styling.
  25433. * `tNode.classBindings` should be used (or `tNode.styleBindings` otherwise.)
  25434. */
  25435. function insertTStylingBinding(tData, tNode, tStylingKeyWithStatic, index, isHostBinding, isClassBinding) {
  25436. ngDevMode && assertFirstUpdatePass(getTView());
  25437. let tBindings = isClassBinding ? tNode.classBindings : tNode.styleBindings;
  25438. let tmplHead = getTStylingRangePrev(tBindings);
  25439. let tmplTail = getTStylingRangeNext(tBindings);
  25440. tData[index] = tStylingKeyWithStatic;
  25441. let isKeyDuplicateOfStatic = false;
  25442. let tStylingKey;
  25443. if (Array.isArray(tStylingKeyWithStatic)) {
  25444. // We are case when the `TStylingKey` contains static fields as well.
  25445. const staticKeyValueArray = tStylingKeyWithStatic;
  25446. tStylingKey = staticKeyValueArray[1]; // unwrap.
  25447. // We need to check if our key is present in the static so that we can mark it as duplicate.
  25448. if (tStylingKey === null ||
  25449. keyValueArrayIndexOf(staticKeyValueArray, tStylingKey) > 0) {
  25450. // tStylingKey is present in the statics, need to mark it as duplicate.
  25451. isKeyDuplicateOfStatic = true;
  25452. }
  25453. }
  25454. else {
  25455. tStylingKey = tStylingKeyWithStatic;
  25456. }
  25457. if (isHostBinding) {
  25458. // We are inserting host bindings
  25459. // If we don't have template bindings then `tail` is 0.
  25460. const hasTemplateBindings = tmplTail !== 0;
  25461. // This is important to know because that means that the `head` can't point to the first
  25462. // template bindings (there are none.) Instead the head points to the tail of the template.
  25463. if (hasTemplateBindings) {
  25464. // template head's "prev" will point to last host binding or to 0 if no host bindings yet
  25465. const previousNode = getTStylingRangePrev(tData[tmplHead + 1]);
  25466. tData[index + 1] = toTStylingRange(previousNode, tmplHead);
  25467. // if a host binding has already been registered, we need to update the next of that host
  25468. // binding to point to this one
  25469. if (previousNode !== 0) {
  25470. // We need to update the template-tail value to point to us.
  25471. tData[previousNode + 1] = setTStylingRangeNext(tData[previousNode + 1], index);
  25472. }
  25473. // The "previous" of the template binding head should point to this host binding
  25474. tData[tmplHead + 1] = setTStylingRangePrev(tData[tmplHead + 1], index);
  25475. }
  25476. else {
  25477. tData[index + 1] = toTStylingRange(tmplHead, 0);
  25478. // if a host binding has already been registered, we need to update the next of that host
  25479. // binding to point to this one
  25480. if (tmplHead !== 0) {
  25481. // We need to update the template-tail value to point to us.
  25482. tData[tmplHead + 1] = setTStylingRangeNext(tData[tmplHead + 1], index);
  25483. }
  25484. // if we don't have template, the head points to template-tail, and needs to be advanced.
  25485. tmplHead = index;
  25486. }
  25487. }
  25488. else {
  25489. // We are inserting in template section.
  25490. // We need to set this binding's "previous" to the current template tail
  25491. tData[index + 1] = toTStylingRange(tmplTail, 0);
  25492. ngDevMode &&
  25493. assertEqual(tmplHead !== 0 && tmplTail === 0, false, 'Adding template bindings after hostBindings is not allowed.');
  25494. if (tmplHead === 0) {
  25495. tmplHead = index;
  25496. }
  25497. else {
  25498. // We need to update the previous value "next" to point to this binding
  25499. tData[tmplTail + 1] = setTStylingRangeNext(tData[tmplTail + 1], index);
  25500. }
  25501. tmplTail = index;
  25502. }
  25503. // Now we need to update / compute the duplicates.
  25504. // Starting with our location search towards head (least priority)
  25505. if (isKeyDuplicateOfStatic) {
  25506. tData[index + 1] = setTStylingRangePrevDuplicate(tData[index + 1]);
  25507. }
  25508. markDuplicates(tData, tStylingKey, index, true);
  25509. markDuplicates(tData, tStylingKey, index, false);
  25510. markDuplicateOfResidualStyling(tNode, tStylingKey, tData, index, isClassBinding);
  25511. tBindings = toTStylingRange(tmplHead, tmplTail);
  25512. if (isClassBinding) {
  25513. tNode.classBindings = tBindings;
  25514. }
  25515. else {
  25516. tNode.styleBindings = tBindings;
  25517. }
  25518. }
  25519. /**
  25520. * Look into the residual styling to see if the current `tStylingKey` is duplicate of residual.
  25521. *
  25522. * @param tNode `TNode` where the residual is stored.
  25523. * @param tStylingKey `TStylingKey` to store.
  25524. * @param tData `TData` associated with the current `LView`.
  25525. * @param index location of where `tStyleValue` should be stored (and linked into list.)
  25526. * @param isClassBinding True if the associated `tStylingKey` as a `class` styling.
  25527. * `tNode.classBindings` should be used (or `tNode.styleBindings` otherwise.)
  25528. */
  25529. function markDuplicateOfResidualStyling(tNode, tStylingKey, tData, index, isClassBinding) {
  25530. const residual = isClassBinding ? tNode.residualClasses : tNode.residualStyles;
  25531. if (residual != null /* or undefined */ &&
  25532. typeof tStylingKey == 'string' &&
  25533. keyValueArrayIndexOf(residual, tStylingKey) >= 0) {
  25534. // We have duplicate in the residual so mark ourselves as duplicate.
  25535. tData[index + 1] = setTStylingRangeNextDuplicate(tData[index + 1]);
  25536. }
  25537. }
  25538. /**
  25539. * Marks `TStyleValue`s as duplicates if another style binding in the list has the same
  25540. * `TStyleValue`.
  25541. *
  25542. * NOTE: this function is intended to be called twice once with `isPrevDir` set to `true` and once
  25543. * with it set to `false` to search both the previous as well as next items in the list.
  25544. *
  25545. * No duplicate case
  25546. * ```
  25547. * [style.color]
  25548. * [style.width.px] <<- index
  25549. * [style.height.px]
  25550. * ```
  25551. *
  25552. * In the above case adding `[style.width.px]` to the existing `[style.color]` produces no
  25553. * duplicates because `width` is not found in any other part of the linked list.
  25554. *
  25555. * Duplicate case
  25556. * ```
  25557. * [style.color]
  25558. * [style.width.em]
  25559. * [style.width.px] <<- index
  25560. * ```
  25561. * In the above case adding `[style.width.px]` will produce a duplicate with `[style.width.em]`
  25562. * because `width` is found in the chain.
  25563. *
  25564. * Map case 1
  25565. * ```
  25566. * [style.width.px]
  25567. * [style.color]
  25568. * [style] <<- index
  25569. * ```
  25570. * In the above case adding `[style]` will produce a duplicate with any other bindings because
  25571. * `[style]` is a Map and as such is fully dynamic and could produce `color` or `width`.
  25572. *
  25573. * Map case 2
  25574. * ```
  25575. * [style]
  25576. * [style.width.px]
  25577. * [style.color] <<- index
  25578. * ```
  25579. * In the above case adding `[style.color]` will produce a duplicate because there is already a
  25580. * `[style]` binding which is a Map and as such is fully dynamic and could produce `color` or
  25581. * `width`.
  25582. *
  25583. * NOTE: Once `[style]` (Map) is added into the system all things are mapped as duplicates.
  25584. * NOTE: We use `style` as example, but same logic is applied to `class`es as well.
  25585. *
  25586. * @param tData `TData` where the linked list is stored.
  25587. * @param tStylingKey `TStylingKeyPrimitive` which contains the value to compare to other keys in
  25588. * the linked list.
  25589. * @param index Starting location in the linked list to search from
  25590. * @param isPrevDir Direction.
  25591. * - `true` for previous (lower priority);
  25592. * - `false` for next (higher priority).
  25593. */
  25594. function markDuplicates(tData, tStylingKey, index, isPrevDir) {
  25595. const tStylingAtIndex = tData[index + 1];
  25596. const isMap = tStylingKey === null;
  25597. let cursor = isPrevDir
  25598. ? getTStylingRangePrev(tStylingAtIndex)
  25599. : getTStylingRangeNext(tStylingAtIndex);
  25600. let foundDuplicate = false;
  25601. // We keep iterating as long as we have a cursor
  25602. // AND either:
  25603. // - we found what we are looking for, OR
  25604. // - we are a map in which case we have to continue searching even after we find what we were
  25605. // looking for since we are a wild card and everything needs to be flipped to duplicate.
  25606. while (cursor !== 0 && (foundDuplicate === false || isMap)) {
  25607. ngDevMode && assertIndexInRange(tData, cursor);
  25608. const tStylingValueAtCursor = tData[cursor];
  25609. const tStyleRangeAtCursor = tData[cursor + 1];
  25610. if (isStylingMatch(tStylingValueAtCursor, tStylingKey)) {
  25611. foundDuplicate = true;
  25612. tData[cursor + 1] = isPrevDir
  25613. ? setTStylingRangeNextDuplicate(tStyleRangeAtCursor)
  25614. : setTStylingRangePrevDuplicate(tStyleRangeAtCursor);
  25615. }
  25616. cursor = isPrevDir
  25617. ? getTStylingRangePrev(tStyleRangeAtCursor)
  25618. : getTStylingRangeNext(tStyleRangeAtCursor);
  25619. }
  25620. if (foundDuplicate) {
  25621. // if we found a duplicate, than mark ourselves.
  25622. tData[index + 1] = isPrevDir
  25623. ? setTStylingRangePrevDuplicate(tStylingAtIndex)
  25624. : setTStylingRangeNextDuplicate(tStylingAtIndex);
  25625. }
  25626. }
  25627. /**
  25628. * Determines if two `TStylingKey`s are a match.
  25629. *
  25630. * When computing whether a binding contains a duplicate, we need to compare if the instruction
  25631. * `TStylingKey` has a match.
  25632. *
  25633. * Here are examples of `TStylingKey`s which match given `tStylingKeyCursor` is:
  25634. * - `color`
  25635. * - `color` // Match another color
  25636. * - `null` // That means that `tStylingKey` is a `classMap`/`styleMap` instruction
  25637. * - `['', 'color', 'other', true]` // wrapped `color` so match
  25638. * - `['', null, 'other', true]` // wrapped `null` so match
  25639. * - `['', 'width', 'color', 'value']` // wrapped static value contains a match on `'color'`
  25640. * - `null` // `tStylingKeyCursor` always match as it is `classMap`/`styleMap` instruction
  25641. *
  25642. * @param tStylingKeyCursor
  25643. * @param tStylingKey
  25644. */
  25645. function isStylingMatch(tStylingKeyCursor, tStylingKey) {
  25646. ngDevMode &&
  25647. assertNotEqual(Array.isArray(tStylingKey), true, "Expected that 'tStylingKey' has been unwrapped");
  25648. if (tStylingKeyCursor === null || // If the cursor is `null` it means that we have map at that
  25649. // location so we must assume that we have a match.
  25650. tStylingKey == null || // If `tStylingKey` is `null` then it is a map therefor assume that it
  25651. // contains a match.
  25652. (Array.isArray(tStylingKeyCursor) ? tStylingKeyCursor[1] : tStylingKeyCursor) === tStylingKey // If the keys match explicitly than we are a match.
  25653. ) {
  25654. return true;
  25655. }
  25656. else if (Array.isArray(tStylingKeyCursor) && typeof tStylingKey === 'string') {
  25657. // if we did not find a match, but `tStylingKeyCursor` is `KeyValueArray` that means cursor has
  25658. // statics and we need to check those as well.
  25659. return keyValueArrayIndexOf(tStylingKeyCursor, tStylingKey) >= 0; // see if we are matching the key
  25660. }
  25661. return false;
  25662. }
  25663. // Global state of the parser. (This makes parser non-reentrant, but that is not an issue)
  25664. const parserState = {
  25665. textEnd: 0,
  25666. key: 0,
  25667. keyEnd: 0,
  25668. value: 0,
  25669. valueEnd: 0,
  25670. };
  25671. /**
  25672. * Retrieves the last parsed `key` of style.
  25673. * @param text the text to substring the key from.
  25674. */
  25675. function getLastParsedKey(text) {
  25676. return text.substring(parserState.key, parserState.keyEnd);
  25677. }
  25678. /**
  25679. * Retrieves the last parsed `value` of style.
  25680. * @param text the text to substring the key from.
  25681. */
  25682. function getLastParsedValue(text) {
  25683. return text.substring(parserState.value, parserState.valueEnd);
  25684. }
  25685. /**
  25686. * Initializes `className` string for parsing and parses the first token.
  25687. *
  25688. * This function is intended to be used in this format:
  25689. * ```ts
  25690. * for (let i = parseClassName(text); i >= 0; i = parseClassNameNext(text, i)) {
  25691. * const key = getLastParsedKey();
  25692. * ...
  25693. * }
  25694. * ```
  25695. * @param text `className` to parse
  25696. * @returns index where the next invocation of `parseClassNameNext` should resume.
  25697. */
  25698. function parseClassName(text) {
  25699. resetParserState(text);
  25700. return parseClassNameNext(text, consumeWhitespace(text, 0, parserState.textEnd));
  25701. }
  25702. /**
  25703. * Parses next `className` token.
  25704. *
  25705. * This function is intended to be used in this format:
  25706. * ```ts
  25707. * for (let i = parseClassName(text); i >= 0; i = parseClassNameNext(text, i)) {
  25708. * const key = getLastParsedKey();
  25709. * ...
  25710. * }
  25711. * ```
  25712. *
  25713. * @param text `className` to parse
  25714. * @param index where the parsing should resume.
  25715. * @returns index where the next invocation of `parseClassNameNext` should resume.
  25716. */
  25717. function parseClassNameNext(text, index) {
  25718. const end = parserState.textEnd;
  25719. if (end === index) {
  25720. return -1;
  25721. }
  25722. index = parserState.keyEnd = consumeClassToken(text, (parserState.key = index), end);
  25723. return consumeWhitespace(text, index, end);
  25724. }
  25725. /**
  25726. * Initializes `cssText` string for parsing and parses the first key/values.
  25727. *
  25728. * This function is intended to be used in this format:
  25729. * ```ts
  25730. * for (let i = parseStyle(text); i >= 0; i = parseStyleNext(text, i))) {
  25731. * const key = getLastParsedKey();
  25732. * const value = getLastParsedValue();
  25733. * ...
  25734. * }
  25735. * ```
  25736. * @param text `cssText` to parse
  25737. * @returns index where the next invocation of `parseStyleNext` should resume.
  25738. */
  25739. function parseStyle(text) {
  25740. resetParserState(text);
  25741. return parseStyleNext(text, consumeWhitespace(text, 0, parserState.textEnd));
  25742. }
  25743. /**
  25744. * Parses the next `cssText` key/values.
  25745. *
  25746. * This function is intended to be used in this format:
  25747. * ```ts
  25748. * for (let i = parseStyle(text); i >= 0; i = parseStyleNext(text, i))) {
  25749. * const key = getLastParsedKey();
  25750. * const value = getLastParsedValue();
  25751. * ...
  25752. * }
  25753. *
  25754. * @param text `cssText` to parse
  25755. * @param index where the parsing should resume.
  25756. * @returns index where the next invocation of `parseStyleNext` should resume.
  25757. */
  25758. function parseStyleNext(text, startIndex) {
  25759. const end = parserState.textEnd;
  25760. let index = (parserState.key = consumeWhitespace(text, startIndex, end));
  25761. if (end === index) {
  25762. // we reached an end so just quit
  25763. return -1;
  25764. }
  25765. index = parserState.keyEnd = consumeStyleKey(text, index, end);
  25766. index = consumeSeparator(text, index, end, 58 /* CharCode.COLON */);
  25767. index = parserState.value = consumeWhitespace(text, index, end);
  25768. index = parserState.valueEnd = consumeStyleValue(text, index, end);
  25769. return consumeSeparator(text, index, end, 59 /* CharCode.SEMI_COLON */);
  25770. }
  25771. /**
  25772. * Reset the global state of the styling parser.
  25773. * @param text The styling text to parse.
  25774. */
  25775. function resetParserState(text) {
  25776. parserState.key = 0;
  25777. parserState.keyEnd = 0;
  25778. parserState.value = 0;
  25779. parserState.valueEnd = 0;
  25780. parserState.textEnd = text.length;
  25781. }
  25782. /**
  25783. * Returns index of next non-whitespace character.
  25784. *
  25785. * @param text Text to scan
  25786. * @param startIndex Starting index of character where the scan should start.
  25787. * @param endIndex Ending index of character where the scan should end.
  25788. * @returns Index of next non-whitespace character (May be the same as `start` if no whitespace at
  25789. * that location.)
  25790. */
  25791. function consumeWhitespace(text, startIndex, endIndex) {
  25792. while (startIndex < endIndex && text.charCodeAt(startIndex) <= 32 /* CharCode.SPACE */) {
  25793. startIndex++;
  25794. }
  25795. return startIndex;
  25796. }
  25797. /**
  25798. * Returns index of last char in class token.
  25799. *
  25800. * @param text Text to scan
  25801. * @param startIndex Starting index of character where the scan should start.
  25802. * @param endIndex Ending index of character where the scan should end.
  25803. * @returns Index after last char in class token.
  25804. */
  25805. function consumeClassToken(text, startIndex, endIndex) {
  25806. while (startIndex < endIndex && text.charCodeAt(startIndex) > 32 /* CharCode.SPACE */) {
  25807. startIndex++;
  25808. }
  25809. return startIndex;
  25810. }
  25811. /**
  25812. * Consumes all of the characters belonging to style key and token.
  25813. *
  25814. * @param text Text to scan
  25815. * @param startIndex Starting index of character where the scan should start.
  25816. * @param endIndex Ending index of character where the scan should end.
  25817. * @returns Index after last style key character.
  25818. */
  25819. function consumeStyleKey(text, startIndex, endIndex) {
  25820. let ch;
  25821. while (startIndex < endIndex &&
  25822. ((ch = text.charCodeAt(startIndex)) === 45 /* CharCode.DASH */ ||
  25823. ch === 95 /* CharCode.UNDERSCORE */ ||
  25824. ((ch & -33 /* CharCode.UPPER_CASE */) >= 65 /* CharCode.A */ && (ch & -33 /* CharCode.UPPER_CASE */) <= 90 /* CharCode.Z */) ||
  25825. (ch >= 48 /* CharCode.ZERO */ && ch <= 57 /* CharCode.NINE */))) {
  25826. startIndex++;
  25827. }
  25828. return startIndex;
  25829. }
  25830. /**
  25831. * Consumes all whitespace and the separator `:` after the style key.
  25832. *
  25833. * @param text Text to scan
  25834. * @param startIndex Starting index of character where the scan should start.
  25835. * @param endIndex Ending index of character where the scan should end.
  25836. * @returns Index after separator and surrounding whitespace.
  25837. */
  25838. function consumeSeparator(text, startIndex, endIndex, separator) {
  25839. startIndex = consumeWhitespace(text, startIndex, endIndex);
  25840. if (startIndex < endIndex) {
  25841. if (ngDevMode && text.charCodeAt(startIndex) !== separator) {
  25842. malformedStyleError(text, String.fromCharCode(separator), startIndex);
  25843. }
  25844. startIndex++;
  25845. }
  25846. return startIndex;
  25847. }
  25848. /**
  25849. * Consumes style value honoring `url()` and `""` text.
  25850. *
  25851. * @param text Text to scan
  25852. * @param startIndex Starting index of character where the scan should start.
  25853. * @param endIndex Ending index of character where the scan should end.
  25854. * @returns Index after last style value character.
  25855. */
  25856. function consumeStyleValue(text, startIndex, endIndex) {
  25857. let ch1 = -1; // 1st previous character
  25858. let ch2 = -1; // 2nd previous character
  25859. let ch3 = -1; // 3rd previous character
  25860. let i = startIndex;
  25861. let lastChIndex = i;
  25862. while (i < endIndex) {
  25863. const ch = text.charCodeAt(i++);
  25864. if (ch === 59 /* CharCode.SEMI_COLON */) {
  25865. return lastChIndex;
  25866. }
  25867. else if (ch === 34 /* CharCode.DOUBLE_QUOTE */ || ch === 39 /* CharCode.SINGLE_QUOTE */) {
  25868. lastChIndex = i = consumeQuotedText(text, ch, i, endIndex);
  25869. }
  25870. else if (startIndex === i - 4 && // We have seen only 4 characters so far "URL(" (Ignore "foo_URL()")
  25871. ch3 === 85 /* CharCode.U */ &&
  25872. ch2 === 82 /* CharCode.R */ &&
  25873. ch1 === 76 /* CharCode.L */ &&
  25874. ch === 40 /* CharCode.OPEN_PAREN */) {
  25875. lastChIndex = i = consumeQuotedText(text, 41 /* CharCode.CLOSE_PAREN */, i, endIndex);
  25876. }
  25877. else if (ch > 32 /* CharCode.SPACE */) {
  25878. // if we have a non-whitespace character then capture its location
  25879. lastChIndex = i;
  25880. }
  25881. ch3 = ch2;
  25882. ch2 = ch1;
  25883. ch1 = ch & -33 /* CharCode.UPPER_CASE */;
  25884. }
  25885. return lastChIndex;
  25886. }
  25887. /**
  25888. * Consumes all of the quoted characters.
  25889. *
  25890. * @param text Text to scan
  25891. * @param quoteCharCode CharCode of either `"` or `'` quote or `)` for `url(...)`.
  25892. * @param startIndex Starting index of character where the scan should start.
  25893. * @param endIndex Ending index of character where the scan should end.
  25894. * @returns Index after quoted characters.
  25895. */
  25896. function consumeQuotedText(text, quoteCharCode, startIndex, endIndex) {
  25897. let ch1 = -1; // 1st previous character
  25898. let index = startIndex;
  25899. while (index < endIndex) {
  25900. const ch = text.charCodeAt(index++);
  25901. if (ch == quoteCharCode && ch1 !== 92 /* CharCode.BACK_SLASH */) {
  25902. return index;
  25903. }
  25904. if (ch == 92 /* CharCode.BACK_SLASH */ && ch1 === 92 /* CharCode.BACK_SLASH */) {
  25905. // two back slashes cancel each other out. For example `"\\"` should properly end the
  25906. // quotation. (It should not assume that the last `"` is escaped.)
  25907. ch1 = 0;
  25908. }
  25909. else {
  25910. ch1 = ch;
  25911. }
  25912. }
  25913. throw ngDevMode
  25914. ? malformedStyleError(text, String.fromCharCode(quoteCharCode), endIndex)
  25915. : new Error();
  25916. }
  25917. function malformedStyleError(text, expecting, index) {
  25918. ngDevMode && assertEqual(typeof text === 'string', true, 'String expected here');
  25919. throw throwError(`Malformed style at location ${index} in string '` +
  25920. text.substring(0, index) +
  25921. '[>>' +
  25922. text.substring(index, index + 1) +
  25923. '<<]' +
  25924. text.slice(index + 1) +
  25925. `'. Expecting '${expecting}'.`);
  25926. }
  25927. /**
  25928. * Update a property on a selected element.
  25929. *
  25930. * Operates on the element selected by index via the {@link select} instruction.
  25931. *
  25932. * If the property name also exists as an input property on one of the element's directives,
  25933. * the component property will be set instead of the element property. This check must
  25934. * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled
  25935. *
  25936. * @param propName Name of property. Because it is going to DOM, this is not subject to
  25937. * renaming as part of minification.
  25938. * @param value New value to write.
  25939. * @param sanitizer An optional function used to sanitize the value.
  25940. * @returns This function returns itself so that it may be chained
  25941. * (e.g. `property('name', ctx.name)('title', ctx.title)`)
  25942. *
  25943. * @codeGenApi
  25944. */
  25945. function ɵɵproperty(propName, value, sanitizer) {
  25946. const lView = getLView();
  25947. const bindingIndex = nextBindingIndex();
  25948. if (bindingUpdated(lView, bindingIndex, value)) {
  25949. const tView = getTView();
  25950. const tNode = getSelectedTNode();
  25951. elementPropertyInternal(tView, tNode, lView, propName, value, lView[RENDERER], sanitizer, false);
  25952. ngDevMode && storePropertyBindingMetadata(tView.data, tNode, propName, bindingIndex);
  25953. }
  25954. return ɵɵproperty;
  25955. }
  25956. /**
  25957. * Given `<div style="..." my-dir>` and `MyDir` with `@Input('style')` we need to write to
  25958. * directive input.
  25959. */
  25960. function setDirectiveInputsWhichShadowsStyling(tView, tNode, lView, value, isClassBased) {
  25961. // We support both 'class' and `className` hence the fallback.
  25962. setAllInputsForProperty(tNode, tView, lView, isClassBased ? 'class' : 'style', value);
  25963. }
  25964. /**
  25965. * Update a style binding on an element with the provided value.
  25966. *
  25967. * If the style value is falsy then it will be removed from the element
  25968. * (or assigned a different value depending if there are any styles placed
  25969. * on the element with `styleMap` or any static styles that are
  25970. * present from when the element was created with `styling`).
  25971. *
  25972. * Note that the styling element is updated as part of `stylingApply`.
  25973. *
  25974. * @param prop A valid CSS property.
  25975. * @param value New value to write (`null` or an empty string to remove).
  25976. * @param suffix Optional suffix. Used with scalar values to add unit such as `px`.
  25977. *
  25978. * Note that this will apply the provided style value to the host element if this function is called
  25979. * within a host binding function.
  25980. *
  25981. * @codeGenApi
  25982. */
  25983. function ɵɵstyleProp(prop, value, suffix) {
  25984. checkStylingProperty(prop, value, suffix, false);
  25985. return ɵɵstyleProp;
  25986. }
  25987. /**
  25988. * Update a class binding on an element with the provided value.
  25989. *
  25990. * This instruction is meant to handle the `[class.foo]="exp"` case and,
  25991. * therefore, the class binding itself must already be allocated using
  25992. * `styling` within the creation block.
  25993. *
  25994. * @param prop A valid CSS class (only one).
  25995. * @param value A true/false value which will turn the class on or off.
  25996. *
  25997. * Note that this will apply the provided class value to the host element if this function
  25998. * is called within a host binding function.
  25999. *
  26000. * @codeGenApi
  26001. */
  26002. function ɵɵclassProp(className, value) {
  26003. checkStylingProperty(className, value, null, true);
  26004. return ɵɵclassProp;
  26005. }
  26006. /**
  26007. * Update style bindings using an object literal on an element.
  26008. *
  26009. * This instruction is meant to apply styling via the `[style]="exp"` template bindings.
  26010. * When styles are applied to the element they will then be updated with respect to
  26011. * any styles/classes set via `styleProp`. If any styles are set to falsy
  26012. * then they will be removed from the element.
  26013. *
  26014. * Note that the styling instruction will not be applied until `stylingApply` is called.
  26015. *
  26016. * @param styles A key/value style map of the styles that will be applied to the given element.
  26017. * Any missing styles (that have already been applied to the element beforehand) will be
  26018. * removed (unset) from the element's styling.
  26019. *
  26020. * Note that this will apply the provided styleMap value to the host element if this function
  26021. * is called within a host binding.
  26022. *
  26023. * @codeGenApi
  26024. */
  26025. function ɵɵstyleMap(styles) {
  26026. checkStylingMap(styleKeyValueArraySet, styleStringParser, styles, false);
  26027. }
  26028. /**
  26029. * Parse text as style and add values to KeyValueArray.
  26030. *
  26031. * This code is pulled out to a separate function so that it can be tree shaken away if it is not
  26032. * needed. It is only referenced from `ɵɵstyleMap`.
  26033. *
  26034. * @param keyValueArray KeyValueArray to add parsed values to.
  26035. * @param text text to parse.
  26036. */
  26037. function styleStringParser(keyValueArray, text) {
  26038. for (let i = parseStyle(text); i >= 0; i = parseStyleNext(text, i)) {
  26039. styleKeyValueArraySet(keyValueArray, getLastParsedKey(text), getLastParsedValue(text));
  26040. }
  26041. }
  26042. /**
  26043. * Update class bindings using an object literal or class-string on an element.
  26044. *
  26045. * This instruction is meant to apply styling via the `[class]="exp"` template bindings.
  26046. * When classes are applied to the element they will then be updated with
  26047. * respect to any styles/classes set via `classProp`. If any
  26048. * classes are set to falsy then they will be removed from the element.
  26049. *
  26050. * Note that the styling instruction will not be applied until `stylingApply` is called.
  26051. * Note that this will the provided classMap value to the host element if this function is called
  26052. * within a host binding.
  26053. *
  26054. * @param classes A key/value map or string of CSS classes that will be added to the
  26055. * given element. Any missing classes (that have already been applied to the element
  26056. * beforehand) will be removed (unset) from the element's list of CSS classes.
  26057. *
  26058. * @codeGenApi
  26059. */
  26060. function ɵɵclassMap(classes) {
  26061. checkStylingMap(classKeyValueArraySet, classStringParser, classes, true);
  26062. }
  26063. /**
  26064. * Parse text as class and add values to KeyValueArray.
  26065. *
  26066. * This code is pulled out to a separate function so that it can be tree shaken away if it is not
  26067. * needed. It is only referenced from `ɵɵclassMap`.
  26068. *
  26069. * @param keyValueArray KeyValueArray to add parsed values to.
  26070. * @param text text to parse.
  26071. */
  26072. function classStringParser(keyValueArray, text) {
  26073. for (let i = parseClassName(text); i >= 0; i = parseClassNameNext(text, i)) {
  26074. keyValueArraySet(keyValueArray, getLastParsedKey(text), true);
  26075. }
  26076. }
  26077. /**
  26078. * Common code between `ɵɵclassProp` and `ɵɵstyleProp`.
  26079. *
  26080. * @param prop property name.
  26081. * @param value binding value.
  26082. * @param suffix suffix for the property (e.g. `em` or `px`)
  26083. * @param isClassBased `true` if `class` change (`false` if `style`)
  26084. */
  26085. function checkStylingProperty(prop, value, suffix, isClassBased) {
  26086. const lView = getLView();
  26087. const tView = getTView();
  26088. // Styling instructions use 2 slots per binding.
  26089. // 1. one for the value / TStylingKey
  26090. // 2. one for the intermittent-value / TStylingRange
  26091. const bindingIndex = incrementBindingIndex(2);
  26092. if (tView.firstUpdatePass) {
  26093. stylingFirstUpdatePass(tView, prop, bindingIndex, isClassBased);
  26094. }
  26095. if (value !== NO_CHANGE && bindingUpdated(lView, bindingIndex, value)) {
  26096. const tNode = tView.data[getSelectedIndex()];
  26097. updateStyling(tView, tNode, lView, lView[RENDERER], prop, (lView[bindingIndex + 1] = normalizeSuffix(value, suffix)), isClassBased, bindingIndex);
  26098. }
  26099. }
  26100. /**
  26101. * Common code between `ɵɵclassMap` and `ɵɵstyleMap`.
  26102. *
  26103. * @param keyValueArraySet (See `keyValueArraySet` in "util/array_utils") Gets passed in as a
  26104. * function so that `style` can be processed. This is done for tree shaking purposes.
  26105. * @param stringParser Parser used to parse `value` if `string`. (Passed in as `style` and `class`
  26106. * have different parsers.)
  26107. * @param value bound value from application
  26108. * @param isClassBased `true` if `class` change (`false` if `style`)
  26109. */
  26110. function checkStylingMap(keyValueArraySet, stringParser, value, isClassBased) {
  26111. const tView = getTView();
  26112. const bindingIndex = incrementBindingIndex(2);
  26113. if (tView.firstUpdatePass) {
  26114. stylingFirstUpdatePass(tView, null, bindingIndex, isClassBased);
  26115. }
  26116. const lView = getLView();
  26117. if (value !== NO_CHANGE && bindingUpdated(lView, bindingIndex, value)) {
  26118. // `getSelectedIndex()` should be here (rather than in instruction) so that it is guarded by the
  26119. // if so as not to read unnecessarily.
  26120. const tNode = tView.data[getSelectedIndex()];
  26121. if (hasStylingInputShadow(tNode, isClassBased) && !isInHostBindings(tView, bindingIndex)) {
  26122. if (ngDevMode) {
  26123. // verify that if we are shadowing then `TData` is appropriately marked so that we skip
  26124. // processing this binding in styling resolution.
  26125. const tStylingKey = tView.data[bindingIndex];
  26126. assertEqual(Array.isArray(tStylingKey) ? tStylingKey[1] : tStylingKey, false, "Styling linked list shadow input should be marked as 'false'");
  26127. }
  26128. // VE does not concatenate the static portion like we are doing here.
  26129. // Instead VE just ignores the static completely if dynamic binding is present.
  26130. // Because of locality we have already set the static portion because we don't know if there
  26131. // is a dynamic portion until later. If we would ignore the static portion it would look like
  26132. // the binding has removed it. This would confuse `[ngStyle]`/`[ngClass]` to do the wrong
  26133. // thing as it would think that the static portion was removed. For this reason we
  26134. // concatenate it so that `[ngStyle]`/`[ngClass]` can continue to work on changed.
  26135. let staticPrefix = isClassBased ? tNode.classesWithoutHost : tNode.stylesWithoutHost;
  26136. ngDevMode &&
  26137. isClassBased === false &&
  26138. staticPrefix !== null &&
  26139. assertEqual(staticPrefix.endsWith(';'), true, "Expecting static portion to end with ';'");
  26140. if (staticPrefix !== null) {
  26141. // We want to make sure that falsy values of `value` become empty strings.
  26142. value = concatStringsWithSpace(staticPrefix, value ? value : '');
  26143. }
  26144. // Given `<div [style] my-dir>` such that `my-dir` has `@Input('style')`.
  26145. // This takes over the `[style]` binding. (Same for `[class]`)
  26146. setDirectiveInputsWhichShadowsStyling(tView, tNode, lView, value, isClassBased);
  26147. }
  26148. else {
  26149. updateStylingMap(tView, tNode, lView, lView[RENDERER], lView[bindingIndex + 1], (lView[bindingIndex + 1] = toStylingKeyValueArray(keyValueArraySet, stringParser, value)), isClassBased, bindingIndex);
  26150. }
  26151. }
  26152. }
  26153. /**
  26154. * Determines when the binding is in `hostBindings` section
  26155. *
  26156. * @param tView Current `TView`
  26157. * @param bindingIndex index of binding which we would like if it is in `hostBindings`
  26158. */
  26159. function isInHostBindings(tView, bindingIndex) {
  26160. // All host bindings are placed after the expando section.
  26161. return bindingIndex >= tView.expandoStartIndex;
  26162. }
  26163. /**
  26164. * Collects the necessary information to insert the binding into a linked list of style bindings
  26165. * using `insertTStylingBinding`.
  26166. *
  26167. * @param tView `TView` where the binding linked list will be stored.
  26168. * @param tStylingKey Property/key of the binding.
  26169. * @param bindingIndex Index of binding associated with the `prop`
  26170. * @param isClassBased `true` if `class` change (`false` if `style`)
  26171. */
  26172. function stylingFirstUpdatePass(tView, tStylingKey, bindingIndex, isClassBased) {
  26173. ngDevMode && assertFirstUpdatePass(tView);
  26174. const tData = tView.data;
  26175. if (tData[bindingIndex + 1] === null) {
  26176. // The above check is necessary because we don't clear first update pass until first successful
  26177. // (no exception) template execution. This prevents the styling instruction from double adding
  26178. // itself to the list.
  26179. // `getSelectedIndex()` should be here (rather than in instruction) so that it is guarded by the
  26180. // if so as not to read unnecessarily.
  26181. const tNode = tData[getSelectedIndex()];
  26182. ngDevMode && assertDefined(tNode, 'TNode expected');
  26183. const isHostBindings = isInHostBindings(tView, bindingIndex);
  26184. if (hasStylingInputShadow(tNode, isClassBased) && tStylingKey === null && !isHostBindings) {
  26185. // `tStylingKey === null` implies that we are either `[style]` or `[class]` binding.
  26186. // If there is a directive which uses `@Input('style')` or `@Input('class')` than
  26187. // we need to neutralize this binding since that directive is shadowing it.
  26188. // We turn this into a noop by setting the key to `false`
  26189. tStylingKey = false;
  26190. }
  26191. tStylingKey = wrapInStaticStylingKey(tData, tNode, tStylingKey, isClassBased);
  26192. insertTStylingBinding(tData, tNode, tStylingKey, bindingIndex, isHostBindings, isClassBased);
  26193. }
  26194. }
  26195. /**
  26196. * Adds static styling information to the binding if applicable.
  26197. *
  26198. * The linked list of styles not only stores the list and keys, but also stores static styling
  26199. * information on some of the keys. This function determines if the key should contain the styling
  26200. * information and computes it.
  26201. *
  26202. * See `TStylingStatic` for more details.
  26203. *
  26204. * @param tData `TData` where the linked list is stored.
  26205. * @param tNode `TNode` for which the styling is being computed.
  26206. * @param stylingKey `TStylingKeyPrimitive` which may need to be wrapped into `TStylingKey`
  26207. * @param isClassBased `true` if `class` (`false` if `style`)
  26208. */
  26209. function wrapInStaticStylingKey(tData, tNode, stylingKey, isClassBased) {
  26210. const hostDirectiveDef = getCurrentDirectiveDef(tData);
  26211. let residual = isClassBased ? tNode.residualClasses : tNode.residualStyles;
  26212. if (hostDirectiveDef === null) {
  26213. // We are in template node.
  26214. // If template node already had styling instruction then it has already collected the static
  26215. // styling and there is no need to collect them again. We know that we are the first styling
  26216. // instruction because the `TNode.*Bindings` points to 0 (nothing has been inserted yet).
  26217. const isFirstStylingInstructionInTemplate = (isClassBased ? tNode.classBindings : tNode.styleBindings) === 0;
  26218. if (isFirstStylingInstructionInTemplate) {
  26219. // It would be nice to be able to get the statics from `mergeAttrs`, however, at this point
  26220. // they are already merged and it would not be possible to figure which property belongs where
  26221. // in the priority.
  26222. stylingKey = collectStylingFromDirectives(null, tData, tNode, stylingKey, isClassBased);
  26223. stylingKey = collectStylingFromTAttrs(stylingKey, tNode.attrs, isClassBased);
  26224. // We know that if we have styling binding in template we can't have residual.
  26225. residual = null;
  26226. }
  26227. }
  26228. else {
  26229. // We are in host binding node and there was no binding instruction in template node.
  26230. // This means that we need to compute the residual.
  26231. const directiveStylingLast = tNode.directiveStylingLast;
  26232. const isFirstStylingInstructionInHostBinding = directiveStylingLast === -1 || tData[directiveStylingLast] !== hostDirectiveDef;
  26233. if (isFirstStylingInstructionInHostBinding) {
  26234. stylingKey = collectStylingFromDirectives(hostDirectiveDef, tData, tNode, stylingKey, isClassBased);
  26235. if (residual === null) {
  26236. // - If `null` than either:
  26237. // - Template styling instruction already ran and it has consumed the static
  26238. // styling into its `TStylingKey` and so there is no need to update residual. Instead
  26239. // we need to update the `TStylingKey` associated with the first template node
  26240. // instruction. OR
  26241. // - Some other styling instruction ran and determined that there are no residuals
  26242. let templateStylingKey = getTemplateHeadTStylingKey(tData, tNode, isClassBased);
  26243. if (templateStylingKey !== undefined && Array.isArray(templateStylingKey)) {
  26244. // Only recompute if `templateStylingKey` had static values. (If no static value found
  26245. // then there is nothing to do since this operation can only produce less static keys, not
  26246. // more.)
  26247. templateStylingKey = collectStylingFromDirectives(null, tData, tNode, templateStylingKey[1] /* unwrap previous statics */, isClassBased);
  26248. templateStylingKey = collectStylingFromTAttrs(templateStylingKey, tNode.attrs, isClassBased);
  26249. setTemplateHeadTStylingKey(tData, tNode, isClassBased, templateStylingKey);
  26250. }
  26251. }
  26252. else {
  26253. // We only need to recompute residual if it is not `null`.
  26254. // - If existing residual (implies there was no template styling). This means that some of
  26255. // the statics may have moved from the residual to the `stylingKey` and so we have to
  26256. // recompute.
  26257. // - If `undefined` this is the first time we are running.
  26258. residual = collectResidual(tData, tNode, isClassBased);
  26259. }
  26260. }
  26261. }
  26262. if (residual !== undefined) {
  26263. isClassBased ? (tNode.residualClasses = residual) : (tNode.residualStyles = residual);
  26264. }
  26265. return stylingKey;
  26266. }
  26267. /**
  26268. * Retrieve the `TStylingKey` for the template styling instruction.
  26269. *
  26270. * This is needed since `hostBinding` styling instructions are inserted after the template
  26271. * instruction. While the template instruction needs to update the residual in `TNode` the
  26272. * `hostBinding` instructions need to update the `TStylingKey` of the template instruction because
  26273. * the template instruction is downstream from the `hostBindings` instructions.
  26274. *
  26275. * @param tData `TData` where the linked list is stored.
  26276. * @param tNode `TNode` for which the styling is being computed.
  26277. * @param isClassBased `true` if `class` (`false` if `style`)
  26278. * @return `TStylingKey` if found or `undefined` if not found.
  26279. */
  26280. function getTemplateHeadTStylingKey(tData, tNode, isClassBased) {
  26281. const bindings = isClassBased ? tNode.classBindings : tNode.styleBindings;
  26282. if (getTStylingRangeNext(bindings) === 0) {
  26283. // There does not seem to be a styling instruction in the `template`.
  26284. return undefined;
  26285. }
  26286. return tData[getTStylingRangePrev(bindings)];
  26287. }
  26288. /**
  26289. * Update the `TStylingKey` of the first template instruction in `TNode`.
  26290. *
  26291. * Logically `hostBindings` styling instructions are of lower priority than that of the template.
  26292. * However, they execute after the template styling instructions. This means that they get inserted
  26293. * in front of the template styling instructions.
  26294. *
  26295. * If we have a template styling instruction and a new `hostBindings` styling instruction is
  26296. * executed it means that it may need to steal static fields from the template instruction. This
  26297. * method allows us to update the first template instruction `TStylingKey` with a new value.
  26298. *
  26299. * Assume:
  26300. * ```angular-ts
  26301. * <div my-dir style="color: red" [style.color]="tmplExp"></div>
  26302. *
  26303. * @Directive({
  26304. * host: {
  26305. * 'style': 'width: 100px',
  26306. * '[style.color]': 'dirExp',
  26307. * }
  26308. * })
  26309. * class MyDir {}
  26310. * ```
  26311. *
  26312. * when `[style.color]="tmplExp"` executes it creates this data structure.
  26313. * ```ts
  26314. * ['', 'color', 'color', 'red', 'width', '100px'],
  26315. * ```
  26316. *
  26317. * The reason for this is that the template instruction does not know if there are styling
  26318. * instructions and must assume that there are none and must collect all of the static styling.
  26319. * (both
  26320. * `color' and 'width`)
  26321. *
  26322. * When `'[style.color]': 'dirExp',` executes we need to insert a new data into the linked list.
  26323. * ```ts
  26324. * ['', 'color', 'width', '100px'], // newly inserted
  26325. * ['', 'color', 'color', 'red', 'width', '100px'], // this is wrong
  26326. * ```
  26327. *
  26328. * Notice that the template statics is now wrong as it incorrectly contains `width` so we need to
  26329. * update it like so:
  26330. * ```ts
  26331. * ['', 'color', 'width', '100px'],
  26332. * ['', 'color', 'color', 'red'], // UPDATE
  26333. * ```
  26334. *
  26335. * @param tData `TData` where the linked list is stored.
  26336. * @param tNode `TNode` for which the styling is being computed.
  26337. * @param isClassBased `true` if `class` (`false` if `style`)
  26338. * @param tStylingKey New `TStylingKey` which is replacing the old one.
  26339. */
  26340. function setTemplateHeadTStylingKey(tData, tNode, isClassBased, tStylingKey) {
  26341. const bindings = isClassBased ? tNode.classBindings : tNode.styleBindings;
  26342. ngDevMode &&
  26343. assertNotEqual(getTStylingRangeNext(bindings), 0, 'Expecting to have at least one template styling binding.');
  26344. tData[getTStylingRangePrev(bindings)] = tStylingKey;
  26345. }
  26346. /**
  26347. * Collect all static values after the current `TNode.directiveStylingLast` index.
  26348. *
  26349. * Collect the remaining styling information which has not yet been collected by an existing
  26350. * styling instruction.
  26351. *
  26352. * @param tData `TData` where the `DirectiveDefs` are stored.
  26353. * @param tNode `TNode` which contains the directive range.
  26354. * @param isClassBased `true` if `class` (`false` if `style`)
  26355. */
  26356. function collectResidual(tData, tNode, isClassBased) {
  26357. let residual = undefined;
  26358. const directiveEnd = tNode.directiveEnd;
  26359. ngDevMode &&
  26360. assertNotEqual(tNode.directiveStylingLast, -1, 'By the time this function gets called at least one hostBindings-node styling instruction must have executed.');
  26361. // We add `1 + tNode.directiveStart` because we need to skip the current directive (as we are
  26362. // collecting things after the last `hostBindings` directive which had a styling instruction.)
  26363. for (let i = 1 + tNode.directiveStylingLast; i < directiveEnd; i++) {
  26364. const attrs = tData[i].hostAttrs;
  26365. residual = collectStylingFromTAttrs(residual, attrs, isClassBased);
  26366. }
  26367. return collectStylingFromTAttrs(residual, tNode.attrs, isClassBased);
  26368. }
  26369. /**
  26370. * Collect the static styling information with lower priority than `hostDirectiveDef`.
  26371. *
  26372. * (This is opposite of residual styling.)
  26373. *
  26374. * @param hostDirectiveDef `DirectiveDef` for which we want to collect lower priority static
  26375. * styling. (Or `null` if template styling)
  26376. * @param tData `TData` where the linked list is stored.
  26377. * @param tNode `TNode` for which the styling is being computed.
  26378. * @param stylingKey Existing `TStylingKey` to update or wrap.
  26379. * @param isClassBased `true` if `class` (`false` if `style`)
  26380. */
  26381. function collectStylingFromDirectives(hostDirectiveDef, tData, tNode, stylingKey, isClassBased) {
  26382. // We need to loop because there can be directives which have `hostAttrs` but don't have
  26383. // `hostBindings` so this loop catches up to the current directive..
  26384. let currentDirective = null;
  26385. const directiveEnd = tNode.directiveEnd;
  26386. let directiveStylingLast = tNode.directiveStylingLast;
  26387. if (directiveStylingLast === -1) {
  26388. directiveStylingLast = tNode.directiveStart;
  26389. }
  26390. else {
  26391. directiveStylingLast++;
  26392. }
  26393. while (directiveStylingLast < directiveEnd) {
  26394. currentDirective = tData[directiveStylingLast];
  26395. ngDevMode && assertDefined(currentDirective, 'expected to be defined');
  26396. stylingKey = collectStylingFromTAttrs(stylingKey, currentDirective.hostAttrs, isClassBased);
  26397. if (currentDirective === hostDirectiveDef)
  26398. break;
  26399. directiveStylingLast++;
  26400. }
  26401. if (hostDirectiveDef !== null) {
  26402. // we only advance the styling cursor if we are collecting data from host bindings.
  26403. // Template executes before host bindings and so if we would update the index,
  26404. // host bindings would not get their statics.
  26405. tNode.directiveStylingLast = directiveStylingLast;
  26406. }
  26407. return stylingKey;
  26408. }
  26409. /**
  26410. * Convert `TAttrs` into `TStylingStatic`.
  26411. *
  26412. * @param stylingKey existing `TStylingKey` to update or wrap.
  26413. * @param attrs `TAttributes` to process.
  26414. * @param isClassBased `true` if `class` (`false` if `style`)
  26415. */
  26416. function collectStylingFromTAttrs(stylingKey, attrs, isClassBased) {
  26417. const desiredMarker = isClassBased ? 1 /* AttributeMarker.Classes */ : 2 /* AttributeMarker.Styles */;
  26418. let currentMarker = -1 /* AttributeMarker.ImplicitAttributes */;
  26419. if (attrs !== null) {
  26420. for (let i = 0; i < attrs.length; i++) {
  26421. const item = attrs[i];
  26422. if (typeof item === 'number') {
  26423. currentMarker = item;
  26424. }
  26425. else {
  26426. if (currentMarker === desiredMarker) {
  26427. if (!Array.isArray(stylingKey)) {
  26428. stylingKey = stylingKey === undefined ? [] : ['', stylingKey];
  26429. }
  26430. keyValueArraySet(stylingKey, item, isClassBased ? true : attrs[++i]);
  26431. }
  26432. }
  26433. }
  26434. }
  26435. return stylingKey === undefined ? null : stylingKey;
  26436. }
  26437. /**
  26438. * Convert user input to `KeyValueArray`.
  26439. *
  26440. * This function takes user input which could be `string`, Object literal, or iterable and converts
  26441. * it into a consistent representation. The output of this is `KeyValueArray` (which is an array
  26442. * where
  26443. * even indexes contain keys and odd indexes contain values for those keys).
  26444. *
  26445. * The advantage of converting to `KeyValueArray` is that we can perform diff in an input
  26446. * independent
  26447. * way.
  26448. * (ie we can compare `foo bar` to `['bar', 'baz'] and determine a set of changes which need to be
  26449. * applied)
  26450. *
  26451. * The fact that `KeyValueArray` is sorted is very important because it allows us to compute the
  26452. * difference in linear fashion without the need to allocate any additional data.
  26453. *
  26454. * For example if we kept this as a `Map` we would have to iterate over previous `Map` to determine
  26455. * which values need to be deleted, over the new `Map` to determine additions, and we would have to
  26456. * keep additional `Map` to keep track of duplicates or items which have not yet been visited.
  26457. *
  26458. * @param keyValueArraySet (See `keyValueArraySet` in "util/array_utils") Gets passed in as a
  26459. * function so that `style` can be processed. This is done
  26460. * for tree shaking purposes.
  26461. * @param stringParser The parser is passed in so that it will be tree shakable. See
  26462. * `styleStringParser` and `classStringParser`
  26463. * @param value The value to parse/convert to `KeyValueArray`
  26464. */
  26465. function toStylingKeyValueArray(keyValueArraySet, stringParser, value) {
  26466. if (value == null /*|| value === undefined */ || value === '')
  26467. return EMPTY_ARRAY;
  26468. const styleKeyValueArray = [];
  26469. const unwrappedValue = unwrapSafeValue(value);
  26470. if (Array.isArray(unwrappedValue)) {
  26471. for (let i = 0; i < unwrappedValue.length; i++) {
  26472. keyValueArraySet(styleKeyValueArray, unwrappedValue[i], true);
  26473. }
  26474. }
  26475. else if (typeof unwrappedValue === 'object') {
  26476. for (const key in unwrappedValue) {
  26477. if (unwrappedValue.hasOwnProperty(key)) {
  26478. keyValueArraySet(styleKeyValueArray, key, unwrappedValue[key]);
  26479. }
  26480. }
  26481. }
  26482. else if (typeof unwrappedValue === 'string') {
  26483. stringParser(styleKeyValueArray, unwrappedValue);
  26484. }
  26485. else {
  26486. ngDevMode &&
  26487. throwError('Unsupported styling type: ' + typeof unwrappedValue + ' (' + unwrappedValue + ')');
  26488. }
  26489. return styleKeyValueArray;
  26490. }
  26491. /**
  26492. * Set a `value` for a `key`.
  26493. *
  26494. * See: `keyValueArraySet` for details
  26495. *
  26496. * @param keyValueArray KeyValueArray to add to.
  26497. * @param key Style key to add.
  26498. * @param value The value to set.
  26499. */
  26500. function styleKeyValueArraySet(keyValueArray, key, value) {
  26501. keyValueArraySet(keyValueArray, key, unwrapSafeValue(value));
  26502. }
  26503. /**
  26504. * Class-binding-specific function for setting the `value` for a `key`.
  26505. *
  26506. * See: `keyValueArraySet` for details
  26507. *
  26508. * @param keyValueArray KeyValueArray to add to.
  26509. * @param key Style key to add.
  26510. * @param value The value to set.
  26511. */
  26512. function classKeyValueArraySet(keyValueArray, key, value) {
  26513. // We use `classList.add` to eventually add the CSS classes to the DOM node. Any value passed into
  26514. // `add` is stringified and added to the `class` attribute, e.g. even null, undefined or numbers
  26515. // will be added. Stringify the key here so that our internal data structure matches the value in
  26516. // the DOM. The only exceptions are empty strings and strings that contain spaces for which
  26517. // the browser throws an error. We ignore such values, because the error is somewhat cryptic.
  26518. const stringKey = String(key);
  26519. if (stringKey !== '' && !stringKey.includes(' ')) {
  26520. keyValueArraySet(keyValueArray, stringKey, value);
  26521. }
  26522. }
  26523. /**
  26524. * Update map based styling.
  26525. *
  26526. * Map based styling could be anything which contains more than one binding. For example `string`,
  26527. * or object literal. Dealing with all of these types would complicate the logic so
  26528. * instead this function expects that the complex input is first converted into normalized
  26529. * `KeyValueArray`. The advantage of normalization is that we get the values sorted, which makes it
  26530. * very cheap to compute deltas between the previous and current value.
  26531. *
  26532. * @param tView Associated `TView.data` contains the linked list of binding priorities.
  26533. * @param tNode `TNode` where the binding is located.
  26534. * @param lView `LView` contains the values associated with other styling binding at this `TNode`.
  26535. * @param renderer Renderer to use if any updates.
  26536. * @param oldKeyValueArray Previous value represented as `KeyValueArray`
  26537. * @param newKeyValueArray Current value represented as `KeyValueArray`
  26538. * @param isClassBased `true` if `class` (`false` if `style`)
  26539. * @param bindingIndex Binding index of the binding.
  26540. */
  26541. function updateStylingMap(tView, tNode, lView, renderer, oldKeyValueArray, newKeyValueArray, isClassBased, bindingIndex) {
  26542. if (oldKeyValueArray === NO_CHANGE) {
  26543. // On first execution the oldKeyValueArray is NO_CHANGE => treat it as empty KeyValueArray.
  26544. oldKeyValueArray = EMPTY_ARRAY;
  26545. }
  26546. let oldIndex = 0;
  26547. let newIndex = 0;
  26548. let oldKey = 0 < oldKeyValueArray.length ? oldKeyValueArray[0] : null;
  26549. let newKey = 0 < newKeyValueArray.length ? newKeyValueArray[0] : null;
  26550. while (oldKey !== null || newKey !== null) {
  26551. ngDevMode && assertLessThan(oldIndex, 999, 'Are we stuck in infinite loop?');
  26552. ngDevMode && assertLessThan(newIndex, 999, 'Are we stuck in infinite loop?');
  26553. const oldValue = oldIndex < oldKeyValueArray.length ? oldKeyValueArray[oldIndex + 1] : undefined;
  26554. const newValue = newIndex < newKeyValueArray.length ? newKeyValueArray[newIndex + 1] : undefined;
  26555. let setKey = null;
  26556. let setValue = undefined;
  26557. if (oldKey === newKey) {
  26558. // UPDATE: Keys are equal => new value is overwriting old value.
  26559. oldIndex += 2;
  26560. newIndex += 2;
  26561. if (oldValue !== newValue) {
  26562. setKey = newKey;
  26563. setValue = newValue;
  26564. }
  26565. }
  26566. else if (newKey === null || (oldKey !== null && oldKey < newKey)) {
  26567. // DELETE: oldKey key is missing or we did not find the oldKey in the newValue
  26568. // (because the keyValueArray is sorted and `newKey` is found later alphabetically).
  26569. // `"background" < "color"` so we need to delete `"background"` because it is not found in the
  26570. // new array.
  26571. oldIndex += 2;
  26572. setKey = oldKey;
  26573. }
  26574. else {
  26575. // CREATE: newKey's is earlier alphabetically than oldKey's (or no oldKey) => we have new key.
  26576. // `"color" > "background"` so we need to add `color` because it is in new array but not in
  26577. // old array.
  26578. ngDevMode && assertDefined(newKey, 'Expecting to have a valid key');
  26579. newIndex += 2;
  26580. setKey = newKey;
  26581. setValue = newValue;
  26582. }
  26583. if (setKey !== null) {
  26584. updateStyling(tView, tNode, lView, renderer, setKey, setValue, isClassBased, bindingIndex);
  26585. }
  26586. oldKey = oldIndex < oldKeyValueArray.length ? oldKeyValueArray[oldIndex] : null;
  26587. newKey = newIndex < newKeyValueArray.length ? newKeyValueArray[newIndex] : null;
  26588. }
  26589. }
  26590. /**
  26591. * Update a simple (property name) styling.
  26592. *
  26593. * This function takes `prop` and updates the DOM to that value. The function takes the binding
  26594. * value as well as binding priority into consideration to determine which value should be written
  26595. * to DOM. (For example it may be determined that there is a higher priority overwrite which blocks
  26596. * the DOM write, or if the value goes to `undefined` a lower priority overwrite may be consulted.)
  26597. *
  26598. * @param tView Associated `TView.data` contains the linked list of binding priorities.
  26599. * @param tNode `TNode` where the binding is located.
  26600. * @param lView `LView` contains the values associated with other styling binding at this `TNode`.
  26601. * @param renderer Renderer to use if any updates.
  26602. * @param prop Either style property name or a class name.
  26603. * @param value Either style value for `prop` or `true`/`false` if `prop` is class.
  26604. * @param isClassBased `true` if `class` (`false` if `style`)
  26605. * @param bindingIndex Binding index of the binding.
  26606. */
  26607. function updateStyling(tView, tNode, lView, renderer, prop, value, isClassBased, bindingIndex) {
  26608. if (!(tNode.type & 3 /* TNodeType.AnyRNode */)) {
  26609. // It is possible to have styling on non-elements (such as ng-container).
  26610. // This is rare, but it does happen. In such a case, just ignore the binding.
  26611. return;
  26612. }
  26613. const tData = tView.data;
  26614. const tRange = tData[bindingIndex + 1];
  26615. const higherPriorityValue = getTStylingRangeNextDuplicate(tRange)
  26616. ? findStylingValue(tData, tNode, lView, prop, getTStylingRangeNext(tRange), isClassBased)
  26617. : undefined;
  26618. if (!isStylingValuePresent(higherPriorityValue)) {
  26619. // We don't have a next duplicate, or we did not find a duplicate value.
  26620. if (!isStylingValuePresent(value)) {
  26621. // We should delete current value or restore to lower priority value.
  26622. if (getTStylingRangePrevDuplicate(tRange)) {
  26623. // We have a possible prev duplicate, let's retrieve it.
  26624. value = findStylingValue(tData, null, lView, prop, bindingIndex, isClassBased);
  26625. }
  26626. }
  26627. const rNode = getNativeByIndex(getSelectedIndex(), lView);
  26628. applyStyling(renderer, isClassBased, rNode, prop, value);
  26629. }
  26630. }
  26631. /**
  26632. * Search for styling value with higher priority which is overwriting current value, or a
  26633. * value of lower priority to which we should fall back if the value is `undefined`.
  26634. *
  26635. * When value is being applied at a location, related values need to be consulted.
  26636. * - If there is a higher priority binding, we should be using that one instead.
  26637. * For example `<div [style]="{color:exp1}" [style.color]="exp2">` change to `exp1`
  26638. * requires that we check `exp2` to see if it is set to value other than `undefined`.
  26639. * - If there is a lower priority binding and we are changing to `undefined`
  26640. * For example `<div [style]="{color:exp1}" [style.color]="exp2">` change to `exp2` to
  26641. * `undefined` requires that we check `exp1` (and static values) and use that as new value.
  26642. *
  26643. * NOTE: The styling stores two values.
  26644. * 1. The raw value which came from the application is stored at `index + 0` location. (This value
  26645. * is used for dirty checking).
  26646. * 2. The normalized value is stored at `index + 1`.
  26647. *
  26648. * @param tData `TData` used for traversing the priority.
  26649. * @param tNode `TNode` to use for resolving static styling. Also controls search direction.
  26650. * - `TNode` search next and quit as soon as `isStylingValuePresent(value)` is true.
  26651. * If no value found consult `tNode.residualStyle`/`tNode.residualClass` for default value.
  26652. * - `null` search prev and go all the way to end. Return last value where
  26653. * `isStylingValuePresent(value)` is true.
  26654. * @param lView `LView` used for retrieving the actual values.
  26655. * @param prop Property which we are interested in.
  26656. * @param index Starting index in the linked list of styling bindings where the search should start.
  26657. * @param isClassBased `true` if `class` (`false` if `style`)
  26658. */
  26659. function findStylingValue(tData, tNode, lView, prop, index, isClassBased) {
  26660. // `TNode` to use for resolving static styling. Also controls search direction.
  26661. // - `TNode` search next and quit as soon as `isStylingValuePresent(value)` is true.
  26662. // If no value found consult `tNode.residualStyle`/`tNode.residualClass` for default value.
  26663. // - `null` search prev and go all the way to end. Return last value where
  26664. // `isStylingValuePresent(value)` is true.
  26665. const isPrevDirection = tNode === null;
  26666. let value = undefined;
  26667. while (index > 0) {
  26668. const rawKey = tData[index];
  26669. const containsStatics = Array.isArray(rawKey);
  26670. // Unwrap the key if we contain static values.
  26671. const key = containsStatics ? rawKey[1] : rawKey;
  26672. const isStylingMap = key === null;
  26673. let valueAtLViewIndex = lView[index + 1];
  26674. if (valueAtLViewIndex === NO_CHANGE) {
  26675. // In firstUpdatePass the styling instructions create a linked list of styling.
  26676. // On subsequent passes it is possible for a styling instruction to try to read a binding
  26677. // which
  26678. // has not yet executed. In that case we will find `NO_CHANGE` and we should assume that
  26679. // we have `undefined` (or empty array in case of styling-map instruction) instead. This
  26680. // allows the resolution to apply the value (which may later be overwritten when the
  26681. // binding actually executes.)
  26682. valueAtLViewIndex = isStylingMap ? EMPTY_ARRAY : undefined;
  26683. }
  26684. let currentValue = isStylingMap
  26685. ? keyValueArrayGet(valueAtLViewIndex, prop)
  26686. : key === prop
  26687. ? valueAtLViewIndex
  26688. : undefined;
  26689. if (containsStatics && !isStylingValuePresent(currentValue)) {
  26690. currentValue = keyValueArrayGet(rawKey, prop);
  26691. }
  26692. if (isStylingValuePresent(currentValue)) {
  26693. value = currentValue;
  26694. if (isPrevDirection) {
  26695. return value;
  26696. }
  26697. }
  26698. const tRange = tData[index + 1];
  26699. index = isPrevDirection ? getTStylingRangePrev(tRange) : getTStylingRangeNext(tRange);
  26700. }
  26701. if (tNode !== null) {
  26702. // in case where we are going in next direction AND we did not find anything, we need to
  26703. // consult residual styling
  26704. let residual = isClassBased ? tNode.residualClasses : tNode.residualStyles;
  26705. if (residual != null /** OR residual !=== undefined */) {
  26706. value = keyValueArrayGet(residual, prop);
  26707. }
  26708. }
  26709. return value;
  26710. }
  26711. /**
  26712. * Determines if the binding value should be used (or if the value is 'undefined' and hence priority
  26713. * resolution should be used.)
  26714. *
  26715. * @param value Binding style value.
  26716. */
  26717. function isStylingValuePresent(value) {
  26718. // Currently only `undefined` value is considered non-binding. That is `undefined` says I don't
  26719. // have an opinion as to what this binding should be and you should consult other bindings by
  26720. // priority to determine the valid value.
  26721. // This is extracted into a single function so that we have a single place to control this.
  26722. return value !== undefined;
  26723. }
  26724. /**
  26725. * Normalizes and/or adds a suffix to the value.
  26726. *
  26727. * If value is `null`/`undefined` no suffix is added
  26728. * @param value
  26729. * @param suffix
  26730. */
  26731. function normalizeSuffix(value, suffix) {
  26732. if (value == null || value === '') ;
  26733. else if (typeof suffix === 'string') {
  26734. value = value + suffix;
  26735. }
  26736. else if (typeof value === 'object') {
  26737. value = stringify(unwrapSafeValue(value));
  26738. }
  26739. return value;
  26740. }
  26741. /**
  26742. * Tests if the `TNode` has input shadow.
  26743. *
  26744. * An input shadow is when a directive steals (shadows) the input by using `@Input('style')` or
  26745. * `@Input('class')` as input.
  26746. *
  26747. * @param tNode `TNode` which we would like to see if it has shadow.
  26748. * @param isClassBased `true` if `class` (`false` if `style`)
  26749. */
  26750. function hasStylingInputShadow(tNode, isClassBased) {
  26751. return (tNode.flags & (isClassBased ? 8 /* TNodeFlags.hasClassInput */ : 16 /* TNodeFlags.hasStyleInput */)) !== 0;
  26752. }
  26753. /**
  26754. *
  26755. * Update an interpolated class on an element with single bound value surrounded by text.
  26756. *
  26757. * Used when the value passed to a property has 1 interpolated value in it:
  26758. *
  26759. * ```html
  26760. * <div class="prefix{{v0}}suffix"></div>
  26761. * ```
  26762. *
  26763. * Its compiled representation is:
  26764. *
  26765. * ```ts
  26766. * ɵɵclassMapInterpolate1('prefix', v0, 'suffix');
  26767. * ```
  26768. *
  26769. * @param prefix Static value used for concatenation only.
  26770. * @param v0 Value checked for change.
  26771. * @param suffix Static value used for concatenation only.
  26772. * @codeGenApi
  26773. */
  26774. function ɵɵclassMapInterpolate1(prefix, v0, suffix) {
  26775. const lView = getLView();
  26776. const interpolatedValue = interpolation1(lView, prefix, v0, suffix);
  26777. checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
  26778. }
  26779. /**
  26780. *
  26781. * Update an interpolated class on an element with 2 bound values surrounded by text.
  26782. *
  26783. * Used when the value passed to a property has 2 interpolated values in it:
  26784. *
  26785. * ```html
  26786. * <div class="prefix{{v0}}-{{v1}}suffix"></div>
  26787. * ```
  26788. *
  26789. * Its compiled representation is:
  26790. *
  26791. * ```ts
  26792. * ɵɵclassMapInterpolate2('prefix', v0, '-', v1, 'suffix');
  26793. * ```
  26794. *
  26795. * @param prefix Static value used for concatenation only.
  26796. * @param v0 Value checked for change.
  26797. * @param i0 Static value used for concatenation only.
  26798. * @param v1 Value checked for change.
  26799. * @param suffix Static value used for concatenation only.
  26800. * @codeGenApi
  26801. */
  26802. function ɵɵclassMapInterpolate2(prefix, v0, i0, v1, suffix) {
  26803. const lView = getLView();
  26804. const interpolatedValue = interpolation2(lView, prefix, v0, i0, v1, suffix);
  26805. checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
  26806. }
  26807. /**
  26808. *
  26809. * Update an interpolated class on an element with 3 bound values surrounded by text.
  26810. *
  26811. * Used when the value passed to a property has 3 interpolated values in it:
  26812. *
  26813. * ```html
  26814. * <div class="prefix{{v0}}-{{v1}}-{{v2}}suffix"></div>
  26815. * ```
  26816. *
  26817. * Its compiled representation is:
  26818. *
  26819. * ```ts
  26820. * ɵɵclassMapInterpolate3(
  26821. * 'prefix', v0, '-', v1, '-', v2, 'suffix');
  26822. * ```
  26823. *
  26824. * @param prefix Static value used for concatenation only.
  26825. * @param v0 Value checked for change.
  26826. * @param i0 Static value used for concatenation only.
  26827. * @param v1 Value checked for change.
  26828. * @param i1 Static value used for concatenation only.
  26829. * @param v2 Value checked for change.
  26830. * @param suffix Static value used for concatenation only.
  26831. * @codeGenApi
  26832. */
  26833. function ɵɵclassMapInterpolate3(prefix, v0, i0, v1, i1, v2, suffix) {
  26834. const lView = getLView();
  26835. const interpolatedValue = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix);
  26836. checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
  26837. }
  26838. /**
  26839. *
  26840. * Update an interpolated class on an element with 4 bound values surrounded by text.
  26841. *
  26842. * Used when the value passed to a property has 4 interpolated values in it:
  26843. *
  26844. * ```html
  26845. * <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}suffix"></div>
  26846. * ```
  26847. *
  26848. * Its compiled representation is:
  26849. *
  26850. * ```ts
  26851. * ɵɵclassMapInterpolate4(
  26852. * 'prefix', v0, '-', v1, '-', v2, '-', v3, 'suffix');
  26853. * ```
  26854. *
  26855. * @param prefix Static value used for concatenation only.
  26856. * @param v0 Value checked for change.
  26857. * @param i0 Static value used for concatenation only.
  26858. * @param v1 Value checked for change.
  26859. * @param i1 Static value used for concatenation only.
  26860. * @param v2 Value checked for change.
  26861. * @param i2 Static value used for concatenation only.
  26862. * @param v3 Value checked for change.
  26863. * @param suffix Static value used for concatenation only.
  26864. * @codeGenApi
  26865. */
  26866. function ɵɵclassMapInterpolate4(prefix, v0, i0, v1, i1, v2, i2, v3, suffix) {
  26867. const lView = getLView();
  26868. const interpolatedValue = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix);
  26869. checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
  26870. }
  26871. /**
  26872. *
  26873. * Update an interpolated class on an element with 5 bound values surrounded by text.
  26874. *
  26875. * Used when the value passed to a property has 5 interpolated values in it:
  26876. *
  26877. * ```html
  26878. * <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}suffix"></div>
  26879. * ```
  26880. *
  26881. * Its compiled representation is:
  26882. *
  26883. * ```ts
  26884. * ɵɵclassMapInterpolate5(
  26885. * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, 'suffix');
  26886. * ```
  26887. *
  26888. * @param prefix Static value used for concatenation only.
  26889. * @param v0 Value checked for change.
  26890. * @param i0 Static value used for concatenation only.
  26891. * @param v1 Value checked for change.
  26892. * @param i1 Static value used for concatenation only.
  26893. * @param v2 Value checked for change.
  26894. * @param i2 Static value used for concatenation only.
  26895. * @param v3 Value checked for change.
  26896. * @param i3 Static value used for concatenation only.
  26897. * @param v4 Value checked for change.
  26898. * @param suffix Static value used for concatenation only.
  26899. * @codeGenApi
  26900. */
  26901. function ɵɵclassMapInterpolate5(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix) {
  26902. const lView = getLView();
  26903. const interpolatedValue = interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix);
  26904. checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
  26905. }
  26906. /**
  26907. *
  26908. * Update an interpolated class on an element with 6 bound values surrounded by text.
  26909. *
  26910. * Used when the value passed to a property has 6 interpolated values in it:
  26911. *
  26912. * ```html
  26913. * <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}suffix"></div>
  26914. * ```
  26915. *
  26916. * Its compiled representation is:
  26917. *
  26918. * ```ts
  26919. * ɵɵclassMapInterpolate6(
  26920. * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, 'suffix');
  26921. * ```
  26922. *
  26923. * @param prefix Static value used for concatenation only.
  26924. * @param v0 Value checked for change.
  26925. * @param i0 Static value used for concatenation only.
  26926. * @param v1 Value checked for change.
  26927. * @param i1 Static value used for concatenation only.
  26928. * @param v2 Value checked for change.
  26929. * @param i2 Static value used for concatenation only.
  26930. * @param v3 Value checked for change.
  26931. * @param i3 Static value used for concatenation only.
  26932. * @param v4 Value checked for change.
  26933. * @param i4 Static value used for concatenation only.
  26934. * @param v5 Value checked for change.
  26935. * @param suffix Static value used for concatenation only.
  26936. * @codeGenApi
  26937. */
  26938. function ɵɵclassMapInterpolate6(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix) {
  26939. const lView = getLView();
  26940. const interpolatedValue = interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix);
  26941. checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
  26942. }
  26943. /**
  26944. *
  26945. * Update an interpolated class on an element with 7 bound values surrounded by text.
  26946. *
  26947. * Used when the value passed to a property has 7 interpolated values in it:
  26948. *
  26949. * ```html
  26950. * <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}suffix"></div>
  26951. * ```
  26952. *
  26953. * Its compiled representation is:
  26954. *
  26955. * ```ts
  26956. * ɵɵclassMapInterpolate7(
  26957. * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, 'suffix');
  26958. * ```
  26959. *
  26960. * @param prefix Static value used for concatenation only.
  26961. * @param v0 Value checked for change.
  26962. * @param i0 Static value used for concatenation only.
  26963. * @param v1 Value checked for change.
  26964. * @param i1 Static value used for concatenation only.
  26965. * @param v2 Value checked for change.
  26966. * @param i2 Static value used for concatenation only.
  26967. * @param v3 Value checked for change.
  26968. * @param i3 Static value used for concatenation only.
  26969. * @param v4 Value checked for change.
  26970. * @param i4 Static value used for concatenation only.
  26971. * @param v5 Value checked for change.
  26972. * @param i5 Static value used for concatenation only.
  26973. * @param v6 Value checked for change.
  26974. * @param suffix Static value used for concatenation only.
  26975. * @codeGenApi
  26976. */
  26977. function ɵɵclassMapInterpolate7(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix) {
  26978. const lView = getLView();
  26979. const interpolatedValue = interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix);
  26980. checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
  26981. }
  26982. /**
  26983. *
  26984. * Update an interpolated class on an element with 8 bound values surrounded by text.
  26985. *
  26986. * Used when the value passed to a property has 8 interpolated values in it:
  26987. *
  26988. * ```html
  26989. * <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}suffix"></div>
  26990. * ```
  26991. *
  26992. * Its compiled representation is:
  26993. *
  26994. * ```ts
  26995. * ɵɵclassMapInterpolate8(
  26996. * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, 'suffix');
  26997. * ```
  26998. *
  26999. * @param prefix Static value used for concatenation only.
  27000. * @param v0 Value checked for change.
  27001. * @param i0 Static value used for concatenation only.
  27002. * @param v1 Value checked for change.
  27003. * @param i1 Static value used for concatenation only.
  27004. * @param v2 Value checked for change.
  27005. * @param i2 Static value used for concatenation only.
  27006. * @param v3 Value checked for change.
  27007. * @param i3 Static value used for concatenation only.
  27008. * @param v4 Value checked for change.
  27009. * @param i4 Static value used for concatenation only.
  27010. * @param v5 Value checked for change.
  27011. * @param i5 Static value used for concatenation only.
  27012. * @param v6 Value checked for change.
  27013. * @param i6 Static value used for concatenation only.
  27014. * @param v7 Value checked for change.
  27015. * @param suffix Static value used for concatenation only.
  27016. * @codeGenApi
  27017. */
  27018. function ɵɵclassMapInterpolate8(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix) {
  27019. const lView = getLView();
  27020. const interpolatedValue = interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix);
  27021. checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
  27022. }
  27023. /**
  27024. * Update an interpolated class on an element with 9 or more bound values surrounded by text.
  27025. *
  27026. * Used when the number of interpolated values exceeds 8.
  27027. *
  27028. * ```html
  27029. * <div
  27030. * class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}-{{v8}}-{{v9}}suffix"></div>
  27031. * ```
  27032. *
  27033. * Its compiled representation is:
  27034. *
  27035. * ```ts
  27036. * ɵɵclassMapInterpolateV(
  27037. * ['prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, '-', v9,
  27038. * 'suffix']);
  27039. * ```
  27040. *.
  27041. * @param values The collection of values and the strings in-between those values, beginning with
  27042. * a string prefix and ending with a string suffix.
  27043. * (e.g. `['prefix', value0, '-', value1, '-', value2, ..., value99, 'suffix']`)
  27044. * @codeGenApi
  27045. */
  27046. function ɵɵclassMapInterpolateV(values) {
  27047. const lView = getLView();
  27048. const interpolatedValue = interpolationV(lView, values);
  27049. checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
  27050. }
  27051. /*!
  27052. * @license
  27053. * Copyright Google LLC All Rights Reserved.
  27054. *
  27055. * Use of this source code is governed by an MIT-style license that can be
  27056. * found in the LICENSE file at https://angular.dev/license
  27057. */
  27058. /**
  27059. * Instruction that returns the component instance in which the current instruction is executing.
  27060. * This is a constant-time version of `nextContent` for the case where we know that we need the
  27061. * component instance specifically, rather than the context of a particular template.
  27062. *
  27063. * @codeGenApi
  27064. */
  27065. function ɵɵcomponentInstance() {
  27066. const instance = getLView()[DECLARATION_COMPONENT_VIEW][CONTEXT];
  27067. ngDevMode && assertDefined(instance, 'Expected component instance to be defined');
  27068. return instance;
  27069. }
  27070. /**
  27071. * A type representing the live collection to be reconciled with any new (incoming) collection. This
  27072. * is an adapter class that makes it possible to work with different internal data structures,
  27073. * regardless of the actual values of the incoming collection.
  27074. */
  27075. class LiveCollection {
  27076. destroy(item) {
  27077. // noop by default
  27078. }
  27079. updateValue(index, value) {
  27080. // noop by default
  27081. }
  27082. // operations below could be implemented on top of the operations defined so far, but having
  27083. // them explicitly allow clear expression of intent and potentially more performant
  27084. // implementations
  27085. swap(index1, index2) {
  27086. const startIdx = Math.min(index1, index2);
  27087. const endIdx = Math.max(index1, index2);
  27088. const endItem = this.detach(endIdx);
  27089. if (endIdx - startIdx > 1) {
  27090. const startItem = this.detach(startIdx);
  27091. this.attach(startIdx, endItem);
  27092. this.attach(endIdx, startItem);
  27093. }
  27094. else {
  27095. this.attach(startIdx, endItem);
  27096. }
  27097. }
  27098. move(prevIndex, newIdx) {
  27099. this.attach(newIdx, this.detach(prevIndex));
  27100. }
  27101. }
  27102. function valuesMatching(liveIdx, liveValue, newIdx, newValue, trackBy) {
  27103. if (liveIdx === newIdx && Object.is(liveValue, newValue)) {
  27104. // matching and no value identity to update
  27105. return 1;
  27106. }
  27107. else if (Object.is(trackBy(liveIdx, liveValue), trackBy(newIdx, newValue))) {
  27108. // matching but requires value identity update
  27109. return -1;
  27110. }
  27111. return 0;
  27112. }
  27113. function recordDuplicateKeys(keyToIdx, key, idx) {
  27114. const idxSoFar = keyToIdx.get(key);
  27115. if (idxSoFar !== undefined) {
  27116. idxSoFar.add(idx);
  27117. }
  27118. else {
  27119. keyToIdx.set(key, new Set([idx]));
  27120. }
  27121. }
  27122. /**
  27123. * The live collection reconciliation algorithm that perform various in-place operations, so it
  27124. * reflects the content of the new (incoming) collection.
  27125. *
  27126. * The reconciliation algorithm has 2 code paths:
  27127. * - "fast" path that don't require any memory allocation;
  27128. * - "slow" path that requires additional memory allocation for intermediate data structures used to
  27129. * collect additional information about the live collection.
  27130. * It might happen that the algorithm switches between the two modes in question in a single
  27131. * reconciliation path - generally it tries to stay on the "fast" path as much as possible.
  27132. *
  27133. * The overall complexity of the algorithm is O(n + m) for speed and O(n) for memory (where n is the
  27134. * length of the live collection and m is the length of the incoming collection). Given the problem
  27135. * at hand the complexity / performance constraints makes it impossible to perform the absolute
  27136. * minimum of operation to reconcile the 2 collections. The algorithm makes different tradeoffs to
  27137. * stay within reasonable performance bounds and may apply sub-optimal number of operations in
  27138. * certain situations.
  27139. *
  27140. * @param liveCollection the current, live collection;
  27141. * @param newCollection the new, incoming collection;
  27142. * @param trackByFn key generation function that determines equality between items in the life and
  27143. * incoming collection;
  27144. */
  27145. function reconcile(liveCollection, newCollection, trackByFn) {
  27146. let detachedItems = undefined;
  27147. let liveKeysInTheFuture = undefined;
  27148. let liveStartIdx = 0;
  27149. let liveEndIdx = liveCollection.length - 1;
  27150. const duplicateKeys = ngDevMode ? new Map() : undefined;
  27151. if (Array.isArray(newCollection)) {
  27152. let newEndIdx = newCollection.length - 1;
  27153. while (liveStartIdx <= liveEndIdx && liveStartIdx <= newEndIdx) {
  27154. // compare from the beginning
  27155. const liveStartValue = liveCollection.at(liveStartIdx);
  27156. const newStartValue = newCollection[liveStartIdx];
  27157. if (ngDevMode) {
  27158. recordDuplicateKeys(duplicateKeys, trackByFn(liveStartIdx, newStartValue), liveStartIdx);
  27159. }
  27160. const isStartMatching = valuesMatching(liveStartIdx, liveStartValue, liveStartIdx, newStartValue, trackByFn);
  27161. if (isStartMatching !== 0) {
  27162. if (isStartMatching < 0) {
  27163. liveCollection.updateValue(liveStartIdx, newStartValue);
  27164. }
  27165. liveStartIdx++;
  27166. continue;
  27167. }
  27168. // compare from the end
  27169. // TODO(perf): do _all_ the matching from the end
  27170. const liveEndValue = liveCollection.at(liveEndIdx);
  27171. const newEndValue = newCollection[newEndIdx];
  27172. if (ngDevMode) {
  27173. recordDuplicateKeys(duplicateKeys, trackByFn(newEndIdx, newEndValue), newEndIdx);
  27174. }
  27175. const isEndMatching = valuesMatching(liveEndIdx, liveEndValue, newEndIdx, newEndValue, trackByFn);
  27176. if (isEndMatching !== 0) {
  27177. if (isEndMatching < 0) {
  27178. liveCollection.updateValue(liveEndIdx, newEndValue);
  27179. }
  27180. liveEndIdx--;
  27181. newEndIdx--;
  27182. continue;
  27183. }
  27184. // Detect swap and moves:
  27185. const liveStartKey = trackByFn(liveStartIdx, liveStartValue);
  27186. const liveEndKey = trackByFn(liveEndIdx, liveEndValue);
  27187. const newStartKey = trackByFn(liveStartIdx, newStartValue);
  27188. if (Object.is(newStartKey, liveEndKey)) {
  27189. const newEndKey = trackByFn(newEndIdx, newEndValue);
  27190. // detect swap on both ends;
  27191. if (Object.is(newEndKey, liveStartKey)) {
  27192. liveCollection.swap(liveStartIdx, liveEndIdx);
  27193. liveCollection.updateValue(liveEndIdx, newEndValue);
  27194. newEndIdx--;
  27195. liveEndIdx--;
  27196. }
  27197. else {
  27198. // the new item is the same as the live item with the end pointer - this is a move forward
  27199. // to an earlier index;
  27200. liveCollection.move(liveEndIdx, liveStartIdx);
  27201. }
  27202. liveCollection.updateValue(liveStartIdx, newStartValue);
  27203. liveStartIdx++;
  27204. continue;
  27205. }
  27206. // Fallback to the slow path: we need to learn more about the content of the live and new
  27207. // collections.
  27208. detachedItems ??= new UniqueValueMultiKeyMap();
  27209. liveKeysInTheFuture ??= initLiveItemsInTheFuture(liveCollection, liveStartIdx, liveEndIdx, trackByFn);
  27210. // Check if I'm inserting a previously detached item: if so, attach it here
  27211. if (attachPreviouslyDetached(liveCollection, detachedItems, liveStartIdx, newStartKey)) {
  27212. liveCollection.updateValue(liveStartIdx, newStartValue);
  27213. liveStartIdx++;
  27214. liveEndIdx++;
  27215. }
  27216. else if (!liveKeysInTheFuture.has(newStartKey)) {
  27217. // Check if we seen a new item that doesn't exist in the old collection and must be INSERTED
  27218. const newItem = liveCollection.create(liveStartIdx, newCollection[liveStartIdx]);
  27219. liveCollection.attach(liveStartIdx, newItem);
  27220. liveStartIdx++;
  27221. liveEndIdx++;
  27222. }
  27223. else {
  27224. // We know that the new item exists later on in old collection but we don't know its index
  27225. // and as the consequence can't move it (don't know where to find it). Detach the old item,
  27226. // hoping that it unlocks the fast path again.
  27227. detachedItems.set(liveStartKey, liveCollection.detach(liveStartIdx));
  27228. liveEndIdx--;
  27229. }
  27230. }
  27231. // Final cleanup steps:
  27232. // - more items in the new collection => insert
  27233. while (liveStartIdx <= newEndIdx) {
  27234. createOrAttach(liveCollection, detachedItems, trackByFn, liveStartIdx, newCollection[liveStartIdx]);
  27235. liveStartIdx++;
  27236. }
  27237. }
  27238. else if (newCollection != null) {
  27239. // iterable - immediately fallback to the slow path
  27240. const newCollectionIterator = newCollection[Symbol.iterator]();
  27241. let newIterationResult = newCollectionIterator.next();
  27242. while (!newIterationResult.done && liveStartIdx <= liveEndIdx) {
  27243. const liveValue = liveCollection.at(liveStartIdx);
  27244. const newValue = newIterationResult.value;
  27245. if (ngDevMode) {
  27246. recordDuplicateKeys(duplicateKeys, trackByFn(liveStartIdx, newValue), liveStartIdx);
  27247. }
  27248. const isStartMatching = valuesMatching(liveStartIdx, liveValue, liveStartIdx, newValue, trackByFn);
  27249. if (isStartMatching !== 0) {
  27250. // found a match - move on, but update value
  27251. if (isStartMatching < 0) {
  27252. liveCollection.updateValue(liveStartIdx, newValue);
  27253. }
  27254. liveStartIdx++;
  27255. newIterationResult = newCollectionIterator.next();
  27256. }
  27257. else {
  27258. detachedItems ??= new UniqueValueMultiKeyMap();
  27259. liveKeysInTheFuture ??= initLiveItemsInTheFuture(liveCollection, liveStartIdx, liveEndIdx, trackByFn);
  27260. // Check if I'm inserting a previously detached item: if so, attach it here
  27261. const newKey = trackByFn(liveStartIdx, newValue);
  27262. if (attachPreviouslyDetached(liveCollection, detachedItems, liveStartIdx, newKey)) {
  27263. liveCollection.updateValue(liveStartIdx, newValue);
  27264. liveStartIdx++;
  27265. liveEndIdx++;
  27266. newIterationResult = newCollectionIterator.next();
  27267. }
  27268. else if (!liveKeysInTheFuture.has(newKey)) {
  27269. liveCollection.attach(liveStartIdx, liveCollection.create(liveStartIdx, newValue));
  27270. liveStartIdx++;
  27271. liveEndIdx++;
  27272. newIterationResult = newCollectionIterator.next();
  27273. }
  27274. else {
  27275. // it is a move forward - detach the current item without advancing in collections
  27276. const liveKey = trackByFn(liveStartIdx, liveValue);
  27277. detachedItems.set(liveKey, liveCollection.detach(liveStartIdx));
  27278. liveEndIdx--;
  27279. }
  27280. }
  27281. }
  27282. // this is a new item as we run out of the items in the old collection - create or attach a
  27283. // previously detached one
  27284. while (!newIterationResult.done) {
  27285. createOrAttach(liveCollection, detachedItems, trackByFn, liveCollection.length, newIterationResult.value);
  27286. newIterationResult = newCollectionIterator.next();
  27287. }
  27288. }
  27289. // Cleanups common to the array and iterable:
  27290. // - more items in the live collection => delete starting from the end;
  27291. while (liveStartIdx <= liveEndIdx) {
  27292. liveCollection.destroy(liveCollection.detach(liveEndIdx--));
  27293. }
  27294. // - destroy items that were detached but never attached again.
  27295. detachedItems?.forEach((item) => {
  27296. liveCollection.destroy(item);
  27297. });
  27298. // report duplicate keys (dev mode only)
  27299. if (ngDevMode) {
  27300. let duplicatedKeysMsg = [];
  27301. for (const [key, idxSet] of duplicateKeys) {
  27302. if (idxSet.size > 1) {
  27303. const idx = [...idxSet].sort((a, b) => a - b);
  27304. for (let i = 1; i < idx.length; i++) {
  27305. duplicatedKeysMsg.push(`key "${stringifyForError(key)}" at index "${idx[i - 1]}" and "${idx[i]}"`);
  27306. }
  27307. }
  27308. }
  27309. if (duplicatedKeysMsg.length > 0) {
  27310. const message = formatRuntimeError(-955 /* RuntimeErrorCode.LOOP_TRACK_DUPLICATE_KEYS */, 'The provided track expression resulted in duplicated keys for a given collection. ' +
  27311. 'Adjust the tracking expression such that it uniquely identifies all the items in the collection. ' +
  27312. 'Duplicated keys were: \n' +
  27313. duplicatedKeysMsg.join(', \n') +
  27314. '.');
  27315. console.warn(message);
  27316. }
  27317. }
  27318. }
  27319. function attachPreviouslyDetached(prevCollection, detachedItems, index, key) {
  27320. if (detachedItems !== undefined && detachedItems.has(key)) {
  27321. prevCollection.attach(index, detachedItems.get(key));
  27322. detachedItems.delete(key);
  27323. return true;
  27324. }
  27325. return false;
  27326. }
  27327. function createOrAttach(liveCollection, detachedItems, trackByFn, index, value) {
  27328. if (!attachPreviouslyDetached(liveCollection, detachedItems, index, trackByFn(index, value))) {
  27329. const newItem = liveCollection.create(index, value);
  27330. liveCollection.attach(index, newItem);
  27331. }
  27332. else {
  27333. liveCollection.updateValue(index, value);
  27334. }
  27335. }
  27336. function initLiveItemsInTheFuture(liveCollection, start, end, trackByFn) {
  27337. const keys = new Set();
  27338. for (let i = start; i <= end; i++) {
  27339. keys.add(trackByFn(i, liveCollection.at(i)));
  27340. }
  27341. return keys;
  27342. }
  27343. /**
  27344. * A specific, partial implementation of the Map interface with the following characteristics:
  27345. * - allows multiple values for a given key;
  27346. * - maintain FIFO order for multiple values corresponding to a given key;
  27347. * - assumes that all values are unique.
  27348. *
  27349. * The implementation aims at having the minimal overhead for cases where keys are _not_ duplicated
  27350. * (the most common case in the list reconciliation algorithm). To achieve this, the first value for
  27351. * a given key is stored in a regular map. Then, when more values are set for a given key, we
  27352. * maintain a form of linked list in a separate map. To maintain this linked list we assume that all
  27353. * values (in the entire collection) are unique.
  27354. */
  27355. class UniqueValueMultiKeyMap {
  27356. // A map from a key to the first value corresponding to this key.
  27357. kvMap = new Map();
  27358. // A map that acts as a linked list of values - each value maps to the next value in this "linked
  27359. // list" (this only works if values are unique). Allocated lazily to avoid memory consumption when
  27360. // there are no duplicated values.
  27361. _vMap = undefined;
  27362. has(key) {
  27363. return this.kvMap.has(key);
  27364. }
  27365. delete(key) {
  27366. if (!this.has(key))
  27367. return false;
  27368. const value = this.kvMap.get(key);
  27369. if (this._vMap !== undefined && this._vMap.has(value)) {
  27370. this.kvMap.set(key, this._vMap.get(value));
  27371. this._vMap.delete(value);
  27372. }
  27373. else {
  27374. this.kvMap.delete(key);
  27375. }
  27376. return true;
  27377. }
  27378. get(key) {
  27379. return this.kvMap.get(key);
  27380. }
  27381. set(key, value) {
  27382. if (this.kvMap.has(key)) {
  27383. let prevValue = this.kvMap.get(key);
  27384. // Note: we don't use `assertNotSame`, because the value needs to be stringified even if
  27385. // there is no error which can freeze the browser for large values (see #58509).
  27386. if (ngDevMode && prevValue === value) {
  27387. throw new Error(`Detected a duplicated value ${value} for the key ${key}`);
  27388. }
  27389. if (this._vMap === undefined) {
  27390. this._vMap = new Map();
  27391. }
  27392. const vMap = this._vMap;
  27393. while (vMap.has(prevValue)) {
  27394. prevValue = vMap.get(prevValue);
  27395. }
  27396. vMap.set(prevValue, value);
  27397. }
  27398. else {
  27399. this.kvMap.set(key, value);
  27400. }
  27401. }
  27402. forEach(cb) {
  27403. for (let [key, value] of this.kvMap) {
  27404. cb(value, key);
  27405. if (this._vMap !== undefined) {
  27406. const vMap = this._vMap;
  27407. while (vMap.has(value)) {
  27408. value = vMap.get(value);
  27409. cb(value, key);
  27410. }
  27411. }
  27412. }
  27413. }
  27414. }
  27415. /**
  27416. * The conditional instruction represents the basic building block on the runtime side to support
  27417. * built-in "if" and "switch". On the high level this instruction is responsible for adding and
  27418. * removing views selected by a conditional expression.
  27419. *
  27420. * @param matchingTemplateIndex Index of a template TNode representing a conditional view to be
  27421. * inserted; -1 represents a special case when there is no view to insert.
  27422. * @param contextValue Value that should be exposed as the context of the conditional.
  27423. * @codeGenApi
  27424. */
  27425. function ɵɵconditional(matchingTemplateIndex, contextValue) {
  27426. performanceMarkFeature('NgControlFlow');
  27427. const hostLView = getLView();
  27428. const bindingIndex = nextBindingIndex();
  27429. const prevMatchingTemplateIndex = hostLView[bindingIndex] !== NO_CHANGE ? hostLView[bindingIndex] : -1;
  27430. const prevContainer = prevMatchingTemplateIndex !== -1
  27431. ? getLContainer(hostLView, HEADER_OFFSET + prevMatchingTemplateIndex)
  27432. : undefined;
  27433. const viewInContainerIdx = 0;
  27434. if (bindingUpdated(hostLView, bindingIndex, matchingTemplateIndex)) {
  27435. const prevConsumer = setActiveConsumer$1(null);
  27436. try {
  27437. // The index of the view to show changed - remove the previously displayed one
  27438. // (it is a noop if there are no active views in a container).
  27439. if (prevContainer !== undefined) {
  27440. removeLViewFromLContainer(prevContainer, viewInContainerIdx);
  27441. }
  27442. // Index -1 is a special case where none of the conditions evaluates to
  27443. // a truthy value and as the consequence we've got no view to show.
  27444. if (matchingTemplateIndex !== -1) {
  27445. const nextLContainerIndex = HEADER_OFFSET + matchingTemplateIndex;
  27446. const nextContainer = getLContainer(hostLView, nextLContainerIndex);
  27447. const templateTNode = getExistingTNode(hostLView[TVIEW], nextLContainerIndex);
  27448. const dehydratedView = findMatchingDehydratedView(nextContainer, templateTNode.tView.ssrId);
  27449. const embeddedLView = createAndRenderEmbeddedLView(hostLView, templateTNode, contextValue, {
  27450. dehydratedView,
  27451. });
  27452. addLViewToLContainer(nextContainer, embeddedLView, viewInContainerIdx, shouldAddViewToDom(templateTNode, dehydratedView));
  27453. }
  27454. }
  27455. finally {
  27456. setActiveConsumer$1(prevConsumer);
  27457. }
  27458. }
  27459. else if (prevContainer !== undefined) {
  27460. // We might keep displaying the same template but the actual value of the expression could have
  27461. // changed - re-bind in context.
  27462. const lView = getLViewFromLContainer(prevContainer, viewInContainerIdx);
  27463. if (lView !== undefined) {
  27464. lView[CONTEXT] = contextValue;
  27465. }
  27466. }
  27467. }
  27468. class RepeaterContext {
  27469. lContainer;
  27470. $implicit;
  27471. $index;
  27472. constructor(lContainer, $implicit, $index) {
  27473. this.lContainer = lContainer;
  27474. this.$implicit = $implicit;
  27475. this.$index = $index;
  27476. }
  27477. get $count() {
  27478. return this.lContainer.length - CONTAINER_HEADER_OFFSET;
  27479. }
  27480. }
  27481. /**
  27482. * A built-in trackBy function used for situations where users specified collection index as a
  27483. * tracking expression. Having this function body in the runtime avoids unnecessary code generation.
  27484. *
  27485. * @param index
  27486. * @returns
  27487. */
  27488. function ɵɵrepeaterTrackByIndex(index) {
  27489. return index;
  27490. }
  27491. /**
  27492. * A built-in trackBy function used for situations where users specified collection item reference
  27493. * as a tracking expression. Having this function body in the runtime avoids unnecessary code
  27494. * generation.
  27495. *
  27496. * @param index
  27497. * @returns
  27498. */
  27499. function ɵɵrepeaterTrackByIdentity(_, value) {
  27500. return value;
  27501. }
  27502. class RepeaterMetadata {
  27503. hasEmptyBlock;
  27504. trackByFn;
  27505. liveCollection;
  27506. constructor(hasEmptyBlock, trackByFn, liveCollection) {
  27507. this.hasEmptyBlock = hasEmptyBlock;
  27508. this.trackByFn = trackByFn;
  27509. this.liveCollection = liveCollection;
  27510. }
  27511. }
  27512. /**
  27513. * The repeaterCreate instruction runs in the creation part of the template pass and initializes
  27514. * internal data structures required by the update pass of the built-in repeater logic. Repeater
  27515. * metadata are allocated in the data part of LView with the following layout:
  27516. * - LView[HEADER_OFFSET + index] - metadata
  27517. * - LView[HEADER_OFFSET + index + 1] - reference to a template function rendering an item
  27518. * - LView[HEADER_OFFSET + index + 2] - optional reference to a template function rendering an empty
  27519. * block
  27520. *
  27521. * @param index Index at which to store the metadata of the repeater.
  27522. * @param templateFn Reference to the template of the main repeater block.
  27523. * @param decls The number of nodes, local refs, and pipes for the main block.
  27524. * @param vars The number of bindings for the main block.
  27525. * @param tagName The name of the container element, if applicable
  27526. * @param attrsIndex Index of template attributes in the `consts` array.
  27527. * @param trackByFn Reference to the tracking function.
  27528. * @param trackByUsesComponentInstance Whether the tracking function has any references to the
  27529. * component instance. If it doesn't, we can avoid rebinding it.
  27530. * @param emptyTemplateFn Reference to the template function of the empty block.
  27531. * @param emptyDecls The number of nodes, local refs, and pipes for the empty block.
  27532. * @param emptyVars The number of bindings for the empty block.
  27533. * @param emptyTagName The name of the empty block container element, if applicable
  27534. * @param emptyAttrsIndex Index of the empty block template attributes in the `consts` array.
  27535. *
  27536. * @codeGenApi
  27537. */
  27538. function ɵɵrepeaterCreate(index, templateFn, decls, vars, tagName, attrsIndex, trackByFn, trackByUsesComponentInstance, emptyTemplateFn, emptyDecls, emptyVars, emptyTagName, emptyAttrsIndex) {
  27539. performanceMarkFeature('NgControlFlow');
  27540. ngDevMode &&
  27541. assertFunction(trackByFn, `A track expression must be a function, was ${typeof trackByFn} instead.`);
  27542. const lView = getLView();
  27543. const tView = getTView();
  27544. const hasEmptyBlock = emptyTemplateFn !== undefined;
  27545. const hostLView = getLView();
  27546. const boundTrackBy = trackByUsesComponentInstance
  27547. ? // We only want to bind when necessary, because it produces a
  27548. // new function. For pure functions it's not necessary.
  27549. trackByFn.bind(hostLView[DECLARATION_COMPONENT_VIEW][CONTEXT])
  27550. : trackByFn;
  27551. const metadata = new RepeaterMetadata(hasEmptyBlock, boundTrackBy);
  27552. hostLView[HEADER_OFFSET + index] = metadata;
  27553. declareTemplate(lView, tView, index + 1, templateFn, decls, vars, tagName, getConstant(tView.consts, attrsIndex));
  27554. if (hasEmptyBlock) {
  27555. ngDevMode &&
  27556. assertDefined(emptyDecls, 'Missing number of declarations for the empty repeater block.');
  27557. ngDevMode &&
  27558. assertDefined(emptyVars, 'Missing number of bindings for the empty repeater block.');
  27559. declareTemplate(lView, tView, index + 2, emptyTemplateFn, emptyDecls, emptyVars, emptyTagName, getConstant(tView.consts, emptyAttrsIndex));
  27560. }
  27561. }
  27562. function isViewExpensiveToRecreate(lView) {
  27563. // assumption: anything more than a text node with a binding is considered "expensive"
  27564. return lView.length - HEADER_OFFSET > 2;
  27565. }
  27566. class OperationsCounter {
  27567. created = 0;
  27568. destroyed = 0;
  27569. reset() {
  27570. this.created = 0;
  27571. this.destroyed = 0;
  27572. }
  27573. recordCreate() {
  27574. this.created++;
  27575. }
  27576. recordDestroy() {
  27577. this.destroyed++;
  27578. }
  27579. /**
  27580. * A method indicating if the entire collection was re-created as part of the reconciliation pass.
  27581. * Used to warn developers about the usage of a tracking function that might result in excessive
  27582. * amount of view creation / destroy operations.
  27583. *
  27584. * @returns boolean value indicating if a live collection was re-created
  27585. */
  27586. wasReCreated(collectionLen) {
  27587. return collectionLen > 0 && this.created === this.destroyed && this.created === collectionLen;
  27588. }
  27589. }
  27590. class LiveCollectionLContainerImpl extends LiveCollection {
  27591. lContainer;
  27592. hostLView;
  27593. templateTNode;
  27594. operationsCounter = ngDevMode ? new OperationsCounter() : undefined;
  27595. /**
  27596. Property indicating if indexes in the repeater context need to be updated following the live
  27597. collection changes. Index updates are necessary if and only if views are inserted / removed in
  27598. the middle of LContainer. Adds and removals at the end don't require index updates.
  27599. */
  27600. needsIndexUpdate = false;
  27601. constructor(lContainer, hostLView, templateTNode) {
  27602. super();
  27603. this.lContainer = lContainer;
  27604. this.hostLView = hostLView;
  27605. this.templateTNode = templateTNode;
  27606. }
  27607. get length() {
  27608. return this.lContainer.length - CONTAINER_HEADER_OFFSET;
  27609. }
  27610. at(index) {
  27611. return this.getLView(index)[CONTEXT].$implicit;
  27612. }
  27613. attach(index, lView) {
  27614. const dehydratedView = lView[HYDRATION];
  27615. this.needsIndexUpdate ||= index !== this.length;
  27616. addLViewToLContainer(this.lContainer, lView, index, shouldAddViewToDom(this.templateTNode, dehydratedView));
  27617. }
  27618. detach(index) {
  27619. this.needsIndexUpdate ||= index !== this.length - 1;
  27620. return detachExistingView(this.lContainer, index);
  27621. }
  27622. create(index, value) {
  27623. const dehydratedView = findMatchingDehydratedView(this.lContainer, this.templateTNode.tView.ssrId);
  27624. const embeddedLView = createAndRenderEmbeddedLView(this.hostLView, this.templateTNode, new RepeaterContext(this.lContainer, value, index), { dehydratedView });
  27625. this.operationsCounter?.recordCreate();
  27626. return embeddedLView;
  27627. }
  27628. destroy(lView) {
  27629. destroyLView(lView[TVIEW], lView);
  27630. this.operationsCounter?.recordDestroy();
  27631. }
  27632. updateValue(index, value) {
  27633. this.getLView(index)[CONTEXT].$implicit = value;
  27634. }
  27635. reset() {
  27636. this.needsIndexUpdate = false;
  27637. this.operationsCounter?.reset();
  27638. }
  27639. updateIndexes() {
  27640. if (this.needsIndexUpdate) {
  27641. for (let i = 0; i < this.length; i++) {
  27642. this.getLView(i)[CONTEXT].$index = i;
  27643. }
  27644. }
  27645. }
  27646. getLView(index) {
  27647. return getExistingLViewFromLContainer(this.lContainer, index);
  27648. }
  27649. }
  27650. /**
  27651. * The repeater instruction does update-time diffing of a provided collection (against the
  27652. * collection seen previously) and maps changes in the collection to views structure (by adding,
  27653. * removing or moving views as needed).
  27654. * @param collection - the collection instance to be checked for changes
  27655. * @codeGenApi
  27656. */
  27657. function ɵɵrepeater(collection) {
  27658. const prevConsumer = setActiveConsumer$1(null);
  27659. const metadataSlotIdx = getSelectedIndex();
  27660. try {
  27661. const hostLView = getLView();
  27662. const hostTView = hostLView[TVIEW];
  27663. const metadata = hostLView[metadataSlotIdx];
  27664. const containerIndex = metadataSlotIdx + 1;
  27665. const lContainer = getLContainer(hostLView, containerIndex);
  27666. if (metadata.liveCollection === undefined) {
  27667. const itemTemplateTNode = getExistingTNode(hostTView, containerIndex);
  27668. metadata.liveCollection = new LiveCollectionLContainerImpl(lContainer, hostLView, itemTemplateTNode);
  27669. }
  27670. else {
  27671. metadata.liveCollection.reset();
  27672. }
  27673. const liveCollection = metadata.liveCollection;
  27674. reconcile(liveCollection, collection, metadata.trackByFn);
  27675. // Warn developers about situations where the entire collection was re-created as part of the
  27676. // reconciliation pass. Note that this warning might be "overreacting" and report cases where
  27677. // the collection re-creation is the intended behavior. Still, the assumption is that most of
  27678. // the time it is undesired.
  27679. if (ngDevMode &&
  27680. metadata.trackByFn === ɵɵrepeaterTrackByIdentity &&
  27681. liveCollection.operationsCounter?.wasReCreated(liveCollection.length) &&
  27682. isViewExpensiveToRecreate(getExistingLViewFromLContainer(lContainer, 0))) {
  27683. 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}. ` +
  27684. 'This is an expensive operation requiring destruction and subsequent creation of DOM nodes, directives, components etc. ' +
  27685. 'Please review the "track expression" and make sure that it uniquely identifies items in a collection.');
  27686. console.warn(message);
  27687. }
  27688. // moves in the container might caused context's index to get out of order, re-adjust if needed
  27689. liveCollection.updateIndexes();
  27690. // handle empty blocks
  27691. if (metadata.hasEmptyBlock) {
  27692. const bindingIndex = nextBindingIndex();
  27693. const isCollectionEmpty = liveCollection.length === 0;
  27694. if (bindingUpdated(hostLView, bindingIndex, isCollectionEmpty)) {
  27695. const emptyTemplateIndex = metadataSlotIdx + 2;
  27696. const lContainerForEmpty = getLContainer(hostLView, emptyTemplateIndex);
  27697. if (isCollectionEmpty) {
  27698. const emptyTemplateTNode = getExistingTNode(hostTView, emptyTemplateIndex);
  27699. const dehydratedView = findMatchingDehydratedView(lContainerForEmpty, emptyTemplateTNode.tView.ssrId);
  27700. const embeddedLView = createAndRenderEmbeddedLView(hostLView, emptyTemplateTNode, undefined, { dehydratedView });
  27701. addLViewToLContainer(lContainerForEmpty, embeddedLView, 0, shouldAddViewToDom(emptyTemplateTNode, dehydratedView));
  27702. }
  27703. else {
  27704. removeLViewFromLContainer(lContainerForEmpty, 0);
  27705. }
  27706. }
  27707. }
  27708. }
  27709. finally {
  27710. setActiveConsumer$1(prevConsumer);
  27711. }
  27712. }
  27713. function getLContainer(lView, index) {
  27714. const lContainer = lView[index];
  27715. ngDevMode && assertLContainer(lContainer);
  27716. return lContainer;
  27717. }
  27718. function detachExistingView(lContainer, index) {
  27719. const existingLView = detachView(lContainer, index);
  27720. ngDevMode && assertLView(existingLView);
  27721. return existingLView;
  27722. }
  27723. function getExistingLViewFromLContainer(lContainer, index) {
  27724. const existingLView = getLViewFromLContainer(lContainer, index);
  27725. ngDevMode && assertLView(existingLView);
  27726. return existingLView;
  27727. }
  27728. function getExistingTNode(tView, index) {
  27729. const tNode = getTNode(tView, index);
  27730. ngDevMode && assertTNode(tNode);
  27731. return tNode;
  27732. }
  27733. /**
  27734. * Create DOM element. The instruction must later be followed by `elementEnd()` call.
  27735. *
  27736. * @param index Index of the element in the LView array
  27737. * @param name Name of the DOM Node
  27738. * @param attrsIndex Index of the element's attributes in the `consts` array.
  27739. * @param localRefsIndex Index of the element's local references in the `consts` array.
  27740. * @returns This function returns itself so that it may be chained.
  27741. *
  27742. * Attributes and localRefs are passed as an array of strings where elements with an even index
  27743. * hold an attribute name and elements with an odd index hold an attribute value, ex.:
  27744. * ['id', 'warning5', 'class', 'alert']
  27745. *
  27746. * @codeGenApi
  27747. */
  27748. function ɵɵelementStart(index, name, attrsIndex, localRefsIndex) {
  27749. const lView = getLView();
  27750. const tView = getTView();
  27751. const adjustedIndex = HEADER_OFFSET + index;
  27752. ngDevMode &&
  27753. assertEqual(getBindingIndex(), tView.bindingStartIndex, 'elements should be created before any bindings');
  27754. ngDevMode && assertIndexInRange(lView, adjustedIndex);
  27755. const renderer = lView[RENDERER];
  27756. const tNode = tView.firstCreatePass
  27757. ? elementStartFirstCreatePass(adjustedIndex, tView, lView, name, findDirectiveDefMatches, getBindingsEnabled(), attrsIndex, localRefsIndex)
  27758. : tView.data[adjustedIndex];
  27759. const native = _locateOrCreateElementNode(tView, lView, tNode, renderer, name, index);
  27760. lView[adjustedIndex] = native;
  27761. const hasDirectives = isDirectiveHost(tNode);
  27762. if (ngDevMode && tView.firstCreatePass) {
  27763. validateElementIsKnown(native, lView, tNode.value, tView.schemas, hasDirectives);
  27764. }
  27765. setCurrentTNode(tNode, true);
  27766. setupStaticAttributes(renderer, native, tNode);
  27767. if (!isDetachedByI18n(tNode) && wasLastNodeCreated()) {
  27768. // In the i18n case, the translation may have removed this element, so only add it if it is not
  27769. // detached. See `TNodeType.Placeholder` and `LFrame.inI18n` for more context.
  27770. appendChild(tView, lView, native, tNode);
  27771. }
  27772. // any immediate children of a component or template container must be pre-emptively
  27773. // monkey-patched with the component view data so that the element can be inspected
  27774. // later on using any element discovery utility methods (see `element_discovery.ts`)
  27775. if (getElementDepthCount() === 0 || hasDirectives) {
  27776. attachPatchData(native, lView);
  27777. }
  27778. increaseElementDepthCount();
  27779. if (hasDirectives) {
  27780. createDirectivesInstances(tView, lView, tNode);
  27781. executeContentQueries(tView, tNode, lView);
  27782. }
  27783. if (localRefsIndex !== null) {
  27784. saveResolvedLocalsInData(lView, tNode);
  27785. }
  27786. return ɵɵelementStart;
  27787. }
  27788. /**
  27789. * Mark the end of the element.
  27790. * @returns This function returns itself so that it may be chained.
  27791. *
  27792. * @codeGenApi
  27793. */
  27794. function ɵɵelementEnd() {
  27795. let currentTNode = getCurrentTNode();
  27796. ngDevMode && assertDefined(currentTNode, 'No parent node to close.');
  27797. if (isCurrentTNodeParent()) {
  27798. setCurrentTNodeAsNotParent();
  27799. }
  27800. else {
  27801. ngDevMode && assertHasParent(getCurrentTNode());
  27802. currentTNode = currentTNode.parent;
  27803. setCurrentTNode(currentTNode, false);
  27804. }
  27805. const tNode = currentTNode;
  27806. ngDevMode && assertTNodeType(tNode, 3 /* TNodeType.AnyRNode */);
  27807. if (isSkipHydrationRootTNode(tNode)) {
  27808. leaveSkipHydrationBlock();
  27809. }
  27810. decreaseElementDepthCount();
  27811. const tView = getTView();
  27812. if (tView.firstCreatePass) {
  27813. elementEndFirstCreatePass(tView, tNode);
  27814. }
  27815. if (tNode.classesWithoutHost != null && hasClassInput(tNode)) {
  27816. setDirectiveInputsWhichShadowsStyling(tView, tNode, getLView(), tNode.classesWithoutHost, true);
  27817. }
  27818. if (tNode.stylesWithoutHost != null && hasStyleInput(tNode)) {
  27819. setDirectiveInputsWhichShadowsStyling(tView, tNode, getLView(), tNode.stylesWithoutHost, false);
  27820. }
  27821. return ɵɵelementEnd;
  27822. }
  27823. /**
  27824. * Creates an empty element using {@link elementStart} and {@link elementEnd}
  27825. *
  27826. * @param index Index of the element in the data array
  27827. * @param name Name of the DOM Node
  27828. * @param attrsIndex Index of the element's attributes in the `consts` array.
  27829. * @param localRefsIndex Index of the element's local references in the `consts` array.
  27830. * @returns This function returns itself so that it may be chained.
  27831. *
  27832. * @codeGenApi
  27833. */
  27834. function ɵɵelement(index, name, attrsIndex, localRefsIndex) {
  27835. ɵɵelementStart(index, name, attrsIndex, localRefsIndex);
  27836. ɵɵelementEnd();
  27837. return ɵɵelement;
  27838. }
  27839. let _locateOrCreateElementNode = (tView, lView, tNode, renderer, name, index) => {
  27840. lastNodeWasCreated(true);
  27841. return createElementNode(renderer, name, getNamespace());
  27842. };
  27843. /**
  27844. * Enables hydration code path (to lookup existing elements in DOM)
  27845. * in addition to the regular creation mode of element nodes.
  27846. */
  27847. function locateOrCreateElementNodeImpl(tView, lView, tNode, renderer, name, index) {
  27848. const hydrationInfo = lView[HYDRATION];
  27849. const isNodeCreationMode = !hydrationInfo ||
  27850. isInSkipHydrationBlock$1() ||
  27851. isDetachedByI18n(tNode) ||
  27852. isDisconnectedNode$1(hydrationInfo, index);
  27853. lastNodeWasCreated(isNodeCreationMode);
  27854. // Regular creation mode.
  27855. if (isNodeCreationMode) {
  27856. return createElementNode(renderer, name, getNamespace());
  27857. }
  27858. // Hydration mode, looking up an existing element in DOM.
  27859. const native = locateNextRNode(hydrationInfo, tView, lView, tNode);
  27860. ngDevMode && validateMatchingNode(native, Node.ELEMENT_NODE, name, lView, tNode);
  27861. ngDevMode && markRNodeAsClaimedByHydration(native);
  27862. // This element might also be an anchor of a view container.
  27863. if (getSerializedContainerViews(hydrationInfo, index)) {
  27864. // Important note: this element acts as an anchor, but it's **not** a part
  27865. // of the embedded view, so we start the segment **after** this element, taking
  27866. // a reference to the next sibling. For example, the following template:
  27867. // `<div #vcrTarget>` is represented in the DOM as `<div></div>...<!--container-->`,
  27868. // so while processing a `<div>` instruction, point to the next sibling as a
  27869. // start of a segment.
  27870. ngDevMode && validateNodeExists(native.nextSibling, lView, tNode);
  27871. setSegmentHead(hydrationInfo, index, native.nextSibling);
  27872. }
  27873. // Checks if the skip hydration attribute is present during hydration so we know to
  27874. // skip attempting to hydrate this block. We check both TNode and RElement for an
  27875. // attribute: the RElement case is needed for i18n cases, when we add it to host
  27876. // elements during the annotation phase (after all internal data structures are setup).
  27877. if (hydrationInfo &&
  27878. (hasSkipHydrationAttrOnTNode(tNode) || hasSkipHydrationAttrOnRElement(native))) {
  27879. if (isComponentHost(tNode)) {
  27880. enterSkipHydrationBlock(tNode);
  27881. // Since this isn't hydratable, we need to empty the node
  27882. // so there's no duplicate content after render
  27883. clearElementContents(native);
  27884. ngDevMode && markRNodeAsSkippedByHydration(native);
  27885. }
  27886. else if (ngDevMode) {
  27887. // If this is not a component host, throw an error.
  27888. // Hydration can be skipped on per-component basis only.
  27889. throw invalidSkipHydrationHost(native);
  27890. }
  27891. }
  27892. return native;
  27893. }
  27894. function enableLocateOrCreateElementNodeImpl() {
  27895. _locateOrCreateElementNode = locateOrCreateElementNodeImpl;
  27896. }
  27897. function elementContainerStartFirstCreatePass(index, tView, lView, attrsIndex, localRefsIndex) {
  27898. ngDevMode && ngDevMode.firstCreatePass++;
  27899. const tViewConsts = tView.consts;
  27900. const attrs = getConstant(tViewConsts, attrsIndex);
  27901. const tNode = getOrCreateTNode(tView, index, 8 /* TNodeType.ElementContainer */, 'ng-container', attrs);
  27902. // While ng-container doesn't necessarily support styling, we use the style context to identify
  27903. // and execute directives on the ng-container.
  27904. if (attrs !== null) {
  27905. computeStaticStyling(tNode, attrs, true);
  27906. }
  27907. const localRefs = getConstant(tViewConsts, localRefsIndex);
  27908. if (getBindingsEnabled()) {
  27909. resolveDirectives(tView, lView, tNode, localRefs, findDirectiveDefMatches);
  27910. }
  27911. // Merge the template attrs last so that they have the highest priority.
  27912. tNode.mergedAttrs = mergeHostAttrs(tNode.mergedAttrs, tNode.attrs);
  27913. if (tView.queries !== null) {
  27914. tView.queries.elementStart(tView, tNode);
  27915. }
  27916. return tNode;
  27917. }
  27918. /**
  27919. * Creates a logical container for other nodes (<ng-container>) backed by a comment node in the DOM.
  27920. * The instruction must later be followed by `elementContainerEnd()` call.
  27921. *
  27922. * @param index Index of the element in the LView array
  27923. * @param attrsIndex Index of the container attributes in the `consts` array.
  27924. * @param localRefsIndex Index of the container's local references in the `consts` array.
  27925. * @returns This function returns itself so that it may be chained.
  27926. *
  27927. * Even if this instruction accepts a set of attributes no actual attribute values are propagated to
  27928. * the DOM (as a comment node can't have attributes). Attributes are here only for directive
  27929. * matching purposes and setting initial inputs of directives.
  27930. *
  27931. * @codeGenApi
  27932. */
  27933. function ɵɵelementContainerStart(index, attrsIndex, localRefsIndex) {
  27934. const lView = getLView();
  27935. const tView = getTView();
  27936. const adjustedIndex = index + HEADER_OFFSET;
  27937. ngDevMode && assertIndexInRange(lView, adjustedIndex);
  27938. ngDevMode &&
  27939. assertEqual(getBindingIndex(), tView.bindingStartIndex, 'element containers should be created before any bindings');
  27940. const tNode = tView.firstCreatePass
  27941. ? elementContainerStartFirstCreatePass(adjustedIndex, tView, lView, attrsIndex, localRefsIndex)
  27942. : tView.data[adjustedIndex];
  27943. setCurrentTNode(tNode, true);
  27944. const comment = _locateOrCreateElementContainerNode(tView, lView, tNode, index);
  27945. lView[adjustedIndex] = comment;
  27946. if (wasLastNodeCreated()) {
  27947. appendChild(tView, lView, comment, tNode);
  27948. }
  27949. attachPatchData(comment, lView);
  27950. if (isDirectiveHost(tNode)) {
  27951. createDirectivesInstances(tView, lView, tNode);
  27952. executeContentQueries(tView, tNode, lView);
  27953. }
  27954. if (localRefsIndex != null) {
  27955. saveResolvedLocalsInData(lView, tNode);
  27956. }
  27957. return ɵɵelementContainerStart;
  27958. }
  27959. /**
  27960. * Mark the end of the <ng-container>.
  27961. * @returns This function returns itself so that it may be chained.
  27962. *
  27963. * @codeGenApi
  27964. */
  27965. function ɵɵelementContainerEnd() {
  27966. let currentTNode = getCurrentTNode();
  27967. const tView = getTView();
  27968. if (isCurrentTNodeParent()) {
  27969. setCurrentTNodeAsNotParent();
  27970. }
  27971. else {
  27972. ngDevMode && assertHasParent(currentTNode);
  27973. currentTNode = currentTNode.parent;
  27974. setCurrentTNode(currentTNode, false);
  27975. }
  27976. ngDevMode && assertTNodeType(currentTNode, 8 /* TNodeType.ElementContainer */);
  27977. if (tView.firstCreatePass) {
  27978. registerPostOrderHooks(tView, currentTNode);
  27979. if (isContentQueryHost(currentTNode)) {
  27980. tView.queries.elementEnd(currentTNode);
  27981. }
  27982. }
  27983. return ɵɵelementContainerEnd;
  27984. }
  27985. /**
  27986. * Creates an empty logical container using {@link elementContainerStart}
  27987. * and {@link elementContainerEnd}
  27988. *
  27989. * @param index Index of the element in the LView array
  27990. * @param attrsIndex Index of the container attributes in the `consts` array.
  27991. * @param localRefsIndex Index of the container's local references in the `consts` array.
  27992. * @returns This function returns itself so that it may be chained.
  27993. *
  27994. * @codeGenApi
  27995. */
  27996. function ɵɵelementContainer(index, attrsIndex, localRefsIndex) {
  27997. ɵɵelementContainerStart(index, attrsIndex, localRefsIndex);
  27998. ɵɵelementContainerEnd();
  27999. return ɵɵelementContainer;
  28000. }
  28001. let _locateOrCreateElementContainerNode = (tView, lView, tNode, index) => {
  28002. lastNodeWasCreated(true);
  28003. return createCommentNode(lView[RENDERER], ngDevMode ? 'ng-container' : '');
  28004. };
  28005. /**
  28006. * Enables hydration code path (to lookup existing elements in DOM)
  28007. * in addition to the regular creation mode of comment nodes that
  28008. * represent <ng-container>'s anchor.
  28009. */
  28010. function locateOrCreateElementContainerNode(tView, lView, tNode, index) {
  28011. let comment;
  28012. const hydrationInfo = lView[HYDRATION];
  28013. const isNodeCreationMode = !hydrationInfo ||
  28014. isInSkipHydrationBlock$1() ||
  28015. isDisconnectedNode$1(hydrationInfo, index) ||
  28016. isDetachedByI18n(tNode);
  28017. lastNodeWasCreated(isNodeCreationMode);
  28018. // Regular creation mode.
  28019. if (isNodeCreationMode) {
  28020. return createCommentNode(lView[RENDERER], ngDevMode ? 'ng-container' : '');
  28021. }
  28022. // Hydration mode, looking up existing elements in DOM.
  28023. const currentRNode = locateNextRNode(hydrationInfo, tView, lView, tNode);
  28024. ngDevMode && validateNodeExists(currentRNode, lView, tNode);
  28025. const ngContainerSize = getNgContainerSize(hydrationInfo, index);
  28026. ngDevMode &&
  28027. assertNumber(ngContainerSize, 'Unexpected state: hydrating an <ng-container>, ' + 'but no hydration info is available.');
  28028. setSegmentHead(hydrationInfo, index, currentRNode);
  28029. comment = siblingAfter(ngContainerSize, currentRNode);
  28030. if (ngDevMode) {
  28031. validateMatchingNode(comment, Node.COMMENT_NODE, null, lView, tNode);
  28032. markRNodeAsClaimedByHydration(comment);
  28033. }
  28034. return comment;
  28035. }
  28036. function enableLocateOrCreateElementContainerNodeImpl() {
  28037. _locateOrCreateElementContainerNode = locateOrCreateElementContainerNode;
  28038. }
  28039. /**
  28040. * Returns the current OpaqueViewState instance.
  28041. *
  28042. * Used in conjunction with the restoreView() instruction to save a snapshot
  28043. * of the current view and restore it when listeners are invoked. This allows
  28044. * walking the declaration view tree in listeners to get vars from parent views.
  28045. *
  28046. * @codeGenApi
  28047. */
  28048. function ɵɵgetCurrentView() {
  28049. return getLView();
  28050. }
  28051. /**
  28052. * Update a property on a host element. Only applies to native node properties, not inputs.
  28053. *
  28054. * Operates on the element selected by index via the {@link select} instruction.
  28055. *
  28056. * @param propName Name of property. Because it is going to DOM, this is not subject to
  28057. * renaming as part of minification.
  28058. * @param value New value to write.
  28059. * @param sanitizer An optional function used to sanitize the value.
  28060. * @returns This function returns itself so that it may be chained
  28061. * (e.g. `property('name', ctx.name)('title', ctx.title)`)
  28062. *
  28063. * @codeGenApi
  28064. */
  28065. function ɵɵhostProperty(propName, value, sanitizer) {
  28066. const lView = getLView();
  28067. const bindingIndex = nextBindingIndex();
  28068. if (bindingUpdated(lView, bindingIndex, value)) {
  28069. const tView = getTView();
  28070. const tNode = getSelectedTNode();
  28071. elementPropertyInternal(tView, tNode, lView, propName, value, lView[RENDERER], sanitizer, true);
  28072. ngDevMode && storePropertyBindingMetadata(tView.data, tNode, propName, bindingIndex);
  28073. }
  28074. return ɵɵhostProperty;
  28075. }
  28076. /**
  28077. * Updates a synthetic host binding (e.g. `[@foo]`) on a component or directive.
  28078. *
  28079. * This instruction is for compatibility purposes and is designed to ensure that a
  28080. * synthetic host binding (e.g. `@HostBinding('@foo')`) properly gets rendered in
  28081. * the component's renderer. Normally all host bindings are evaluated with the parent
  28082. * component's renderer, but, in the case of animation @triggers, they need to be
  28083. * evaluated with the sub component's renderer (because that's where the animation
  28084. * triggers are defined).
  28085. *
  28086. * Do not use this instruction as a replacement for `elementProperty`. This instruction
  28087. * only exists to ensure compatibility with the ViewEngine's host binding behavior.
  28088. *
  28089. * @param index The index of the element to update in the data array
  28090. * @param propName Name of property. Because it is going to DOM, this is not subject to
  28091. * renaming as part of minification.
  28092. * @param value New value to write.
  28093. * @param sanitizer An optional function used to sanitize the value.
  28094. *
  28095. * @codeGenApi
  28096. */
  28097. function ɵɵsyntheticHostProperty(propName, value, sanitizer) {
  28098. const lView = getLView();
  28099. const bindingIndex = nextBindingIndex();
  28100. if (bindingUpdated(lView, bindingIndex, value)) {
  28101. const tView = getTView();
  28102. const tNode = getSelectedTNode();
  28103. const currentDef = getCurrentDirectiveDef(tView.data);
  28104. const renderer = loadComponentRenderer(currentDef, tNode, lView);
  28105. elementPropertyInternal(tView, tNode, lView, propName, value, renderer, sanitizer, true);
  28106. ngDevMode && storePropertyBindingMetadata(tView.data, tNode, propName, bindingIndex);
  28107. }
  28108. return ɵɵsyntheticHostProperty;
  28109. }
  28110. // THIS CODE IS GENERATED - DO NOT MODIFY.
  28111. const u = undefined;
  28112. function plural(val) {
  28113. const i = Math.floor(Math.abs(val)), v = val.toString().replace(/^[^.]*\.?/, '').length;
  28114. if (i === 1 && v === 0)
  28115. return 1;
  28116. return 5;
  28117. }
  28118. 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];
  28119. /**
  28120. * This const is used to store the locale data registered with `registerLocaleData`
  28121. */
  28122. let LOCALE_DATA = {};
  28123. /**
  28124. * Register locale data to be used internally by Angular. See the
  28125. * ["I18n guide"](guide/i18n/format-data-locale) to know how to import additional locale
  28126. * data.
  28127. *
  28128. * The signature `registerLocaleData(data: any, extraData?: any)` is deprecated since v5.1
  28129. */
  28130. function registerLocaleData(data, localeId, extraData) {
  28131. if (typeof localeId !== 'string') {
  28132. extraData = localeId;
  28133. localeId = data[LocaleDataIndex.LocaleId];
  28134. }
  28135. localeId = localeId.toLowerCase().replace(/_/g, '-');
  28136. LOCALE_DATA[localeId] = data;
  28137. if (extraData) {
  28138. LOCALE_DATA[localeId][LocaleDataIndex.ExtraData] = extraData;
  28139. }
  28140. }
  28141. /**
  28142. * Finds the locale data for a given locale.
  28143. *
  28144. * @param locale The locale code.
  28145. * @returns The locale data.
  28146. * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
  28147. */
  28148. function findLocaleData(locale) {
  28149. const normalizedLocale = normalizeLocale(locale);
  28150. let match = getLocaleData(normalizedLocale);
  28151. if (match) {
  28152. return match;
  28153. }
  28154. // let's try to find a parent locale
  28155. const parentLocale = normalizedLocale.split('-')[0];
  28156. match = getLocaleData(parentLocale);
  28157. if (match) {
  28158. return match;
  28159. }
  28160. if (parentLocale === 'en') {
  28161. return localeEn;
  28162. }
  28163. throw new RuntimeError(701 /* RuntimeErrorCode.MISSING_LOCALE_DATA */, ngDevMode && `Missing locale data for the locale "${locale}".`);
  28164. }
  28165. /**
  28166. * Retrieves the default currency code for the given locale.
  28167. *
  28168. * The default is defined as the first currency which is still in use.
  28169. *
  28170. * @param locale The code of the locale whose currency code we want.
  28171. * @returns The code of the default currency for the given locale.
  28172. *
  28173. */
  28174. function getLocaleCurrencyCode(locale) {
  28175. const data = findLocaleData(locale);
  28176. return data[LocaleDataIndex.CurrencyCode] || null;
  28177. }
  28178. /**
  28179. * Retrieves the plural function used by ICU expressions to determine the plural case to use
  28180. * for a given locale.
  28181. * @param locale A locale code for the locale format rules to use.
  28182. * @returns The plural function for the locale.
  28183. * @see {@link NgPlural}
  28184. * @see [Internationalization (i18n) Guide](guide/i18n)
  28185. */
  28186. function getLocalePluralCase(locale) {
  28187. const data = findLocaleData(locale);
  28188. return data[LocaleDataIndex.PluralCase];
  28189. }
  28190. /**
  28191. * Helper function to get the given `normalizedLocale` from `LOCALE_DATA`
  28192. * or from the global `ng.common.locale`.
  28193. */
  28194. function getLocaleData(normalizedLocale) {
  28195. if (!(normalizedLocale in LOCALE_DATA)) {
  28196. LOCALE_DATA[normalizedLocale] =
  28197. _global.ng &&
  28198. _global.ng.common &&
  28199. _global.ng.common.locales &&
  28200. _global.ng.common.locales[normalizedLocale];
  28201. }
  28202. return LOCALE_DATA[normalizedLocale];
  28203. }
  28204. /**
  28205. * Helper function to remove all the locale data from `LOCALE_DATA`.
  28206. */
  28207. function unregisterAllLocaleData() {
  28208. LOCALE_DATA = {};
  28209. }
  28210. /**
  28211. * Index of each type of locale data from the locale data array
  28212. */
  28213. var LocaleDataIndex;
  28214. (function (LocaleDataIndex) {
  28215. LocaleDataIndex[LocaleDataIndex["LocaleId"] = 0] = "LocaleId";
  28216. LocaleDataIndex[LocaleDataIndex["DayPeriodsFormat"] = 1] = "DayPeriodsFormat";
  28217. LocaleDataIndex[LocaleDataIndex["DayPeriodsStandalone"] = 2] = "DayPeriodsStandalone";
  28218. LocaleDataIndex[LocaleDataIndex["DaysFormat"] = 3] = "DaysFormat";
  28219. LocaleDataIndex[LocaleDataIndex["DaysStandalone"] = 4] = "DaysStandalone";
  28220. LocaleDataIndex[LocaleDataIndex["MonthsFormat"] = 5] = "MonthsFormat";
  28221. LocaleDataIndex[LocaleDataIndex["MonthsStandalone"] = 6] = "MonthsStandalone";
  28222. LocaleDataIndex[LocaleDataIndex["Eras"] = 7] = "Eras";
  28223. LocaleDataIndex[LocaleDataIndex["FirstDayOfWeek"] = 8] = "FirstDayOfWeek";
  28224. LocaleDataIndex[LocaleDataIndex["WeekendRange"] = 9] = "WeekendRange";
  28225. LocaleDataIndex[LocaleDataIndex["DateFormat"] = 10] = "DateFormat";
  28226. LocaleDataIndex[LocaleDataIndex["TimeFormat"] = 11] = "TimeFormat";
  28227. LocaleDataIndex[LocaleDataIndex["DateTimeFormat"] = 12] = "DateTimeFormat";
  28228. LocaleDataIndex[LocaleDataIndex["NumberSymbols"] = 13] = "NumberSymbols";
  28229. LocaleDataIndex[LocaleDataIndex["NumberFormats"] = 14] = "NumberFormats";
  28230. LocaleDataIndex[LocaleDataIndex["CurrencyCode"] = 15] = "CurrencyCode";
  28231. LocaleDataIndex[LocaleDataIndex["CurrencySymbol"] = 16] = "CurrencySymbol";
  28232. LocaleDataIndex[LocaleDataIndex["CurrencyName"] = 17] = "CurrencyName";
  28233. LocaleDataIndex[LocaleDataIndex["Currencies"] = 18] = "Currencies";
  28234. LocaleDataIndex[LocaleDataIndex["Directionality"] = 19] = "Directionality";
  28235. LocaleDataIndex[LocaleDataIndex["PluralCase"] = 20] = "PluralCase";
  28236. LocaleDataIndex[LocaleDataIndex["ExtraData"] = 21] = "ExtraData";
  28237. })(LocaleDataIndex || (LocaleDataIndex = {}));
  28238. /**
  28239. * Returns the canonical form of a locale name - lowercase with `_` replaced with `-`.
  28240. */
  28241. function normalizeLocale(locale) {
  28242. return locale.toLowerCase().replace(/_/g, '-');
  28243. }
  28244. const pluralMapping = ['zero', 'one', 'two', 'few', 'many'];
  28245. /**
  28246. * Returns the plural case based on the locale
  28247. */
  28248. function getPluralCase(value, locale) {
  28249. const plural = getLocalePluralCase(locale)(parseInt(value, 10));
  28250. const result = pluralMapping[plural];
  28251. return result !== undefined ? result : 'other';
  28252. }
  28253. /**
  28254. * The locale id that the application is using by default (for translations and ICU expressions).
  28255. */
  28256. const DEFAULT_LOCALE_ID = 'en-US';
  28257. /**
  28258. * USD currency code that the application uses by default for CurrencyPipe when no
  28259. * DEFAULT_CURRENCY_CODE is provided.
  28260. */
  28261. const USD_CURRENCY_CODE = 'USD';
  28262. /**
  28263. * Marks that the next string is an element name.
  28264. *
  28265. * See `I18nMutateOpCodes` documentation.
  28266. */
  28267. const ELEMENT_MARKER = {
  28268. marker: 'element',
  28269. };
  28270. /**
  28271. * Marks that the next string is comment text need for ICU.
  28272. *
  28273. * See `I18nMutateOpCodes` documentation.
  28274. */
  28275. const ICU_MARKER = {
  28276. marker: 'ICU',
  28277. };
  28278. /**
  28279. * See `I18nCreateOpCodes`
  28280. */
  28281. var I18nCreateOpCode;
  28282. (function (I18nCreateOpCode) {
  28283. /**
  28284. * Number of bits to shift index so that it can be combined with the `APPEND_EAGERLY` and
  28285. * `COMMENT`.
  28286. */
  28287. I18nCreateOpCode[I18nCreateOpCode["SHIFT"] = 2] = "SHIFT";
  28288. /**
  28289. * Should the node be appended to parent immediately after creation.
  28290. */
  28291. I18nCreateOpCode[I18nCreateOpCode["APPEND_EAGERLY"] = 1] = "APPEND_EAGERLY";
  28292. /**
  28293. * If set the node should be comment (rather than a text) node.
  28294. */
  28295. I18nCreateOpCode[I18nCreateOpCode["COMMENT"] = 2] = "COMMENT";
  28296. })(I18nCreateOpCode || (I18nCreateOpCode = {}));
  28297. /**
  28298. * The locale id that the application is currently using (for translations and ICU expressions).
  28299. * This is the ivy version of `LOCALE_ID` that was defined as an injection token for the view engine
  28300. * but is now defined as a global value.
  28301. */
  28302. let LOCALE_ID$1 = DEFAULT_LOCALE_ID;
  28303. /**
  28304. * Sets the locale id that will be used for translations and ICU expressions.
  28305. * This is the ivy version of `LOCALE_ID` that was defined as an injection token for the view engine
  28306. * but is now defined as a global value.
  28307. *
  28308. * @param localeId
  28309. */
  28310. function setLocaleId(localeId) {
  28311. ngDevMode && assertDefined(localeId, `Expected localeId to be defined`);
  28312. if (typeof localeId === 'string') {
  28313. LOCALE_ID$1 = localeId.toLowerCase().replace(/_/g, '-');
  28314. }
  28315. }
  28316. /**
  28317. * Gets the locale id that will be used for translations and ICU expressions.
  28318. * This is the ivy version of `LOCALE_ID` that was defined as an injection token for the view engine
  28319. * but is now defined as a global value.
  28320. */
  28321. function getLocaleId() {
  28322. return LOCALE_ID$1;
  28323. }
  28324. /**
  28325. * Keep track of which input bindings in `ɵɵi18nExp` have changed.
  28326. *
  28327. * This is used to efficiently update expressions in i18n only when the corresponding input has
  28328. * changed.
  28329. *
  28330. * 1) Each bit represents which of the `ɵɵi18nExp` has changed.
  28331. * 2) There are 32 bits allowed in JS.
  28332. * 3) Bit 32 is special as it is shared for all changes past 32. (In other words if you have more
  28333. * than 32 `ɵɵi18nExp` then all changes past 32nd `ɵɵi18nExp` will be mapped to same bit. This means
  28334. * that we may end up changing more than we need to. But i18n expressions with 32 bindings is rare
  28335. * so in practice it should not be an issue.)
  28336. */
  28337. let changeMask = 0b0;
  28338. /**
  28339. * Keeps track of which bit needs to be updated in `changeMask`
  28340. *
  28341. * This value gets incremented on every call to `ɵɵi18nExp`
  28342. */
  28343. let changeMaskCounter = 0;
  28344. /**
  28345. * Keep track of which input bindings in `ɵɵi18nExp` have changed.
  28346. *
  28347. * `setMaskBit` gets invoked by each call to `ɵɵi18nExp`.
  28348. *
  28349. * @param hasChange did `ɵɵi18nExp` detect a change.
  28350. */
  28351. function setMaskBit(hasChange) {
  28352. if (hasChange) {
  28353. changeMask = changeMask | (1 << Math.min(changeMaskCounter, 31));
  28354. }
  28355. changeMaskCounter++;
  28356. }
  28357. function applyI18n(tView, lView, index) {
  28358. if (changeMaskCounter > 0) {
  28359. ngDevMode && assertDefined(tView, `tView should be defined`);
  28360. const tI18n = tView.data[index];
  28361. // When `index` points to an `ɵɵi18nAttributes` then we have an array otherwise `TI18n`
  28362. const updateOpCodes = Array.isArray(tI18n)
  28363. ? tI18n
  28364. : tI18n.update;
  28365. const bindingsStartIndex = getBindingIndex() - changeMaskCounter - 1;
  28366. applyUpdateOpCodes(tView, lView, updateOpCodes, bindingsStartIndex, changeMask);
  28367. }
  28368. // Reset changeMask & maskBit to default for the next update cycle
  28369. changeMask = 0b0;
  28370. changeMaskCounter = 0;
  28371. }
  28372. function createNodeWithoutHydration(lView, textOrName, nodeType) {
  28373. const renderer = lView[RENDERER];
  28374. switch (nodeType) {
  28375. case Node.COMMENT_NODE:
  28376. return createCommentNode(renderer, textOrName);
  28377. case Node.TEXT_NODE:
  28378. return createTextNode(renderer, textOrName);
  28379. case Node.ELEMENT_NODE:
  28380. return createElementNode(renderer, textOrName, null);
  28381. }
  28382. }
  28383. let _locateOrCreateNode = (lView, index, textOrName, nodeType) => {
  28384. lastNodeWasCreated(true);
  28385. return createNodeWithoutHydration(lView, textOrName, nodeType);
  28386. };
  28387. function locateOrCreateNodeImpl(lView, index, textOrName, nodeType) {
  28388. const hydrationInfo = lView[HYDRATION];
  28389. const noOffsetIndex = index - HEADER_OFFSET;
  28390. const isNodeCreationMode = !isI18nHydrationSupportEnabled() ||
  28391. !hydrationInfo ||
  28392. isInSkipHydrationBlock$1() ||
  28393. isDisconnectedNode$1(hydrationInfo, noOffsetIndex);
  28394. lastNodeWasCreated(isNodeCreationMode);
  28395. if (isNodeCreationMode) {
  28396. return createNodeWithoutHydration(lView, textOrName, nodeType);
  28397. }
  28398. const native = locateI18nRNodeByIndex(hydrationInfo, noOffsetIndex);
  28399. // TODO: Improve error handling
  28400. //
  28401. // Other hydration paths use validateMatchingNode() in order to provide
  28402. // detailed information in development mode about the expected DOM.
  28403. // However, not every node in an i18n block has a TNode. Instead, we
  28404. // need to be able to use the AST to generate a similar message.
  28405. ngDevMode && assertDefined(native, 'expected native element');
  28406. ngDevMode && assertEqual(native.nodeType, nodeType, 'expected matching nodeType');
  28407. ngDevMode &&
  28408. nodeType === Node.ELEMENT_NODE &&
  28409. assertEqual(native.tagName.toLowerCase(), textOrName.toLowerCase(), 'expecting matching tagName');
  28410. ngDevMode && markRNodeAsClaimedByHydration(native);
  28411. return native;
  28412. }
  28413. function enableLocateOrCreateI18nNodeImpl() {
  28414. _locateOrCreateNode = locateOrCreateNodeImpl;
  28415. }
  28416. /**
  28417. * Apply `I18nCreateOpCodes` op-codes as stored in `TI18n.create`.
  28418. *
  28419. * Creates text (and comment) nodes which are internationalized.
  28420. *
  28421. * @param lView Current lView
  28422. * @param createOpCodes Set of op-codes to apply
  28423. * @param parentRNode Parent node (so that direct children can be added eagerly) or `null` if it is
  28424. * a root node.
  28425. * @param insertInFrontOf DOM node that should be used as an anchor.
  28426. */
  28427. function applyCreateOpCodes(lView, createOpCodes, parentRNode, insertInFrontOf) {
  28428. const renderer = lView[RENDERER];
  28429. for (let i = 0; i < createOpCodes.length; i++) {
  28430. const opCode = createOpCodes[i++];
  28431. const text = createOpCodes[i];
  28432. const isComment = (opCode & I18nCreateOpCode.COMMENT) === I18nCreateOpCode.COMMENT;
  28433. const appendNow = (opCode & I18nCreateOpCode.APPEND_EAGERLY) === I18nCreateOpCode.APPEND_EAGERLY;
  28434. const index = opCode >>> I18nCreateOpCode.SHIFT;
  28435. let rNode = lView[index];
  28436. let lastNodeWasCreated = false;
  28437. if (rNode === null) {
  28438. // We only create new DOM nodes if they don't already exist: If ICU switches case back to a
  28439. // case which was already instantiated, no need to create new DOM nodes.
  28440. rNode = lView[index] = _locateOrCreateNode(lView, index, text, isComment ? Node.COMMENT_NODE : Node.TEXT_NODE);
  28441. lastNodeWasCreated = wasLastNodeCreated();
  28442. }
  28443. if (appendNow && parentRNode !== null && lastNodeWasCreated) {
  28444. nativeInsertBefore(renderer, parentRNode, rNode, insertInFrontOf, false);
  28445. }
  28446. }
  28447. }
  28448. /**
  28449. * Apply `I18nMutateOpCodes` OpCodes.
  28450. *
  28451. * @param tView Current `TView`
  28452. * @param mutableOpCodes Mutable OpCodes to process
  28453. * @param lView Current `LView`
  28454. * @param anchorRNode place where the i18n node should be inserted.
  28455. */
  28456. function applyMutableOpCodes(tView, mutableOpCodes, lView, anchorRNode) {
  28457. ngDevMode && assertDomNode(anchorRNode);
  28458. const renderer = lView[RENDERER];
  28459. // `rootIdx` represents the node into which all inserts happen.
  28460. let rootIdx = null;
  28461. // `rootRNode` represents the real node into which we insert. This can be different from
  28462. // `lView[rootIdx]` if we have projection.
  28463. // - null we don't have a parent (as can be the case in when we are inserting into a root of
  28464. // LView which has no parent.)
  28465. // - `RElement` The element representing the root after taking projection into account.
  28466. let rootRNode;
  28467. for (let i = 0; i < mutableOpCodes.length; i++) {
  28468. const opCode = mutableOpCodes[i];
  28469. if (typeof opCode == 'string') {
  28470. const textNodeIndex = mutableOpCodes[++i];
  28471. if (lView[textNodeIndex] === null) {
  28472. ngDevMode && ngDevMode.rendererCreateTextNode++;
  28473. ngDevMode && assertIndexInRange(lView, textNodeIndex);
  28474. lView[textNodeIndex] = _locateOrCreateNode(lView, textNodeIndex, opCode, Node.TEXT_NODE);
  28475. }
  28476. }
  28477. else if (typeof opCode == 'number') {
  28478. switch (opCode & 1 /* IcuCreateOpCode.MASK_INSTRUCTION */) {
  28479. case 0 /* IcuCreateOpCode.AppendChild */:
  28480. const parentIdx = getParentFromIcuCreateOpCode(opCode);
  28481. if (rootIdx === null) {
  28482. // The first operation should save the `rootIdx` because the first operation
  28483. // must insert into the root. (Only subsequent operations can insert into a dynamic
  28484. // parent)
  28485. rootIdx = parentIdx;
  28486. rootRNode = renderer.parentNode(anchorRNode);
  28487. }
  28488. let insertInFrontOf;
  28489. let parentRNode;
  28490. if (parentIdx === rootIdx) {
  28491. insertInFrontOf = anchorRNode;
  28492. parentRNode = rootRNode;
  28493. }
  28494. else {
  28495. insertInFrontOf = null;
  28496. parentRNode = unwrapRNode(lView[parentIdx]);
  28497. }
  28498. // FIXME(misko): Refactor with `processI18nText`
  28499. if (parentRNode !== null) {
  28500. // This can happen if the `LView` we are adding to is not attached to a parent `LView`.
  28501. // In such a case there is no "root" we can attach to. This is fine, as we still need to
  28502. // create the elements. When the `LView` gets later added to a parent these "root" nodes
  28503. // get picked up and added.
  28504. ngDevMode && assertDomNode(parentRNode);
  28505. const refIdx = getRefFromIcuCreateOpCode(opCode);
  28506. ngDevMode && assertGreaterThan(refIdx, HEADER_OFFSET, 'Missing ref');
  28507. // `unwrapRNode` is not needed here as all of these point to RNodes as part of the i18n
  28508. // which can't have components.
  28509. const child = lView[refIdx];
  28510. ngDevMode && assertDomNode(child);
  28511. nativeInsertBefore(renderer, parentRNode, child, insertInFrontOf, false);
  28512. const tIcu = getTIcu(tView, refIdx);
  28513. if (tIcu !== null && typeof tIcu === 'object') {
  28514. // If we just added a comment node which has ICU then that ICU may have already been
  28515. // rendered and therefore we need to re-add it here.
  28516. ngDevMode && assertTIcu(tIcu);
  28517. const caseIndex = getCurrentICUCaseIndex(tIcu, lView);
  28518. if (caseIndex !== null) {
  28519. applyMutableOpCodes(tView, tIcu.create[caseIndex], lView, lView[tIcu.anchorIdx]);
  28520. }
  28521. }
  28522. }
  28523. break;
  28524. case 1 /* IcuCreateOpCode.Attr */:
  28525. const elementNodeIndex = opCode >>> 1 /* IcuCreateOpCode.SHIFT_REF */;
  28526. const attrName = mutableOpCodes[++i];
  28527. const attrValue = mutableOpCodes[++i];
  28528. // This code is used for ICU expressions only, since we don't support
  28529. // directives/components in ICUs, we don't need to worry about inputs here
  28530. setElementAttribute(renderer, getNativeByIndex(elementNodeIndex, lView), null, null, attrName, attrValue, null);
  28531. break;
  28532. default:
  28533. if (ngDevMode) {
  28534. throw new RuntimeError(700 /* RuntimeErrorCode.INVALID_I18N_STRUCTURE */, `Unable to determine the type of mutate operation for "${opCode}"`);
  28535. }
  28536. }
  28537. }
  28538. else {
  28539. switch (opCode) {
  28540. case ICU_MARKER:
  28541. const commentValue = mutableOpCodes[++i];
  28542. const commentNodeIndex = mutableOpCodes[++i];
  28543. if (lView[commentNodeIndex] === null) {
  28544. ngDevMode &&
  28545. assertEqual(typeof commentValue, 'string', `Expected "${commentValue}" to be a comment node value`);
  28546. ngDevMode && ngDevMode.rendererCreateComment++;
  28547. ngDevMode && assertIndexInExpandoRange(lView, commentNodeIndex);
  28548. const commentRNode = (lView[commentNodeIndex] = _locateOrCreateNode(lView, commentNodeIndex, commentValue, Node.COMMENT_NODE));
  28549. // FIXME(misko): Attaching patch data is only needed for the root (Also add tests)
  28550. attachPatchData(commentRNode, lView);
  28551. }
  28552. break;
  28553. case ELEMENT_MARKER:
  28554. const tagName = mutableOpCodes[++i];
  28555. const elementNodeIndex = mutableOpCodes[++i];
  28556. if (lView[elementNodeIndex] === null) {
  28557. ngDevMode &&
  28558. assertEqual(typeof tagName, 'string', `Expected "${tagName}" to be an element node tag name`);
  28559. ngDevMode && ngDevMode.rendererCreateElement++;
  28560. ngDevMode && assertIndexInExpandoRange(lView, elementNodeIndex);
  28561. const elementRNode = (lView[elementNodeIndex] = _locateOrCreateNode(lView, elementNodeIndex, tagName, Node.ELEMENT_NODE));
  28562. // FIXME(misko): Attaching patch data is only needed for the root (Also add tests)
  28563. attachPatchData(elementRNode, lView);
  28564. }
  28565. break;
  28566. default:
  28567. ngDevMode &&
  28568. throwError(`Unable to determine the type of mutate operation for "${opCode}"`);
  28569. }
  28570. }
  28571. }
  28572. }
  28573. /**
  28574. * Apply `I18nUpdateOpCodes` OpCodes
  28575. *
  28576. * @param tView Current `TView`
  28577. * @param lView Current `LView`
  28578. * @param updateOpCodes OpCodes to process
  28579. * @param bindingsStartIndex Location of the first `ɵɵi18nApply`
  28580. * @param changeMask Each bit corresponds to a `ɵɵi18nExp` (Counting backwards from
  28581. * `bindingsStartIndex`)
  28582. */
  28583. function applyUpdateOpCodes(tView, lView, updateOpCodes, bindingsStartIndex, changeMask) {
  28584. for (let i = 0; i < updateOpCodes.length; i++) {
  28585. // bit code to check if we should apply the next update
  28586. const checkBit = updateOpCodes[i];
  28587. // Number of opCodes to skip until next set of update codes
  28588. const skipCodes = updateOpCodes[++i];
  28589. if (checkBit & changeMask) {
  28590. // The value has been updated since last checked
  28591. let value = '';
  28592. for (let j = i + 1; j <= i + skipCodes; j++) {
  28593. const opCode = updateOpCodes[j];
  28594. if (typeof opCode == 'string') {
  28595. value += opCode;
  28596. }
  28597. else if (typeof opCode == 'number') {
  28598. if (opCode < 0) {
  28599. // Negative opCode represent `i18nExp` values offset.
  28600. value += renderStringify(lView[bindingsStartIndex - opCode]);
  28601. }
  28602. else {
  28603. const nodeIndex = opCode >>> 2 /* I18nUpdateOpCode.SHIFT_REF */;
  28604. switch (opCode & 3 /* I18nUpdateOpCode.MASK_OPCODE */) {
  28605. case 1 /* I18nUpdateOpCode.Attr */:
  28606. const propName = updateOpCodes[++j];
  28607. const sanitizeFn = updateOpCodes[++j];
  28608. const tNodeOrTagName = tView.data[nodeIndex];
  28609. ngDevMode && assertDefined(tNodeOrTagName, 'Experting TNode or string');
  28610. if (typeof tNodeOrTagName === 'string') {
  28611. // IF we don't have a `TNode`, then we are an element in ICU (as ICU content does
  28612. // not have TNode), in which case we know that there are no directives, and hence
  28613. // we use attribute setting.
  28614. setElementAttribute(lView[RENDERER], lView[nodeIndex], null, tNodeOrTagName, propName, value, sanitizeFn);
  28615. }
  28616. else {
  28617. elementPropertyInternal(tView, tNodeOrTagName, lView, propName, value, lView[RENDERER], sanitizeFn, false);
  28618. }
  28619. break;
  28620. case 0 /* I18nUpdateOpCode.Text */:
  28621. const rText = lView[nodeIndex];
  28622. rText !== null && updateTextNode(lView[RENDERER], rText, value);
  28623. break;
  28624. case 2 /* I18nUpdateOpCode.IcuSwitch */:
  28625. applyIcuSwitchCase(tView, getTIcu(tView, nodeIndex), lView, value);
  28626. break;
  28627. case 3 /* I18nUpdateOpCode.IcuUpdate */:
  28628. applyIcuUpdateCase(tView, getTIcu(tView, nodeIndex), bindingsStartIndex, lView);
  28629. break;
  28630. }
  28631. }
  28632. }
  28633. }
  28634. }
  28635. else {
  28636. const opCode = updateOpCodes[i + 1];
  28637. if (opCode > 0 && (opCode & 3 /* I18nUpdateOpCode.MASK_OPCODE */) === 3 /* I18nUpdateOpCode.IcuUpdate */) {
  28638. // Special case for the `icuUpdateCase`. It could be that the mask did not match, but
  28639. // we still need to execute `icuUpdateCase` because the case has changed recently due to
  28640. // previous `icuSwitchCase` instruction. (`icuSwitchCase` and `icuUpdateCase` always come in
  28641. // pairs.)
  28642. const nodeIndex = opCode >>> 2 /* I18nUpdateOpCode.SHIFT_REF */;
  28643. const tIcu = getTIcu(tView, nodeIndex);
  28644. const currentIndex = lView[tIcu.currentCaseLViewIndex];
  28645. if (currentIndex < 0) {
  28646. applyIcuUpdateCase(tView, tIcu, bindingsStartIndex, lView);
  28647. }
  28648. }
  28649. }
  28650. i += skipCodes;
  28651. }
  28652. }
  28653. /**
  28654. * Apply OpCodes associated with updating an existing ICU.
  28655. *
  28656. * @param tView Current `TView`
  28657. * @param tIcu Current `TIcu`
  28658. * @param bindingsStartIndex Location of the first `ɵɵi18nApply`
  28659. * @param lView Current `LView`
  28660. */
  28661. function applyIcuUpdateCase(tView, tIcu, bindingsStartIndex, lView) {
  28662. ngDevMode && assertIndexInRange(lView, tIcu.currentCaseLViewIndex);
  28663. let activeCaseIndex = lView[tIcu.currentCaseLViewIndex];
  28664. if (activeCaseIndex !== null) {
  28665. let mask = changeMask;
  28666. if (activeCaseIndex < 0) {
  28667. // Clear the flag.
  28668. // Negative number means that the ICU was freshly created and we need to force the update.
  28669. activeCaseIndex = lView[tIcu.currentCaseLViewIndex] = ~activeCaseIndex;
  28670. // -1 is same as all bits on, which simulates creation since it marks all bits dirty
  28671. mask = -1;
  28672. }
  28673. applyUpdateOpCodes(tView, lView, tIcu.update[activeCaseIndex], bindingsStartIndex, mask);
  28674. }
  28675. }
  28676. /**
  28677. * Apply OpCodes associated with switching a case on ICU.
  28678. *
  28679. * This involves tearing down existing case and than building up a new case.
  28680. *
  28681. * @param tView Current `TView`
  28682. * @param tIcu Current `TIcu`
  28683. * @param lView Current `LView`
  28684. * @param value Value of the case to update to.
  28685. */
  28686. function applyIcuSwitchCase(tView, tIcu, lView, value) {
  28687. // Rebuild a new case for this ICU
  28688. const caseIndex = getCaseIndex(tIcu, value);
  28689. let activeCaseIndex = getCurrentICUCaseIndex(tIcu, lView);
  28690. if (activeCaseIndex !== caseIndex) {
  28691. applyIcuSwitchCaseRemove(tView, tIcu, lView);
  28692. lView[tIcu.currentCaseLViewIndex] = caseIndex === null ? null : ~caseIndex;
  28693. if (caseIndex !== null) {
  28694. // Add the nodes for the new case
  28695. const anchorRNode = lView[tIcu.anchorIdx];
  28696. if (anchorRNode) {
  28697. ngDevMode && assertDomNode(anchorRNode);
  28698. applyMutableOpCodes(tView, tIcu.create[caseIndex], lView, anchorRNode);
  28699. }
  28700. claimDehydratedIcuCase(lView, tIcu.anchorIdx, caseIndex);
  28701. }
  28702. }
  28703. }
  28704. /**
  28705. * Apply OpCodes associated with tearing ICU case.
  28706. *
  28707. * This involves tearing down existing case and than building up a new case.
  28708. *
  28709. * @param tView Current `TView`
  28710. * @param tIcu Current `TIcu`
  28711. * @param lView Current `LView`
  28712. */
  28713. function applyIcuSwitchCaseRemove(tView, tIcu, lView) {
  28714. let activeCaseIndex = getCurrentICUCaseIndex(tIcu, lView);
  28715. if (activeCaseIndex !== null) {
  28716. const removeCodes = tIcu.remove[activeCaseIndex];
  28717. for (let i = 0; i < removeCodes.length; i++) {
  28718. const nodeOrIcuIndex = removeCodes[i];
  28719. if (nodeOrIcuIndex > 0) {
  28720. // Positive numbers are `RNode`s.
  28721. const rNode = getNativeByIndex(nodeOrIcuIndex, lView);
  28722. rNode !== null && nativeRemoveNode(lView[RENDERER], rNode);
  28723. }
  28724. else {
  28725. // Negative numbers are ICUs
  28726. applyIcuSwitchCaseRemove(tView, getTIcu(tView, ~nodeOrIcuIndex), lView);
  28727. }
  28728. }
  28729. }
  28730. }
  28731. /**
  28732. * Returns the index of the current case of an ICU expression depending on the main binding value
  28733. *
  28734. * @param icuExpression
  28735. * @param bindingValue The value of the main binding used by this ICU expression
  28736. */
  28737. function getCaseIndex(icuExpression, bindingValue) {
  28738. let index = icuExpression.cases.indexOf(bindingValue);
  28739. if (index === -1) {
  28740. switch (icuExpression.type) {
  28741. case 1 /* IcuType.plural */: {
  28742. const resolvedCase = getPluralCase(bindingValue, getLocaleId());
  28743. index = icuExpression.cases.indexOf(resolvedCase);
  28744. if (index === -1 && resolvedCase !== 'other') {
  28745. index = icuExpression.cases.indexOf('other');
  28746. }
  28747. break;
  28748. }
  28749. case 0 /* IcuType.select */: {
  28750. index = icuExpression.cases.indexOf('other');
  28751. break;
  28752. }
  28753. }
  28754. }
  28755. return index === -1 ? null : index;
  28756. }
  28757. /**
  28758. * Converts `I18nCreateOpCodes` array into a human readable format.
  28759. *
  28760. * This function is attached to the `I18nCreateOpCodes.debug` property if `ngDevMode` is enabled.
  28761. * This function provides a human readable view of the opcodes. This is useful when debugging the
  28762. * application as well as writing more readable tests.
  28763. *
  28764. * @param this `I18nCreateOpCodes` if attached as a method.
  28765. * @param opcodes `I18nCreateOpCodes` if invoked as a function.
  28766. */
  28767. function i18nCreateOpCodesToString(opcodes) {
  28768. const createOpCodes = opcodes || (Array.isArray(this) ? this : []);
  28769. let lines = [];
  28770. for (let i = 0; i < createOpCodes.length; i++) {
  28771. const opCode = createOpCodes[i++];
  28772. const text = createOpCodes[i];
  28773. const isComment = (opCode & I18nCreateOpCode.COMMENT) === I18nCreateOpCode.COMMENT;
  28774. const appendNow = (opCode & I18nCreateOpCode.APPEND_EAGERLY) === I18nCreateOpCode.APPEND_EAGERLY;
  28775. const index = opCode >>> I18nCreateOpCode.SHIFT;
  28776. lines.push(`lView[${index}] = document.${isComment ? 'createComment' : 'createText'}(${JSON.stringify(text)});`);
  28777. if (appendNow) {
  28778. lines.push(`parent.appendChild(lView[${index}]);`);
  28779. }
  28780. }
  28781. return lines;
  28782. }
  28783. /**
  28784. * Converts `I18nUpdateOpCodes` array into a human readable format.
  28785. *
  28786. * This function is attached to the `I18nUpdateOpCodes.debug` property if `ngDevMode` is enabled.
  28787. * This function provides a human readable view of the opcodes. This is useful when debugging the
  28788. * application as well as writing more readable tests.
  28789. *
  28790. * @param this `I18nUpdateOpCodes` if attached as a method.
  28791. * @param opcodes `I18nUpdateOpCodes` if invoked as a function.
  28792. */
  28793. function i18nUpdateOpCodesToString(opcodes) {
  28794. const parser = new OpCodeParser(opcodes || (Array.isArray(this) ? this : []));
  28795. let lines = [];
  28796. function consumeOpCode(value) {
  28797. const ref = value >>> 2 /* I18nUpdateOpCode.SHIFT_REF */;
  28798. const opCode = value & 3 /* I18nUpdateOpCode.MASK_OPCODE */;
  28799. switch (opCode) {
  28800. case 0 /* I18nUpdateOpCode.Text */:
  28801. return `(lView[${ref}] as Text).textContent = $$$`;
  28802. case 1 /* I18nUpdateOpCode.Attr */:
  28803. const attrName = parser.consumeString();
  28804. const sanitizationFn = parser.consumeFunction();
  28805. const value = sanitizationFn ? `(${sanitizationFn})($$$)` : '$$$';
  28806. return `(lView[${ref}] as Element).setAttribute('${attrName}', ${value})`;
  28807. case 2 /* I18nUpdateOpCode.IcuSwitch */:
  28808. return `icuSwitchCase(${ref}, $$$)`;
  28809. case 3 /* I18nUpdateOpCode.IcuUpdate */:
  28810. return `icuUpdateCase(${ref})`;
  28811. }
  28812. throw new Error('unexpected OpCode');
  28813. }
  28814. while (parser.hasMore()) {
  28815. let mask = parser.consumeNumber();
  28816. let size = parser.consumeNumber();
  28817. const end = parser.i + size;
  28818. const statements = [];
  28819. let statement = '';
  28820. while (parser.i < end) {
  28821. let value = parser.consumeNumberOrString();
  28822. if (typeof value === 'string') {
  28823. statement += value;
  28824. }
  28825. else if (value < 0) {
  28826. // Negative numbers are ref indexes
  28827. // Here `i` refers to current binding index. It is to signify that the value is relative,
  28828. // rather than absolute.
  28829. statement += '${lView[i' + value + ']}';
  28830. }
  28831. else {
  28832. // Positive numbers are operations.
  28833. const opCodeText = consumeOpCode(value);
  28834. statements.push(opCodeText.replace('$$$', '`' + statement + '`') + ';');
  28835. statement = '';
  28836. }
  28837. }
  28838. lines.push(`if (mask & 0b${mask.toString(2)}) { ${statements.join(' ')} }`);
  28839. }
  28840. return lines;
  28841. }
  28842. /**
  28843. * Converts `I18nCreateOpCodes` array into a human readable format.
  28844. *
  28845. * This function is attached to the `I18nCreateOpCodes.debug` if `ngDevMode` is enabled. This
  28846. * function provides a human readable view of the opcodes. This is useful when debugging the
  28847. * application as well as writing more readable tests.
  28848. *
  28849. * @param this `I18nCreateOpCodes` if attached as a method.
  28850. * @param opcodes `I18nCreateOpCodes` if invoked as a function.
  28851. */
  28852. function icuCreateOpCodesToString(opcodes) {
  28853. const parser = new OpCodeParser(opcodes || (Array.isArray(this) ? this : []));
  28854. let lines = [];
  28855. function consumeOpCode(opCode) {
  28856. const parent = getParentFromIcuCreateOpCode(opCode);
  28857. const ref = getRefFromIcuCreateOpCode(opCode);
  28858. switch (getInstructionFromIcuCreateOpCode(opCode)) {
  28859. case 0 /* IcuCreateOpCode.AppendChild */:
  28860. return `(lView[${parent}] as Element).appendChild(lView[${lastRef}])`;
  28861. case 1 /* IcuCreateOpCode.Attr */:
  28862. return `(lView[${ref}] as Element).setAttribute("${parser.consumeString()}", "${parser.consumeString()}")`;
  28863. }
  28864. throw new Error('Unexpected OpCode: ' + getInstructionFromIcuCreateOpCode(opCode));
  28865. }
  28866. let lastRef = -1;
  28867. while (parser.hasMore()) {
  28868. let value = parser.consumeNumberStringOrMarker();
  28869. if (value === ICU_MARKER) {
  28870. const text = parser.consumeString();
  28871. lastRef = parser.consumeNumber();
  28872. lines.push(`lView[${lastRef}] = document.createComment("${text}")`);
  28873. }
  28874. else if (value === ELEMENT_MARKER) {
  28875. const text = parser.consumeString();
  28876. lastRef = parser.consumeNumber();
  28877. lines.push(`lView[${lastRef}] = document.createElement("${text}")`);
  28878. }
  28879. else if (typeof value === 'string') {
  28880. lastRef = parser.consumeNumber();
  28881. lines.push(`lView[${lastRef}] = document.createTextNode("${value}")`);
  28882. }
  28883. else if (typeof value === 'number') {
  28884. const line = consumeOpCode(value);
  28885. line && lines.push(line);
  28886. }
  28887. else {
  28888. throw new Error('Unexpected value');
  28889. }
  28890. }
  28891. return lines;
  28892. }
  28893. /**
  28894. * Converts `I18nRemoveOpCodes` array into a human readable format.
  28895. *
  28896. * This function is attached to the `I18nRemoveOpCodes.debug` if `ngDevMode` is enabled. This
  28897. * function provides a human readable view of the opcodes. This is useful when debugging the
  28898. * application as well as writing more readable tests.
  28899. *
  28900. * @param this `I18nRemoveOpCodes` if attached as a method.
  28901. * @param opcodes `I18nRemoveOpCodes` if invoked as a function.
  28902. */
  28903. function i18nRemoveOpCodesToString(opcodes) {
  28904. const removeCodes = opcodes || (Array.isArray(this) ? this : []);
  28905. let lines = [];
  28906. for (let i = 0; i < removeCodes.length; i++) {
  28907. const nodeOrIcuIndex = removeCodes[i];
  28908. if (nodeOrIcuIndex > 0) {
  28909. // Positive numbers are `RNode`s.
  28910. lines.push(`remove(lView[${nodeOrIcuIndex}])`);
  28911. }
  28912. else {
  28913. // Negative numbers are ICUs
  28914. lines.push(`removeNestedICU(${~nodeOrIcuIndex})`);
  28915. }
  28916. }
  28917. return lines;
  28918. }
  28919. class OpCodeParser {
  28920. i = 0;
  28921. codes;
  28922. constructor(codes) {
  28923. this.codes = codes;
  28924. }
  28925. hasMore() {
  28926. return this.i < this.codes.length;
  28927. }
  28928. consumeNumber() {
  28929. let value = this.codes[this.i++];
  28930. assertNumber(value, 'expecting number in OpCode');
  28931. return value;
  28932. }
  28933. consumeString() {
  28934. let value = this.codes[this.i++];
  28935. assertString(value, 'expecting string in OpCode');
  28936. return value;
  28937. }
  28938. consumeFunction() {
  28939. let value = this.codes[this.i++];
  28940. if (value === null || typeof value === 'function') {
  28941. return value;
  28942. }
  28943. throw new Error('expecting function in OpCode');
  28944. }
  28945. consumeNumberOrString() {
  28946. let value = this.codes[this.i++];
  28947. if (typeof value === 'string') {
  28948. return value;
  28949. }
  28950. assertNumber(value, 'expecting number or string in OpCode');
  28951. return value;
  28952. }
  28953. consumeNumberStringOrMarker() {
  28954. let value = this.codes[this.i++];
  28955. if (typeof value === 'string' ||
  28956. typeof value === 'number' ||
  28957. value == ICU_MARKER ||
  28958. value == ELEMENT_MARKER) {
  28959. return value;
  28960. }
  28961. assertNumber(value, 'expecting number, string, ICU_MARKER or ELEMENT_MARKER in OpCode');
  28962. return value;
  28963. }
  28964. }
  28965. const BINDING_REGEXP = /�(\d+):?\d*�/gi;
  28966. const ICU_REGEXP = /({\s*�\d+:?\d*�\s*,\s*\S{6}\s*,[\s\S]*})/gi;
  28967. const NESTED_ICU = /�(\d+)�/;
  28968. const ICU_BLOCK_REGEXP = /^\s*(�\d+:?\d*�)\s*,\s*(select|plural)\s*,/;
  28969. const MARKER = `�`;
  28970. const SUBTEMPLATE_REGEXP = /�\/?\*(\d+:\d+)�/gi;
  28971. const PH_REGEXP = /�(\/?[#*]\d+):?\d*�/gi;
  28972. /**
  28973. * Angular uses the special entity &ngsp; as a placeholder for non-removable space.
  28974. * It's replaced by the 0xE500 PUA (Private Use Areas) unicode character and later on replaced by a
  28975. * space.
  28976. * We are re-implementing the same idea since translations might contain this special character.
  28977. */
  28978. const NGSP_UNICODE_REGEXP = /\uE500/g;
  28979. function replaceNgsp(value) {
  28980. return value.replace(NGSP_UNICODE_REGEXP, ' ');
  28981. }
  28982. /**
  28983. * Patch a `debug` property getter on top of the existing object.
  28984. *
  28985. * NOTE: always call this method with `ngDevMode && attachDebugObject(...)`
  28986. *
  28987. * @param obj Object to patch
  28988. * @param debugGetter Getter returning a value to patch
  28989. */
  28990. function attachDebugGetter(obj, debugGetter) {
  28991. if (ngDevMode) {
  28992. Object.defineProperty(obj, 'debug', { get: debugGetter, enumerable: false });
  28993. }
  28994. else {
  28995. throw new Error('This method should be guarded with `ngDevMode` so that it can be tree shaken in production!');
  28996. }
  28997. }
  28998. /**
  28999. * Create dynamic nodes from i18n translation block.
  29000. *
  29001. * - Text nodes are created synchronously
  29002. * - TNodes are linked into tree lazily
  29003. *
  29004. * @param tView Current `TView`
  29005. * @parentTNodeIndex index to the parent TNode of this i18n block
  29006. * @param lView Current `LView`
  29007. * @param index Index of `ɵɵi18nStart` instruction.
  29008. * @param message Message to translate.
  29009. * @param subTemplateIndex Index into the sub template of message translation. (ie in case of
  29010. * `ngIf`) (-1 otherwise)
  29011. */
  29012. function i18nStartFirstCreatePass(tView, parentTNodeIndex, lView, index, message, subTemplateIndex) {
  29013. const rootTNode = getCurrentParentTNode();
  29014. const createOpCodes = [];
  29015. const updateOpCodes = [];
  29016. const existingTNodeStack = [[]];
  29017. const astStack = [[]];
  29018. if (ngDevMode) {
  29019. attachDebugGetter(createOpCodes, i18nCreateOpCodesToString);
  29020. attachDebugGetter(updateOpCodes, i18nUpdateOpCodesToString);
  29021. }
  29022. message = getTranslationForTemplate(message, subTemplateIndex);
  29023. const msgParts = replaceNgsp(message).split(PH_REGEXP);
  29024. for (let i = 0; i < msgParts.length; i++) {
  29025. let value = msgParts[i];
  29026. if ((i & 1) === 0) {
  29027. // Even indexes are text (including bindings & ICU expressions)
  29028. const parts = i18nParseTextIntoPartsAndICU(value);
  29029. for (let j = 0; j < parts.length; j++) {
  29030. let part = parts[j];
  29031. if ((j & 1) === 0) {
  29032. // `j` is odd therefore `part` is string
  29033. const text = part;
  29034. ngDevMode && assertString(text, 'Parsed ICU part should be string');
  29035. if (text !== '') {
  29036. i18nStartFirstCreatePassProcessTextNode(astStack[0], tView, rootTNode, existingTNodeStack[0], createOpCodes, updateOpCodes, lView, text);
  29037. }
  29038. }
  29039. else {
  29040. // `j` is Even therefor `part` is an `ICUExpression`
  29041. const icuExpression = part;
  29042. // Verify that ICU expression has the right shape. Translations might contain invalid
  29043. // constructions (while original messages were correct), so ICU parsing at runtime may
  29044. // not succeed (thus `icuExpression` remains a string).
  29045. // Note: we intentionally retain the error here by not using `ngDevMode`, because
  29046. // the value can change based on the locale and users aren't guaranteed to hit
  29047. // an invalid string while they're developing.
  29048. if (typeof icuExpression !== 'object') {
  29049. throw new Error(`Unable to parse ICU expression in "${message}" message.`);
  29050. }
  29051. const icuContainerTNode = createTNodeAndAddOpCode(tView, rootTNode, existingTNodeStack[0], lView, createOpCodes, ngDevMode ? `ICU ${index}:${icuExpression.mainBinding}` : '', true);
  29052. const icuNodeIndex = icuContainerTNode.index;
  29053. ngDevMode &&
  29054. assertGreaterThanOrEqual(icuNodeIndex, HEADER_OFFSET, 'Index must be in absolute LView offset');
  29055. icuStart(astStack[0], tView, lView, updateOpCodes, parentTNodeIndex, icuExpression, icuNodeIndex);
  29056. }
  29057. }
  29058. }
  29059. else {
  29060. // Odd indexes are placeholders (elements and sub-templates)
  29061. // At this point value is something like: '/#1:2' (originally coming from '�/#1:2�')
  29062. const isClosing = value.charCodeAt(0) === 47 /* CharCode.SLASH */;
  29063. const type = value.charCodeAt(isClosing ? 1 : 0);
  29064. ngDevMode && assertOneOf(type, 42 /* CharCode.STAR */, 35 /* CharCode.HASH */);
  29065. const index = HEADER_OFFSET + Number.parseInt(value.substring(isClosing ? 2 : 1));
  29066. if (isClosing) {
  29067. existingTNodeStack.shift();
  29068. astStack.shift();
  29069. setCurrentTNode(getCurrentParentTNode(), false);
  29070. }
  29071. else {
  29072. const tNode = createTNodePlaceholder(tView, existingTNodeStack[0], index);
  29073. existingTNodeStack.unshift([]);
  29074. setCurrentTNode(tNode, true);
  29075. const placeholderNode = {
  29076. kind: 2 /* I18nNodeKind.PLACEHOLDER */,
  29077. index,
  29078. children: [],
  29079. type: type === 35 /* CharCode.HASH */ ? 0 /* I18nPlaceholderType.ELEMENT */ : 1 /* I18nPlaceholderType.SUBTEMPLATE */,
  29080. };
  29081. astStack[0].push(placeholderNode);
  29082. astStack.unshift(placeholderNode.children);
  29083. }
  29084. }
  29085. }
  29086. tView.data[index] = {
  29087. create: createOpCodes,
  29088. update: updateOpCodes,
  29089. ast: astStack[0],
  29090. parentTNodeIndex,
  29091. };
  29092. }
  29093. /**
  29094. * Allocate space in i18n Range add create OpCode instruction to create a text or comment node.
  29095. *
  29096. * @param tView Current `TView` needed to allocate space in i18n range.
  29097. * @param rootTNode Root `TNode` of the i18n block. This node determines if the new TNode will be
  29098. * added as part of the `i18nStart` instruction or as part of the `TNode.insertBeforeIndex`.
  29099. * @param existingTNodes internal state for `addTNodeAndUpdateInsertBeforeIndex`.
  29100. * @param lView Current `LView` needed to allocate space in i18n range.
  29101. * @param createOpCodes Array storing `I18nCreateOpCodes` where new opCodes will be added.
  29102. * @param text Text to be added when the `Text` or `Comment` node will be created.
  29103. * @param isICU true if a `Comment` node for ICU (instead of `Text`) node should be created.
  29104. */
  29105. function createTNodeAndAddOpCode(tView, rootTNode, existingTNodes, lView, createOpCodes, text, isICU) {
  29106. const i18nNodeIdx = allocExpando(tView, lView, 1, null);
  29107. let opCode = i18nNodeIdx << I18nCreateOpCode.SHIFT;
  29108. let parentTNode = getCurrentParentTNode();
  29109. if (rootTNode === parentTNode) {
  29110. // FIXME(misko): A null `parentTNode` should represent when we fall of the `LView` boundary.
  29111. // (there is no parent), but in some circumstances (because we are inconsistent about how we set
  29112. // `previousOrParentTNode`) it could point to `rootTNode` So this is a work around.
  29113. parentTNode = null;
  29114. }
  29115. if (parentTNode === null) {
  29116. // If we don't have a parent that means that we can eagerly add nodes.
  29117. // If we have a parent than these nodes can't be added now (as the parent has not been created
  29118. // yet) and instead the `parentTNode` is responsible for adding it. See
  29119. // `TNode.insertBeforeIndex`
  29120. opCode |= I18nCreateOpCode.APPEND_EAGERLY;
  29121. }
  29122. if (isICU) {
  29123. opCode |= I18nCreateOpCode.COMMENT;
  29124. ensureIcuContainerVisitorLoaded(loadIcuContainerVisitor);
  29125. }
  29126. createOpCodes.push(opCode, text === null ? '' : text);
  29127. // We store `{{?}}` so that when looking at debug `TNodeType.template` we can see where the
  29128. // bindings are.
  29129. const tNode = createTNodeAtIndex(tView, i18nNodeIdx, isICU ? 32 /* TNodeType.Icu */ : 1 /* TNodeType.Text */, text === null ? (ngDevMode ? '{{?}}' : '') : text, null);
  29130. addTNodeAndUpdateInsertBeforeIndex(existingTNodes, tNode);
  29131. const tNodeIdx = tNode.index;
  29132. setCurrentTNode(tNode, false /* Text nodes are self closing */);
  29133. if (parentTNode !== null && rootTNode !== parentTNode) {
  29134. // We are a child of deeper node (rather than a direct child of `i18nStart` instruction.)
  29135. // We have to make sure to add ourselves to the parent.
  29136. setTNodeInsertBeforeIndex(parentTNode, tNodeIdx);
  29137. }
  29138. return tNode;
  29139. }
  29140. /**
  29141. * Processes text node in i18n block.
  29142. *
  29143. * Text nodes can have:
  29144. * - Create instruction in `createOpCodes` for creating the text node.
  29145. * - Allocate spec for text node in i18n range of `LView`
  29146. * - If contains binding:
  29147. * - bindings => allocate space in i18n range of `LView` to store the binding value.
  29148. * - populate `updateOpCodes` with update instructions.
  29149. *
  29150. * @param tView Current `TView`
  29151. * @param rootTNode Root `TNode` of the i18n block. This node determines if the new TNode will
  29152. * be added as part of the `i18nStart` instruction or as part of the
  29153. * `TNode.insertBeforeIndex`.
  29154. * @param existingTNodes internal state for `addTNodeAndUpdateInsertBeforeIndex`.
  29155. * @param createOpCodes Location where the creation OpCodes will be stored.
  29156. * @param lView Current `LView`
  29157. * @param text The translated text (which may contain binding)
  29158. */
  29159. function i18nStartFirstCreatePassProcessTextNode(ast, tView, rootTNode, existingTNodes, createOpCodes, updateOpCodes, lView, text) {
  29160. const hasBinding = text.match(BINDING_REGEXP);
  29161. const tNode = createTNodeAndAddOpCode(tView, rootTNode, existingTNodes, lView, createOpCodes, hasBinding ? null : text, false);
  29162. const index = tNode.index;
  29163. if (hasBinding) {
  29164. generateBindingUpdateOpCodes(updateOpCodes, text, index, null, 0, null);
  29165. }
  29166. ast.push({ kind: 0 /* I18nNodeKind.TEXT */, index });
  29167. }
  29168. /**
  29169. * See `i18nAttributes` above.
  29170. */
  29171. function i18nAttributesFirstPass(tView, index, values) {
  29172. const previousElement = getCurrentTNode();
  29173. const previousElementIndex = previousElement.index;
  29174. const updateOpCodes = [];
  29175. if (ngDevMode) {
  29176. attachDebugGetter(updateOpCodes, i18nUpdateOpCodesToString);
  29177. }
  29178. if (tView.firstCreatePass && tView.data[index] === null) {
  29179. for (let i = 0; i < values.length; i += 2) {
  29180. const attrName = values[i];
  29181. const message = values[i + 1];
  29182. if (message !== '') {
  29183. // Check if attribute value contains an ICU and throw an error if that's the case.
  29184. // ICUs in element attributes are not supported.
  29185. // Note: we intentionally retain the error here by not using `ngDevMode`, because
  29186. // the `value` can change based on the locale and users aren't guaranteed to hit
  29187. // an invalid string while they're developing.
  29188. if (ICU_REGEXP.test(message)) {
  29189. throw new Error(`ICU expressions are not supported in attributes. Message: "${message}".`);
  29190. }
  29191. // i18n attributes that hit this code path are guaranteed to have bindings, because
  29192. // the compiler treats static i18n attributes as regular attribute bindings.
  29193. // Since this may not be the first i18n attribute on this element we need to pass in how
  29194. // many previous bindings there have already been.
  29195. generateBindingUpdateOpCodes(updateOpCodes, message, previousElementIndex, attrName, countBindings(updateOpCodes), null);
  29196. }
  29197. }
  29198. tView.data[index] = updateOpCodes;
  29199. }
  29200. }
  29201. /**
  29202. * Generate the OpCodes to update the bindings of a string.
  29203. *
  29204. * @param updateOpCodes Place where the update opcodes will be stored.
  29205. * @param str The string containing the bindings.
  29206. * @param destinationNode Index of the destination node which will receive the binding.
  29207. * @param attrName Name of the attribute, if the string belongs to an attribute.
  29208. * @param sanitizeFn Sanitization function used to sanitize the string after update, if necessary.
  29209. * @param bindingStart The lView index of the next expression that can be bound via an opCode.
  29210. * @returns The mask value for these bindings
  29211. */
  29212. function generateBindingUpdateOpCodes(updateOpCodes, str, destinationNode, attrName, bindingStart, sanitizeFn) {
  29213. ngDevMode &&
  29214. assertGreaterThanOrEqual(destinationNode, HEADER_OFFSET, 'Index must be in absolute LView offset');
  29215. const maskIndex = updateOpCodes.length; // Location of mask
  29216. const sizeIndex = maskIndex + 1; // location of size for skipping
  29217. updateOpCodes.push(null, null); // Alloc space for mask and size
  29218. const startIndex = maskIndex + 2; // location of first allocation.
  29219. if (ngDevMode) {
  29220. attachDebugGetter(updateOpCodes, i18nUpdateOpCodesToString);
  29221. }
  29222. const textParts = str.split(BINDING_REGEXP);
  29223. let mask = 0;
  29224. for (let j = 0; j < textParts.length; j++) {
  29225. const textValue = textParts[j];
  29226. if (j & 1) {
  29227. // Odd indexes are bindings
  29228. const bindingIndex = bindingStart + parseInt(textValue, 10);
  29229. updateOpCodes.push(-1 - bindingIndex);
  29230. mask = mask | toMaskBit(bindingIndex);
  29231. }
  29232. else if (textValue !== '') {
  29233. // Even indexes are text
  29234. updateOpCodes.push(textValue);
  29235. }
  29236. }
  29237. updateOpCodes.push((destinationNode << 2 /* I18nUpdateOpCode.SHIFT_REF */) |
  29238. (attrName ? 1 /* I18nUpdateOpCode.Attr */ : 0 /* I18nUpdateOpCode.Text */));
  29239. if (attrName) {
  29240. updateOpCodes.push(attrName, sanitizeFn);
  29241. }
  29242. updateOpCodes[maskIndex] = mask;
  29243. updateOpCodes[sizeIndex] = updateOpCodes.length - startIndex;
  29244. return mask;
  29245. }
  29246. /**
  29247. * Count the number of bindings in the given `opCodes`.
  29248. *
  29249. * It could be possible to speed this up, by passing the number of bindings found back from
  29250. * `generateBindingUpdateOpCodes()` to `i18nAttributesFirstPass()` but this would then require more
  29251. * complexity in the code and/or transient objects to be created.
  29252. *
  29253. * Since this function is only called once when the template is instantiated, is trivial in the
  29254. * first instance (since `opCodes` will be an empty array), and it is not common for elements to
  29255. * contain multiple i18n bound attributes, it seems like this is a reasonable compromise.
  29256. */
  29257. function countBindings(opCodes) {
  29258. let count = 0;
  29259. for (let i = 0; i < opCodes.length; i++) {
  29260. const opCode = opCodes[i];
  29261. // Bindings are negative numbers.
  29262. if (typeof opCode === 'number' && opCode < 0) {
  29263. count++;
  29264. }
  29265. }
  29266. return count;
  29267. }
  29268. /**
  29269. * Convert binding index to mask bit.
  29270. *
  29271. * Each index represents a single bit on the bit-mask. Because bit-mask only has 32 bits, we make
  29272. * the 32nd bit share all masks for all bindings higher than 32. Since it is extremely rare to
  29273. * have more than 32 bindings this will be hit very rarely. The downside of hitting this corner
  29274. * case is that we will execute binding code more often than necessary. (penalty of performance)
  29275. */
  29276. function toMaskBit(bindingIndex) {
  29277. return 1 << Math.min(bindingIndex, 31);
  29278. }
  29279. /**
  29280. * Removes everything inside the sub-templates of a message.
  29281. */
  29282. function removeInnerTemplateTranslation(message) {
  29283. let match;
  29284. let res = '';
  29285. let index = 0;
  29286. let inTemplate = false;
  29287. let tagMatched;
  29288. while ((match = SUBTEMPLATE_REGEXP.exec(message)) !== null) {
  29289. if (!inTemplate) {
  29290. res += message.substring(index, match.index + match[0].length);
  29291. tagMatched = match[1];
  29292. inTemplate = true;
  29293. }
  29294. else {
  29295. if (match[0] === `${MARKER}/*${tagMatched}${MARKER}`) {
  29296. index = match.index;
  29297. inTemplate = false;
  29298. }
  29299. }
  29300. }
  29301. ngDevMode &&
  29302. assertEqual(inTemplate, false, `Tag mismatch: unable to find the end of the sub-template in the translation "${message}"`);
  29303. res += message.slice(index);
  29304. return res;
  29305. }
  29306. /**
  29307. * Extracts a part of a message and removes the rest.
  29308. *
  29309. * This method is used for extracting a part of the message associated with a template. A
  29310. * translated message can span multiple templates.
  29311. *
  29312. * Example:
  29313. * ```html
  29314. * <div i18n>Translate <span *ngIf>me</span>!</div>
  29315. * ```
  29316. *
  29317. * @param message The message to crop
  29318. * @param subTemplateIndex Index of the sub-template to extract. If undefined it returns the
  29319. * external template and removes all sub-templates.
  29320. */
  29321. function getTranslationForTemplate(message, subTemplateIndex) {
  29322. if (isRootTemplateMessage(subTemplateIndex)) {
  29323. // We want the root template message, ignore all sub-templates
  29324. return removeInnerTemplateTranslation(message);
  29325. }
  29326. else {
  29327. // We want a specific sub-template
  29328. const start = message.indexOf(`:${subTemplateIndex}${MARKER}`) + 2 + subTemplateIndex.toString().length;
  29329. const end = message.search(new RegExp(`${MARKER}\\/\\*\\d+:${subTemplateIndex}${MARKER}`));
  29330. return removeInnerTemplateTranslation(message.substring(start, end));
  29331. }
  29332. }
  29333. /**
  29334. * Generate the OpCodes for ICU expressions.
  29335. *
  29336. * @param icuExpression
  29337. * @param index Index where the anchor is stored and an optional `TIcuContainerNode`
  29338. * - `lView[anchorIdx]` points to a `Comment` node representing the anchor for the ICU.
  29339. * - `tView.data[anchorIdx]` points to the `TIcuContainerNode` if ICU is root (`null` otherwise)
  29340. */
  29341. function icuStart(ast, tView, lView, updateOpCodes, parentIdx, icuExpression, anchorIdx) {
  29342. ngDevMode && assertDefined(icuExpression, 'ICU expression must be defined');
  29343. let bindingMask = 0;
  29344. const tIcu = {
  29345. type: icuExpression.type,
  29346. currentCaseLViewIndex: allocExpando(tView, lView, 1, null),
  29347. anchorIdx,
  29348. cases: [],
  29349. create: [],
  29350. remove: [],
  29351. update: [],
  29352. };
  29353. addUpdateIcuSwitch(updateOpCodes, icuExpression, anchorIdx);
  29354. setTIcu(tView, anchorIdx, tIcu);
  29355. const values = icuExpression.values;
  29356. const cases = [];
  29357. for (let i = 0; i < values.length; i++) {
  29358. // Each value is an array of strings & other ICU expressions
  29359. const valueArr = values[i];
  29360. const nestedIcus = [];
  29361. for (let j = 0; j < valueArr.length; j++) {
  29362. const value = valueArr[j];
  29363. if (typeof value !== 'string') {
  29364. // It is an nested ICU expression
  29365. const icuIndex = nestedIcus.push(value) - 1;
  29366. // Replace nested ICU expression by a comment node
  29367. valueArr[j] = `<!--�${icuIndex}�-->`;
  29368. }
  29369. }
  29370. const caseAst = [];
  29371. cases.push(caseAst);
  29372. bindingMask =
  29373. parseIcuCase(caseAst, tView, tIcu, lView, updateOpCodes, parentIdx, icuExpression.cases[i], valueArr.join(''), nestedIcus) | bindingMask;
  29374. }
  29375. if (bindingMask) {
  29376. addUpdateIcuUpdate(updateOpCodes, bindingMask, anchorIdx);
  29377. }
  29378. ast.push({
  29379. kind: 3 /* I18nNodeKind.ICU */,
  29380. index: anchorIdx,
  29381. cases,
  29382. currentCaseLViewIndex: tIcu.currentCaseLViewIndex,
  29383. });
  29384. }
  29385. /**
  29386. * Parses text containing an ICU expression and produces a JSON object for it.
  29387. * Original code from closure library, modified for Angular.
  29388. *
  29389. * @param pattern Text containing an ICU expression that needs to be parsed.
  29390. *
  29391. */
  29392. function parseICUBlock(pattern) {
  29393. const cases = [];
  29394. const values = [];
  29395. let icuType = 1 /* IcuType.plural */;
  29396. let mainBinding = 0;
  29397. pattern = pattern.replace(ICU_BLOCK_REGEXP, function (str, binding, type) {
  29398. if (type === 'select') {
  29399. icuType = 0 /* IcuType.select */;
  29400. }
  29401. else {
  29402. icuType = 1 /* IcuType.plural */;
  29403. }
  29404. mainBinding = parseInt(binding.slice(1), 10);
  29405. return '';
  29406. });
  29407. const parts = i18nParseTextIntoPartsAndICU(pattern);
  29408. // Looking for (key block)+ sequence. One of the keys has to be "other".
  29409. for (let pos = 0; pos < parts.length;) {
  29410. let key = parts[pos++].trim();
  29411. if (icuType === 1 /* IcuType.plural */) {
  29412. // Key can be "=x", we just want "x"
  29413. key = key.replace(/\s*(?:=)?(\w+)\s*/, '$1');
  29414. }
  29415. if (key.length) {
  29416. cases.push(key);
  29417. }
  29418. const blocks = i18nParseTextIntoPartsAndICU(parts[pos++]);
  29419. if (cases.length > values.length) {
  29420. values.push(blocks);
  29421. }
  29422. }
  29423. // TODO(ocombe): support ICU expressions in attributes, see #21615
  29424. return { type: icuType, mainBinding: mainBinding, cases, values };
  29425. }
  29426. /**
  29427. * Breaks pattern into strings and top level {...} blocks.
  29428. * Can be used to break a message into text and ICU expressions, or to break an ICU expression
  29429. * into keys and cases. Original code from closure library, modified for Angular.
  29430. *
  29431. * @param pattern (sub)Pattern to be broken.
  29432. * @returns An `Array<string|IcuExpression>` where:
  29433. * - odd positions: `string` => text between ICU expressions
  29434. * - even positions: `ICUExpression` => ICU expression parsed into `ICUExpression` record.
  29435. */
  29436. function i18nParseTextIntoPartsAndICU(pattern) {
  29437. if (!pattern) {
  29438. return [];
  29439. }
  29440. let prevPos = 0;
  29441. const braceStack = [];
  29442. const results = [];
  29443. const braces = /[{}]/g;
  29444. // lastIndex doesn't get set to 0 so we have to.
  29445. braces.lastIndex = 0;
  29446. let match;
  29447. while ((match = braces.exec(pattern))) {
  29448. const pos = match.index;
  29449. if (match[0] == '}') {
  29450. braceStack.pop();
  29451. if (braceStack.length == 0) {
  29452. // End of the block.
  29453. const block = pattern.substring(prevPos, pos);
  29454. if (ICU_BLOCK_REGEXP.test(block)) {
  29455. results.push(parseICUBlock(block));
  29456. }
  29457. else {
  29458. results.push(block);
  29459. }
  29460. prevPos = pos + 1;
  29461. }
  29462. }
  29463. else {
  29464. if (braceStack.length == 0) {
  29465. const substring = pattern.substring(prevPos, pos);
  29466. results.push(substring);
  29467. prevPos = pos + 1;
  29468. }
  29469. braceStack.push('{');
  29470. }
  29471. }
  29472. const substring = pattern.substring(prevPos);
  29473. results.push(substring);
  29474. return results;
  29475. }
  29476. /**
  29477. * Parses a node, its children and its siblings, and generates the mutate & update OpCodes.
  29478. *
  29479. */
  29480. function parseIcuCase(ast, tView, tIcu, lView, updateOpCodes, parentIdx, caseName, unsafeCaseHtml, nestedIcus) {
  29481. const create = [];
  29482. const remove = [];
  29483. const update = [];
  29484. if (ngDevMode) {
  29485. attachDebugGetter(create, icuCreateOpCodesToString);
  29486. attachDebugGetter(remove, i18nRemoveOpCodesToString);
  29487. attachDebugGetter(update, i18nUpdateOpCodesToString);
  29488. }
  29489. tIcu.cases.push(caseName);
  29490. tIcu.create.push(create);
  29491. tIcu.remove.push(remove);
  29492. tIcu.update.push(update);
  29493. const inertBodyHelper = getInertBodyHelper(getDocument());
  29494. const inertBodyElement = inertBodyHelper.getInertBodyElement(unsafeCaseHtml);
  29495. ngDevMode && assertDefined(inertBodyElement, 'Unable to generate inert body element');
  29496. const inertRootNode = getTemplateContent(inertBodyElement) || inertBodyElement;
  29497. if (inertRootNode) {
  29498. return walkIcuTree(ast, tView, tIcu, lView, updateOpCodes, create, remove, update, inertRootNode, parentIdx, nestedIcus, 0);
  29499. }
  29500. else {
  29501. return 0;
  29502. }
  29503. }
  29504. function walkIcuTree(ast, tView, tIcu, lView, sharedUpdateOpCodes, create, remove, update, parentNode, parentIdx, nestedIcus, depth) {
  29505. let bindingMask = 0;
  29506. let currentNode = parentNode.firstChild;
  29507. while (currentNode) {
  29508. const newIndex = allocExpando(tView, lView, 1, null);
  29509. switch (currentNode.nodeType) {
  29510. case Node.ELEMENT_NODE:
  29511. const element = currentNode;
  29512. const tagName = element.tagName.toLowerCase();
  29513. if (VALID_ELEMENTS.hasOwnProperty(tagName)) {
  29514. addCreateNodeAndAppend(create, ELEMENT_MARKER, tagName, parentIdx, newIndex);
  29515. tView.data[newIndex] = tagName;
  29516. const elAttrs = element.attributes;
  29517. for (let i = 0; i < elAttrs.length; i++) {
  29518. const attr = elAttrs.item(i);
  29519. const lowerAttrName = attr.name.toLowerCase();
  29520. const hasBinding = !!attr.value.match(BINDING_REGEXP);
  29521. // we assume the input string is safe, unless it's using a binding
  29522. if (hasBinding) {
  29523. if (VALID_ATTRS.hasOwnProperty(lowerAttrName)) {
  29524. if (URI_ATTRS[lowerAttrName]) {
  29525. generateBindingUpdateOpCodes(update, attr.value, newIndex, attr.name, 0, _sanitizeUrl);
  29526. }
  29527. else {
  29528. generateBindingUpdateOpCodes(update, attr.value, newIndex, attr.name, 0, null);
  29529. }
  29530. }
  29531. else {
  29532. ngDevMode &&
  29533. console.warn(`WARNING: ignoring unsafe attribute value ` +
  29534. `${lowerAttrName} on element ${tagName} ` +
  29535. `(see ${XSS_SECURITY_URL})`);
  29536. }
  29537. }
  29538. else {
  29539. addCreateAttribute(create, newIndex, attr);
  29540. }
  29541. }
  29542. const elementNode = {
  29543. kind: 1 /* I18nNodeKind.ELEMENT */,
  29544. index: newIndex,
  29545. children: [],
  29546. };
  29547. ast.push(elementNode);
  29548. // Parse the children of this node (if any)
  29549. bindingMask =
  29550. walkIcuTree(elementNode.children, tView, tIcu, lView, sharedUpdateOpCodes, create, remove, update, currentNode, newIndex, nestedIcus, depth + 1) | bindingMask;
  29551. addRemoveNode(remove, newIndex, depth);
  29552. }
  29553. break;
  29554. case Node.TEXT_NODE:
  29555. const value = currentNode.textContent || '';
  29556. const hasBinding = value.match(BINDING_REGEXP);
  29557. addCreateNodeAndAppend(create, null, hasBinding ? '' : value, parentIdx, newIndex);
  29558. addRemoveNode(remove, newIndex, depth);
  29559. if (hasBinding) {
  29560. bindingMask =
  29561. generateBindingUpdateOpCodes(update, value, newIndex, null, 0, null) | bindingMask;
  29562. }
  29563. ast.push({
  29564. kind: 0 /* I18nNodeKind.TEXT */,
  29565. index: newIndex,
  29566. });
  29567. break;
  29568. case Node.COMMENT_NODE:
  29569. // Check if the comment node is a placeholder for a nested ICU
  29570. const isNestedIcu = NESTED_ICU.exec(currentNode.textContent || '');
  29571. if (isNestedIcu) {
  29572. const nestedIcuIndex = parseInt(isNestedIcu[1], 10);
  29573. const icuExpression = nestedIcus[nestedIcuIndex];
  29574. // Create the comment node that will anchor the ICU expression
  29575. addCreateNodeAndAppend(create, ICU_MARKER, ngDevMode ? `nested ICU ${nestedIcuIndex}` : '', parentIdx, newIndex);
  29576. icuStart(ast, tView, lView, sharedUpdateOpCodes, parentIdx, icuExpression, newIndex);
  29577. addRemoveNestedIcu(remove, newIndex, depth);
  29578. }
  29579. break;
  29580. }
  29581. currentNode = currentNode.nextSibling;
  29582. }
  29583. return bindingMask;
  29584. }
  29585. function addRemoveNode(remove, index, depth) {
  29586. if (depth === 0) {
  29587. remove.push(index);
  29588. }
  29589. }
  29590. function addRemoveNestedIcu(remove, index, depth) {
  29591. if (depth === 0) {
  29592. remove.push(~index); // remove ICU at `index`
  29593. remove.push(index); // remove ICU comment at `index`
  29594. }
  29595. }
  29596. function addUpdateIcuSwitch(update, icuExpression, index) {
  29597. update.push(toMaskBit(icuExpression.mainBinding), 2, -1 - icuExpression.mainBinding, (index << 2 /* I18nUpdateOpCode.SHIFT_REF */) | 2 /* I18nUpdateOpCode.IcuSwitch */);
  29598. }
  29599. function addUpdateIcuUpdate(update, bindingMask, index) {
  29600. update.push(bindingMask, 1, (index << 2 /* I18nUpdateOpCode.SHIFT_REF */) | 3 /* I18nUpdateOpCode.IcuUpdate */);
  29601. }
  29602. function addCreateNodeAndAppend(create, marker, text, appendToParentIdx, createAtIdx) {
  29603. if (marker !== null) {
  29604. create.push(marker);
  29605. }
  29606. create.push(text, createAtIdx, icuCreateOpCode(0 /* IcuCreateOpCode.AppendChild */, appendToParentIdx, createAtIdx));
  29607. }
  29608. function addCreateAttribute(create, newIndex, attr) {
  29609. create.push((newIndex << 1 /* IcuCreateOpCode.SHIFT_REF */) | 1 /* IcuCreateOpCode.Attr */, attr.name, attr.value);
  29610. }
  29611. // i18nPostprocess consts
  29612. const ROOT_TEMPLATE_ID = 0;
  29613. const PP_MULTI_VALUE_PLACEHOLDERS_REGEXP = /\[(�.+?�?)\]/;
  29614. const PP_PLACEHOLDERS_REGEXP = /\[(�.+?�?)\]|(�\/?\*\d+:\d+�)/g;
  29615. const PP_ICU_VARS_REGEXP = /({\s*)(VAR_(PLURAL|SELECT)(_\d+)?)(\s*,)/g;
  29616. const PP_ICU_PLACEHOLDERS_REGEXP = /{([A-Z0-9_]+)}/g;
  29617. const PP_ICUS_REGEXP = /�I18N_EXP_(ICU(_\d+)?)�/g;
  29618. const PP_CLOSE_TEMPLATE_REGEXP = /\/\*/;
  29619. const PP_TEMPLATE_ID_REGEXP = /\d+\:(\d+)/;
  29620. /**
  29621. * Handles message string post-processing for internationalization.
  29622. *
  29623. * Handles message string post-processing by transforming it from intermediate
  29624. * format (that might contain some markers that we need to replace) to the final
  29625. * form, consumable by i18nStart instruction. Post processing steps include:
  29626. *
  29627. * 1. Resolve all multi-value cases (like [�*1:1��#2:1�|�#4:1�|�5�])
  29628. * 2. Replace all ICU vars (like "VAR_PLURAL")
  29629. * 3. Replace all placeholders used inside ICUs in a form of {PLACEHOLDER}
  29630. * 4. Replace all ICU references with corresponding values (like �ICU_EXP_ICU_1�)
  29631. * in case multiple ICUs have the same placeholder name
  29632. *
  29633. * @param message Raw translation string for post processing
  29634. * @param replacements Set of replacements that should be applied
  29635. *
  29636. * @returns Transformed string that can be consumed by i18nStart instruction
  29637. *
  29638. * @codeGenApi
  29639. */
  29640. function i18nPostprocess(message, replacements = {}) {
  29641. /**
  29642. * Step 1: resolve all multi-value placeholders like [�#5�|�*1:1��#2:1�|�#4:1�]
  29643. *
  29644. * Note: due to the way we process nested templates (BFS), multi-value placeholders are typically
  29645. * grouped by templates, for example: [�#5�|�#6�|�#1:1�|�#3:2�] where �#5� and �#6� belong to root
  29646. * template, �#1:1� belong to nested template with index 1 and �#1:2� - nested template with index
  29647. * 3. However in real templates the order might be different: i.e. �#1:1� and/or �#3:2� may go in
  29648. * front of �#6�. The post processing step restores the right order by keeping track of the
  29649. * template id stack and looks for placeholders that belong to the currently active template.
  29650. */
  29651. let result = message;
  29652. if (PP_MULTI_VALUE_PLACEHOLDERS_REGEXP.test(message)) {
  29653. const matches = {};
  29654. const templateIdsStack = [ROOT_TEMPLATE_ID];
  29655. result = result.replace(PP_PLACEHOLDERS_REGEXP, (m, phs, tmpl) => {
  29656. const content = phs || tmpl;
  29657. const placeholders = matches[content] || [];
  29658. if (!placeholders.length) {
  29659. content.split('|').forEach((placeholder) => {
  29660. const match = placeholder.match(PP_TEMPLATE_ID_REGEXP);
  29661. const templateId = match ? parseInt(match[1], 10) : ROOT_TEMPLATE_ID;
  29662. const isCloseTemplateTag = PP_CLOSE_TEMPLATE_REGEXP.test(placeholder);
  29663. placeholders.push([templateId, isCloseTemplateTag, placeholder]);
  29664. });
  29665. matches[content] = placeholders;
  29666. }
  29667. if (!placeholders.length) {
  29668. throw new Error(`i18n postprocess: unmatched placeholder - ${content}`);
  29669. }
  29670. const currentTemplateId = templateIdsStack[templateIdsStack.length - 1];
  29671. let idx = 0;
  29672. // find placeholder index that matches current template id
  29673. for (let i = 0; i < placeholders.length; i++) {
  29674. if (placeholders[i][0] === currentTemplateId) {
  29675. idx = i;
  29676. break;
  29677. }
  29678. }
  29679. // update template id stack based on the current tag extracted
  29680. const [templateId, isCloseTemplateTag, placeholder] = placeholders[idx];
  29681. if (isCloseTemplateTag) {
  29682. templateIdsStack.pop();
  29683. }
  29684. else if (currentTemplateId !== templateId) {
  29685. templateIdsStack.push(templateId);
  29686. }
  29687. // remove processed tag from the list
  29688. placeholders.splice(idx, 1);
  29689. return placeholder;
  29690. });
  29691. }
  29692. // return current result if no replacements specified
  29693. if (!Object.keys(replacements).length) {
  29694. return result;
  29695. }
  29696. /**
  29697. * Step 2: replace all ICU vars (like "VAR_PLURAL")
  29698. */
  29699. result = result.replace(PP_ICU_VARS_REGEXP, (match, start, key, _type, _idx, end) => {
  29700. return replacements.hasOwnProperty(key) ? `${start}${replacements[key]}${end}` : match;
  29701. });
  29702. /**
  29703. * Step 3: replace all placeholders used inside ICUs in a form of {PLACEHOLDER}
  29704. */
  29705. result = result.replace(PP_ICU_PLACEHOLDERS_REGEXP, (match, key) => {
  29706. return replacements.hasOwnProperty(key) ? replacements[key] : match;
  29707. });
  29708. /**
  29709. * Step 4: replace all ICU references with corresponding values (like �ICU_EXP_ICU_1�) in case
  29710. * multiple ICUs have the same placeholder name
  29711. */
  29712. result = result.replace(PP_ICUS_REGEXP, (match, key) => {
  29713. if (replacements.hasOwnProperty(key)) {
  29714. const list = replacements[key];
  29715. if (!list.length) {
  29716. throw new Error(`i18n postprocess: unmatched ICU - ${match} with key: ${key}`);
  29717. }
  29718. return list.shift();
  29719. }
  29720. return match;
  29721. });
  29722. return result;
  29723. }
  29724. /**
  29725. * Marks a block of text as translatable.
  29726. *
  29727. * The instructions `i18nStart` and `i18nEnd` mark the translation block in the template.
  29728. * The translation `message` is the value which is locale specific. The translation string may
  29729. * contain placeholders which associate inner elements and sub-templates within the translation.
  29730. *
  29731. * The translation `message` placeholders are:
  29732. * - `�{index}(:{block})�`: *Binding Placeholder*: Marks a location where an expression will be
  29733. * interpolated into. The placeholder `index` points to the expression binding index. An optional
  29734. * `block` that matches the sub-template in which it was declared.
  29735. * - `�#{index}(:{block})�`/`�/#{index}(:{block})�`: *Element Placeholder*: Marks the beginning
  29736. * and end of DOM element that were embedded in the original translation block. The placeholder
  29737. * `index` points to the element index in the template instructions set. An optional `block` that
  29738. * matches the sub-template in which it was declared.
  29739. * - `�*{index}:{block}�`/`�/*{index}:{block}�`: *Sub-template Placeholder*: Sub-templates must be
  29740. * split up and translated separately in each angular template function. The `index` points to the
  29741. * `template` instruction index. A `block` that matches the sub-template in which it was declared.
  29742. *
  29743. * @param index A unique index of the translation in the static block.
  29744. * @param messageIndex An index of the translation message from the `def.consts` array.
  29745. * @param subTemplateIndex Optional sub-template index in the `message`.
  29746. *
  29747. * @codeGenApi
  29748. */
  29749. function ɵɵi18nStart(index, messageIndex, subTemplateIndex = -1) {
  29750. const tView = getTView();
  29751. const lView = getLView();
  29752. const adjustedIndex = HEADER_OFFSET + index;
  29753. ngDevMode && assertDefined(tView, `tView should be defined`);
  29754. const message = getConstant(tView.consts, messageIndex);
  29755. const parentTNode = getCurrentParentTNode();
  29756. if (tView.firstCreatePass) {
  29757. i18nStartFirstCreatePass(tView, parentTNode === null ? 0 : parentTNode.index, lView, adjustedIndex, message, subTemplateIndex);
  29758. }
  29759. // Set a flag that this LView has i18n blocks.
  29760. // The flag is later used to determine whether this component should
  29761. // be hydrated (currently hydration is not supported for i18n blocks).
  29762. if (tView.type === 2 /* TViewType.Embedded */) {
  29763. // Annotate host component's LView (not embedded view's LView),
  29764. // since hydration can be skipped on per-component basis only.
  29765. const componentLView = lView[DECLARATION_COMPONENT_VIEW];
  29766. componentLView[FLAGS] |= 32 /* LViewFlags.HasI18n */;
  29767. }
  29768. else {
  29769. lView[FLAGS] |= 32 /* LViewFlags.HasI18n */;
  29770. }
  29771. const tI18n = tView.data[adjustedIndex];
  29772. const sameViewParentTNode = parentTNode === lView[T_HOST] ? null : parentTNode;
  29773. const parentRNode = getClosestRElement(tView, sameViewParentTNode, lView);
  29774. // If `parentTNode` is an `ElementContainer` than it has `<!--ng-container--->`.
  29775. // When we do inserts we have to make sure to insert in front of `<!--ng-container--->`.
  29776. const insertInFrontOf = parentTNode && parentTNode.type & 8 /* TNodeType.ElementContainer */ ? lView[parentTNode.index] : null;
  29777. prepareI18nBlockForHydration(lView, adjustedIndex, parentTNode, subTemplateIndex);
  29778. applyCreateOpCodes(lView, tI18n.create, parentRNode, insertInFrontOf);
  29779. setInI18nBlock(true);
  29780. }
  29781. /**
  29782. * Translates a translation block marked by `i18nStart` and `i18nEnd`. It inserts the text/ICU nodes
  29783. * into the render tree, moves the placeholder nodes and removes the deleted nodes.
  29784. *
  29785. * @codeGenApi
  29786. */
  29787. function ɵɵi18nEnd() {
  29788. setInI18nBlock(false);
  29789. }
  29790. /**
  29791. *
  29792. * Use this instruction to create a translation block that doesn't contain any placeholder.
  29793. * It calls both {@link i18nStart} and {@link i18nEnd} in one instruction.
  29794. *
  29795. * The translation `message` is the value which is locale specific. The translation string may
  29796. * contain placeholders which associate inner elements and sub-templates within the translation.
  29797. *
  29798. * The translation `message` placeholders are:
  29799. * - `�{index}(:{block})�`: *Binding Placeholder*: Marks a location where an expression will be
  29800. * interpolated into. The placeholder `index` points to the expression binding index. An optional
  29801. * `block` that matches the sub-template in which it was declared.
  29802. * - `�#{index}(:{block})�`/`�/#{index}(:{block})�`: *Element Placeholder*: Marks the beginning
  29803. * and end of DOM element that were embedded in the original translation block. The placeholder
  29804. * `index` points to the element index in the template instructions set. An optional `block` that
  29805. * matches the sub-template in which it was declared.
  29806. * - `�*{index}:{block}�`/`�/*{index}:{block}�`: *Sub-template Placeholder*: Sub-templates must be
  29807. * split up and translated separately in each angular template function. The `index` points to the
  29808. * `template` instruction index. A `block` that matches the sub-template in which it was declared.
  29809. *
  29810. * @param index A unique index of the translation in the static block.
  29811. * @param messageIndex An index of the translation message from the `def.consts` array.
  29812. * @param subTemplateIndex Optional sub-template index in the `message`.
  29813. *
  29814. * @codeGenApi
  29815. */
  29816. function ɵɵi18n(index, messageIndex, subTemplateIndex) {
  29817. ɵɵi18nStart(index, messageIndex, subTemplateIndex);
  29818. ɵɵi18nEnd();
  29819. }
  29820. /**
  29821. * Marks a list of attributes as translatable.
  29822. *
  29823. * @param index A unique index in the static block
  29824. * @param values
  29825. *
  29826. * @codeGenApi
  29827. */
  29828. function ɵɵi18nAttributes(index, attrsIndex) {
  29829. const tView = getTView();
  29830. ngDevMode && assertDefined(tView, `tView should be defined`);
  29831. const attrs = getConstant(tView.consts, attrsIndex);
  29832. i18nAttributesFirstPass(tView, index + HEADER_OFFSET, attrs);
  29833. }
  29834. /**
  29835. * Stores the values of the bindings during each update cycle in order to determine if we need to
  29836. * update the translated nodes.
  29837. *
  29838. * @param value The binding's value
  29839. * @returns This function returns itself so that it may be chained
  29840. * (e.g. `i18nExp(ctx.name)(ctx.title)`)
  29841. *
  29842. * @codeGenApi
  29843. */
  29844. function ɵɵi18nExp(value) {
  29845. const lView = getLView();
  29846. setMaskBit(bindingUpdated(lView, nextBindingIndex(), value));
  29847. return ɵɵi18nExp;
  29848. }
  29849. /**
  29850. * Updates a translation block or an i18n attribute when the bindings have changed.
  29851. *
  29852. * @param index Index of either {@link i18nStart} (translation block) or {@link i18nAttributes}
  29853. * (i18n attribute) on which it should update the content.
  29854. *
  29855. * @codeGenApi
  29856. */
  29857. function ɵɵi18nApply(index) {
  29858. applyI18n(getTView(), getLView(), index + HEADER_OFFSET);
  29859. }
  29860. /**
  29861. * Handles message string post-processing for internationalization.
  29862. *
  29863. * Handles message string post-processing by transforming it from intermediate
  29864. * format (that might contain some markers that we need to replace) to the final
  29865. * form, consumable by i18nStart instruction. Post processing steps include:
  29866. *
  29867. * 1. Resolve all multi-value cases (like [�*1:1��#2:1�|�#4:1�|�5�])
  29868. * 2. Replace all ICU vars (like "VAR_PLURAL")
  29869. * 3. Replace all placeholders used inside ICUs in a form of {PLACEHOLDER}
  29870. * 4. Replace all ICU references with corresponding values (like �ICU_EXP_ICU_1�)
  29871. * in case multiple ICUs have the same placeholder name
  29872. *
  29873. * @param message Raw translation string for post processing
  29874. * @param replacements Set of replacements that should be applied
  29875. *
  29876. * @returns Transformed string that can be consumed by i18nStart instruction
  29877. *
  29878. * @codeGenApi
  29879. */
  29880. function ɵɵi18nPostprocess(message, replacements = {}) {
  29881. return i18nPostprocess(message, replacements);
  29882. }
  29883. /**
  29884. * Wraps an event listener with a function that marks ancestors dirty and prevents default behavior,
  29885. * if applicable.
  29886. *
  29887. * @param tNode The TNode associated with this listener
  29888. * @param lView The LView that contains this listener
  29889. * @param listenerFn The listener function to call
  29890. * @param wrapWithPreventDefault Whether or not to prevent default behavior
  29891. * (the procedural renderer does this already, so in those cases, we should skip)
  29892. */
  29893. function wrapListener(tNode, lView, listenerFn) {
  29894. // Note: we are performing most of the work in the listener function itself
  29895. // to optimize listener registration.
  29896. return function wrapListenerIn_markDirtyAndPreventDefault(e) {
  29897. // Ivy uses `Function` as a special token that allows us to unwrap the function
  29898. // so that it can be invoked programmatically by `DebugNode.triggerEventHandler`.
  29899. if (e === Function) {
  29900. return listenerFn;
  29901. }
  29902. // In order to be backwards compatible with View Engine, events on component host nodes
  29903. // must also mark the component view itself dirty (i.e. the view that it owns).
  29904. const startView = isComponentHost(tNode) ? getComponentLViewByIndex(tNode.index, lView) : lView;
  29905. markViewDirty(startView, 5 /* NotificationSource.Listener */);
  29906. const context = lView[CONTEXT];
  29907. let result = executeListenerWithErrorHandling(lView, context, listenerFn, e);
  29908. // A just-invoked listener function might have coalesced listeners so we need to check for
  29909. // their presence and invoke as needed.
  29910. let nextListenerFn = wrapListenerIn_markDirtyAndPreventDefault.__ngNextListenerFn__;
  29911. while (nextListenerFn) {
  29912. // We should prevent default if any of the listeners explicitly return false
  29913. result = executeListenerWithErrorHandling(lView, context, nextListenerFn, e) && result;
  29914. nextListenerFn = nextListenerFn.__ngNextListenerFn__;
  29915. }
  29916. return result;
  29917. };
  29918. }
  29919. function executeListenerWithErrorHandling(lView, context, listenerFn, e) {
  29920. const prevConsumer = setActiveConsumer(null);
  29921. try {
  29922. profiler(6 /* ProfilerEvent.OutputStart */, context, listenerFn);
  29923. // Only explicitly returning false from a listener should preventDefault
  29924. return listenerFn(e) !== false;
  29925. }
  29926. catch (error) {
  29927. // TODO(atscott): This should report to the application error handler, not the ErrorHandler on LView injector
  29928. handleError(lView, error);
  29929. return false;
  29930. }
  29931. finally {
  29932. profiler(7 /* ProfilerEvent.OutputEnd */, context, listenerFn);
  29933. setActiveConsumer(prevConsumer);
  29934. }
  29935. }
  29936. /** Handles an error thrown in an LView. */
  29937. function handleError(lView, error) {
  29938. const injector = lView[INJECTOR];
  29939. const errorHandler = injector ? injector.get(ErrorHandler, null) : null;
  29940. errorHandler && errorHandler.handleError(error);
  29941. }
  29942. function listenToOutput(tNode, lView, directiveIndex, lookupName, eventName, listenerFn) {
  29943. ngDevMode && assertIndexInRange(lView, directiveIndex);
  29944. const instance = lView[directiveIndex];
  29945. const tView = lView[TVIEW];
  29946. const def = tView.data[directiveIndex];
  29947. const propertyName = def.outputs[lookupName];
  29948. const output = instance[propertyName];
  29949. if (ngDevMode && !isOutputSubscribable(output)) {
  29950. throw new Error(`@Output ${propertyName} not initialized in '${instance.constructor.name}'.`);
  29951. }
  29952. // TODO(pk): introduce utility to store cleanup or find a different way of sharing code with listener
  29953. const tCleanup = tView.firstCreatePass ? getOrCreateTViewCleanup(tView) : null;
  29954. const lCleanup = getOrCreateLViewCleanup(lView);
  29955. const subscription = output.subscribe(listenerFn);
  29956. const idx = lCleanup.length;
  29957. lCleanup.push(listenerFn, subscription);
  29958. tCleanup && tCleanup.push(eventName, tNode.index, idx, -(idx + 1));
  29959. }
  29960. /**
  29961. * Whether the given value represents a subscribable output.
  29962. *
  29963. * For example, an `EventEmitter, a `Subject`, an `Observable` or an
  29964. * `OutputEmitter`.
  29965. */
  29966. function isOutputSubscribable(value) {
  29967. return (value != null && typeof value.subscribe === 'function');
  29968. }
  29969. /**
  29970. * Adds an event listener to the current node.
  29971. *
  29972. * If an output exists on one of the node's directives, it also subscribes to the output
  29973. * and saves the subscription for later cleanup.
  29974. *
  29975. * @param eventName Name of the event
  29976. * @param listenerFn The function to be called when event emits
  29977. * @param useCapture Whether or not to use capture in event listener - this argument is a reminder
  29978. * from the Renderer3 infrastructure and should be removed from the instruction arguments
  29979. * @param eventTargetResolver Function that returns global target information in case this listener
  29980. * should be attached to a global object like window, document or body
  29981. *
  29982. * @codeGenApi
  29983. */
  29984. function ɵɵlistener(eventName, listenerFn, useCapture, eventTargetResolver) {
  29985. const lView = getLView();
  29986. const tView = getTView();
  29987. const tNode = getCurrentTNode();
  29988. listenerInternal(tView, lView, lView[RENDERER], tNode, eventName, listenerFn, eventTargetResolver);
  29989. return ɵɵlistener;
  29990. }
  29991. /**
  29992. * Registers a synthetic host listener (e.g. `(@foo.start)`) on a component or directive.
  29993. *
  29994. * This instruction is for compatibility purposes and is designed to ensure that a
  29995. * synthetic host listener (e.g. `@HostListener('@foo.start')`) properly gets rendered
  29996. * in the component's renderer. Normally all host listeners are evaluated with the
  29997. * parent component's renderer, but, in the case of animation @triggers, they need
  29998. * to be evaluated with the sub component's renderer (because that's where the
  29999. * animation triggers are defined).
  30000. *
  30001. * Do not use this instruction as a replacement for `listener`. This instruction
  30002. * only exists to ensure compatibility with the ViewEngine's host binding behavior.
  30003. *
  30004. * @param eventName Name of the event
  30005. * @param listenerFn The function to be called when event emits
  30006. * @param useCapture Whether or not to use capture in event listener
  30007. * @param eventTargetResolver Function that returns global target information in case this listener
  30008. * should be attached to a global object like window, document or body
  30009. *
  30010. * @codeGenApi
  30011. */
  30012. function ɵɵsyntheticHostListener(eventName, listenerFn) {
  30013. const tNode = getCurrentTNode();
  30014. const lView = getLView();
  30015. const tView = getTView();
  30016. const currentDef = getCurrentDirectiveDef(tView.data);
  30017. const renderer = loadComponentRenderer(currentDef, tNode, lView);
  30018. listenerInternal(tView, lView, renderer, tNode, eventName, listenerFn);
  30019. return ɵɵsyntheticHostListener;
  30020. }
  30021. /**
  30022. * A utility function that checks if a given element has already an event handler registered for an
  30023. * event with a specified name. The TView.cleanup data structure is used to find out which events
  30024. * are registered for a given element.
  30025. */
  30026. function findExistingListener(tView, lView, eventName, tNodeIdx) {
  30027. const tCleanup = tView.cleanup;
  30028. if (tCleanup != null) {
  30029. for (let i = 0; i < tCleanup.length - 1; i += 2) {
  30030. const cleanupEventName = tCleanup[i];
  30031. if (cleanupEventName === eventName && tCleanup[i + 1] === tNodeIdx) {
  30032. // We have found a matching event name on the same node but it might not have been
  30033. // registered yet, so we must explicitly verify entries in the LView cleanup data
  30034. // structures.
  30035. const lCleanup = lView[CLEANUP];
  30036. const listenerIdxInLCleanup = tCleanup[i + 2];
  30037. return lCleanup.length > listenerIdxInLCleanup ? lCleanup[listenerIdxInLCleanup] : null;
  30038. }
  30039. // TView.cleanup can have a mix of 4-elements entries (for event handler cleanups) or
  30040. // 2-element entries (for directive and queries destroy hooks). As such we can encounter
  30041. // blocks of 4 or 2 items in the tView.cleanup and this is why we iterate over 2 elements
  30042. // first and jump another 2 elements if we detect listeners cleanup (4 elements). Also check
  30043. // documentation of TView.cleanup for more details of this data structure layout.
  30044. if (typeof cleanupEventName === 'string') {
  30045. i += 2;
  30046. }
  30047. }
  30048. }
  30049. return null;
  30050. }
  30051. function listenerInternal(tView, lView, renderer, tNode, eventName, listenerFn, eventTargetResolver) {
  30052. const isTNodeDirectiveHost = isDirectiveHost(tNode);
  30053. const firstCreatePass = tView.firstCreatePass;
  30054. const tCleanup = firstCreatePass ? getOrCreateTViewCleanup(tView) : null;
  30055. // When the ɵɵlistener instruction was generated and is executed we know that there is either a
  30056. // native listener or a directive output on this element. As such we we know that we will have to
  30057. // register a listener and store its cleanup function on LView.
  30058. const lCleanup = getOrCreateLViewCleanup(lView);
  30059. ngDevMode && assertTNodeType(tNode, 3 /* TNodeType.AnyRNode */ | 12 /* TNodeType.AnyContainer */);
  30060. let processOutputs = true;
  30061. // Adding a native event listener is applicable when:
  30062. // - The corresponding TNode represents a DOM element.
  30063. // - The event target has a resolver (usually resulting in a global object,
  30064. // such as `window` or `document`).
  30065. if (tNode.type & 3 /* TNodeType.AnyRNode */ || eventTargetResolver) {
  30066. const native = getNativeByTNode(tNode, lView);
  30067. const target = eventTargetResolver ? eventTargetResolver(native) : native;
  30068. const lCleanupIndex = lCleanup.length;
  30069. const idxOrTargetGetter = eventTargetResolver
  30070. ? (_lView) => eventTargetResolver(unwrapRNode(_lView[tNode.index]))
  30071. : tNode.index;
  30072. // In order to match current behavior, native DOM event listeners must be added for all
  30073. // events (including outputs).
  30074. // There might be cases where multiple directives on the same element try to register an event
  30075. // handler function for the same event. In this situation we want to avoid registration of
  30076. // several native listeners as each registration would be intercepted by NgZone and
  30077. // trigger change detection. This would mean that a single user action would result in several
  30078. // change detections being invoked. To avoid this situation we want to have only one call to
  30079. // native handler registration (for the same element and same type of event).
  30080. //
  30081. // In order to have just one native event handler in presence of multiple handler functions,
  30082. // we just register a first handler function as a native event listener and then chain
  30083. // (coalesce) other handler functions on top of the first native handler function.
  30084. let existingListener = null;
  30085. // Please note that the coalescing described here doesn't happen for events specifying an
  30086. // alternative target (ex. (document:click)) - this is to keep backward compatibility with the
  30087. // view engine.
  30088. // Also, we don't have to search for existing listeners is there are no directives
  30089. // matching on a given node as we can't register multiple event handlers for the same event in
  30090. // a template (this would mean having duplicate attributes).
  30091. if (!eventTargetResolver && isTNodeDirectiveHost) {
  30092. existingListener = findExistingListener(tView, lView, eventName, tNode.index);
  30093. }
  30094. if (existingListener !== null) {
  30095. // Attach a new listener to coalesced listeners list, maintaining the order in which
  30096. // listeners are registered. For performance reasons, we keep a reference to the last
  30097. // listener in that list (in `__ngLastListenerFn__` field), so we can avoid going through
  30098. // the entire set each time we need to add a new listener.
  30099. const lastListenerFn = existingListener.__ngLastListenerFn__ || existingListener;
  30100. lastListenerFn.__ngNextListenerFn__ = listenerFn;
  30101. existingListener.__ngLastListenerFn__ = listenerFn;
  30102. processOutputs = false;
  30103. }
  30104. else {
  30105. listenerFn = wrapListener(tNode, lView, listenerFn);
  30106. stashEventListenerImpl(lView, target, eventName, listenerFn);
  30107. const cleanupFn = renderer.listen(target, eventName, listenerFn);
  30108. ngDevMode && ngDevMode.rendererAddEventListener++;
  30109. lCleanup.push(listenerFn, cleanupFn);
  30110. tCleanup && tCleanup.push(eventName, idxOrTargetGetter, lCleanupIndex, lCleanupIndex + 1);
  30111. }
  30112. }
  30113. else {
  30114. // Even if there is no native listener to add, we still need to wrap the listener so that OnPush
  30115. // ancestors are marked dirty when an event occurs.
  30116. listenerFn = wrapListener(tNode, lView, listenerFn);
  30117. }
  30118. if (processOutputs) {
  30119. const outputConfig = tNode.outputs?.[eventName];
  30120. const hostDirectiveOutputConfig = tNode.hostDirectiveOutputs?.[eventName];
  30121. if (hostDirectiveOutputConfig && hostDirectiveOutputConfig.length) {
  30122. for (let i = 0; i < hostDirectiveOutputConfig.length; i += 2) {
  30123. const index = hostDirectiveOutputConfig[i];
  30124. const lookupName = hostDirectiveOutputConfig[i + 1];
  30125. listenToOutput(tNode, lView, index, lookupName, eventName, listenerFn);
  30126. }
  30127. }
  30128. if (outputConfig && outputConfig.length) {
  30129. for (const index of outputConfig) {
  30130. listenToOutput(tNode, lView, index, eventName, eventName, listenerFn);
  30131. }
  30132. }
  30133. }
  30134. }
  30135. /**
  30136. * Retrieves a context at the level specified and saves it as the global, contextViewData.
  30137. * Will get the next level up if level is not specified.
  30138. *
  30139. * This is used to save contexts of parent views so they can be bound in embedded views, or
  30140. * in conjunction with reference() to bind a ref from a parent view.
  30141. *
  30142. * @param level The relative level of the view from which to grab context compared to contextVewData
  30143. * @returns context
  30144. *
  30145. * @codeGenApi
  30146. */
  30147. function ɵɵnextContext(level = 1) {
  30148. return nextContextImpl(level);
  30149. }
  30150. /**
  30151. * Checks a given node against matching projection slots and returns the
  30152. * determined slot index. Returns "null" if no slot matched the given node.
  30153. *
  30154. * This function takes into account the parsed ngProjectAs selector from the
  30155. * node's attributes. If present, it will check whether the ngProjectAs selector
  30156. * matches any of the projection slot selectors.
  30157. */
  30158. function matchingProjectionSlotIndex(tNode, projectionSlots) {
  30159. let wildcardNgContentIndex = null;
  30160. const ngProjectAsAttrVal = getProjectAsAttrValue(tNode);
  30161. for (let i = 0; i < projectionSlots.length; i++) {
  30162. const slotValue = projectionSlots[i];
  30163. // The last wildcard projection slot should match all nodes which aren't matching
  30164. // any selector. This is necessary to be backwards compatible with view engine.
  30165. if (slotValue === '*') {
  30166. wildcardNgContentIndex = i;
  30167. continue;
  30168. }
  30169. // If we ran into an `ngProjectAs` attribute, we should match its parsed selector
  30170. // to the list of selectors, otherwise we fall back to matching against the node.
  30171. if (ngProjectAsAttrVal === null
  30172. ? isNodeMatchingSelectorList(tNode, slotValue, /* isProjectionMode */ true)
  30173. : isSelectorInSelectorList(ngProjectAsAttrVal, slotValue)) {
  30174. return i; // first matching selector "captures" a given node
  30175. }
  30176. }
  30177. return wildcardNgContentIndex;
  30178. }
  30179. /**
  30180. * Instruction to distribute projectable nodes among <ng-content> occurrences in a given template.
  30181. * It takes all the selectors from the entire component's template and decides where
  30182. * each projected node belongs (it re-distributes nodes among "buckets" where each "bucket" is
  30183. * backed by a selector).
  30184. *
  30185. * This function requires CSS selectors to be provided in 2 forms: parsed (by a compiler) and text,
  30186. * un-parsed form.
  30187. *
  30188. * The parsed form is needed for efficient matching of a node against a given CSS selector.
  30189. * The un-parsed, textual form is needed for support of the ngProjectAs attribute.
  30190. *
  30191. * Having a CSS selector in 2 different formats is not ideal, but alternatives have even more
  30192. * drawbacks:
  30193. * - having only a textual form would require runtime parsing of CSS selectors;
  30194. * - we can't have only a parsed as we can't re-construct textual form from it (as entered by a
  30195. * template author).
  30196. *
  30197. * @param projectionSlots? A collection of projection slots. A projection slot can be based
  30198. * on a parsed CSS selectors or set to the wildcard selector ("*") in order to match
  30199. * all nodes which do not match any selector. If not specified, a single wildcard
  30200. * selector projection slot will be defined.
  30201. *
  30202. * @codeGenApi
  30203. */
  30204. function ɵɵprojectionDef(projectionSlots) {
  30205. const componentNode = getLView()[DECLARATION_COMPONENT_VIEW][T_HOST];
  30206. if (!componentNode.projection) {
  30207. // If no explicit projection slots are defined, fall back to a single
  30208. // projection slot with the wildcard selector.
  30209. const numProjectionSlots = projectionSlots ? projectionSlots.length : 1;
  30210. const projectionHeads = (componentNode.projection = newArray(numProjectionSlots, null));
  30211. const tails = projectionHeads.slice();
  30212. let componentChild = componentNode.child;
  30213. while (componentChild !== null) {
  30214. // Do not project let declarations so they don't occupy a slot.
  30215. if (componentChild.type !== 128 /* TNodeType.LetDeclaration */) {
  30216. const slotIndex = projectionSlots
  30217. ? matchingProjectionSlotIndex(componentChild, projectionSlots)
  30218. : 0;
  30219. if (slotIndex !== null) {
  30220. if (tails[slotIndex]) {
  30221. tails[slotIndex].projectionNext = componentChild;
  30222. }
  30223. else {
  30224. projectionHeads[slotIndex] = componentChild;
  30225. }
  30226. tails[slotIndex] = componentChild;
  30227. }
  30228. }
  30229. componentChild = componentChild.next;
  30230. }
  30231. }
  30232. }
  30233. /**
  30234. * Inserts previously re-distributed projected nodes. This instruction must be preceded by a call
  30235. * to the projectionDef instruction.
  30236. *
  30237. * @param nodeIndex Index of the projection node.
  30238. * @param selectorIndex Index of the slot selector.
  30239. * - 0 when the selector is `*` (or unspecified as this is the default value),
  30240. * - 1 based index of the selector from the {@link projectionDef}
  30241. * @param attrs Static attributes set on the `ng-content` node.
  30242. * @param fallbackTemplateFn Template function with fallback content.
  30243. * Will be rendered if the slot is empty at runtime.
  30244. * @param fallbackDecls Number of declarations in the fallback template.
  30245. * @param fallbackVars Number of variables in the fallback template.
  30246. *
  30247. * @codeGenApi
  30248. */
  30249. function ɵɵprojection(nodeIndex, selectorIndex = 0, attrs, fallbackTemplateFn, fallbackDecls, fallbackVars) {
  30250. const lView = getLView();
  30251. const tView = getTView();
  30252. const fallbackIndex = fallbackTemplateFn ? nodeIndex + 1 : null;
  30253. // Fallback content needs to be declared no matter whether the slot is empty since different
  30254. // instances of the component may or may not insert it. Also it needs to be declare *before*
  30255. // the projection node in order to work correctly with hydration.
  30256. if (fallbackIndex !== null) {
  30257. declareTemplate(lView, tView, fallbackIndex, fallbackTemplateFn, fallbackDecls, fallbackVars, null, attrs);
  30258. }
  30259. const tProjectionNode = getOrCreateTNode(tView, HEADER_OFFSET + nodeIndex, 16 /* TNodeType.Projection */, null, attrs || null);
  30260. // We can't use viewData[HOST_NODE] because projection nodes can be nested in embedded views.
  30261. if (tProjectionNode.projection === null) {
  30262. tProjectionNode.projection = selectorIndex;
  30263. }
  30264. // `<ng-content>` has no content. Even if there's fallback
  30265. // content, the fallback is shown next to it.
  30266. setCurrentTNodeAsNotParent();
  30267. const hydrationInfo = lView[HYDRATION];
  30268. const isNodeCreationMode = !hydrationInfo || isInSkipHydrationBlock$1();
  30269. const componentHostNode = lView[DECLARATION_COMPONENT_VIEW][T_HOST];
  30270. const isEmpty = componentHostNode.projection[tProjectionNode.projection] === null;
  30271. if (isEmpty && fallbackIndex !== null) {
  30272. insertFallbackContent(lView, tView, fallbackIndex);
  30273. }
  30274. else if (isNodeCreationMode && !isDetachedByI18n(tProjectionNode)) {
  30275. // re-distribution of projectable nodes is stored on a component's view level
  30276. applyProjection(tView, lView, tProjectionNode);
  30277. }
  30278. }
  30279. /** Inserts the fallback content of a projection slot. Assumes there's no projected content. */
  30280. function insertFallbackContent(lView, tView, fallbackIndex) {
  30281. const adjustedIndex = HEADER_OFFSET + fallbackIndex;
  30282. const fallbackTNode = tView.data[adjustedIndex];
  30283. const fallbackLContainer = lView[adjustedIndex];
  30284. ngDevMode && assertTNode(fallbackTNode);
  30285. ngDevMode && assertLContainer(fallbackLContainer);
  30286. const dehydratedView = findMatchingDehydratedView(fallbackLContainer, fallbackTNode.tView.ssrId);
  30287. const fallbackLView = createAndRenderEmbeddedLView(lView, fallbackTNode, undefined, {
  30288. dehydratedView,
  30289. });
  30290. addLViewToLContainer(fallbackLContainer, fallbackLView, 0, shouldAddViewToDom(fallbackTNode, dehydratedView));
  30291. }
  30292. /**
  30293. *
  30294. * Update an interpolated property on an element with a lone bound value
  30295. *
  30296. * Used when the value passed to a property has 1 interpolated value in it, an no additional text
  30297. * surrounds that interpolated value:
  30298. *
  30299. * ```html
  30300. * <div title="{{v0}}"></div>
  30301. * ```
  30302. *
  30303. * Its compiled representation is::
  30304. *
  30305. * ```ts
  30306. * ɵɵpropertyInterpolate('title', v0);
  30307. * ```
  30308. *
  30309. * If the property name also exists as an input property on one of the element's directives,
  30310. * the component property will be set instead of the element property. This check must
  30311. * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
  30312. *
  30313. * @param propName The name of the property to update
  30314. * @param prefix Static value used for concatenation only.
  30315. * @param v0 Value checked for change.
  30316. * @param suffix Static value used for concatenation only.
  30317. * @param sanitizer An optional sanitizer function
  30318. * @returns itself, so that it may be chained.
  30319. * @codeGenApi
  30320. */
  30321. function ɵɵpropertyInterpolate(propName, v0, sanitizer) {
  30322. ɵɵpropertyInterpolate1(propName, '', v0, '', sanitizer);
  30323. return ɵɵpropertyInterpolate;
  30324. }
  30325. /**
  30326. *
  30327. * Update an interpolated property on an element with single bound value surrounded by text.
  30328. *
  30329. * Used when the value passed to a property has 1 interpolated value in it:
  30330. *
  30331. * ```html
  30332. * <div title="prefix{{v0}}suffix"></div>
  30333. * ```
  30334. *
  30335. * Its compiled representation is::
  30336. *
  30337. * ```ts
  30338. * ɵɵpropertyInterpolate1('title', 'prefix', v0, 'suffix');
  30339. * ```
  30340. *
  30341. * If the property name also exists as an input property on one of the element's directives,
  30342. * the component property will be set instead of the element property. This check must
  30343. * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
  30344. *
  30345. * @param propName The name of the property to update
  30346. * @param prefix Static value used for concatenation only.
  30347. * @param v0 Value checked for change.
  30348. * @param suffix Static value used for concatenation only.
  30349. * @param sanitizer An optional sanitizer function
  30350. * @returns itself, so that it may be chained.
  30351. * @codeGenApi
  30352. */
  30353. function ɵɵpropertyInterpolate1(propName, prefix, v0, suffix, sanitizer) {
  30354. const lView = getLView();
  30355. const interpolatedValue = interpolation1(lView, prefix, v0, suffix);
  30356. if (interpolatedValue !== NO_CHANGE) {
  30357. const tView = getTView();
  30358. const tNode = getSelectedTNode();
  30359. elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
  30360. ngDevMode &&
  30361. storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 1, prefix, suffix);
  30362. }
  30363. return ɵɵpropertyInterpolate1;
  30364. }
  30365. /**
  30366. *
  30367. * Update an interpolated property on an element with 2 bound values surrounded by text.
  30368. *
  30369. * Used when the value passed to a property has 2 interpolated values in it:
  30370. *
  30371. * ```html
  30372. * <div title="prefix{{v0}}-{{v1}}suffix"></div>
  30373. * ```
  30374. *
  30375. * Its compiled representation is::
  30376. *
  30377. * ```ts
  30378. * ɵɵpropertyInterpolate2('title', 'prefix', v0, '-', v1, 'suffix');
  30379. * ```
  30380. *
  30381. * If the property name also exists as an input property on one of the element's directives,
  30382. * the component property will be set instead of the element property. This check must
  30383. * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
  30384. *
  30385. * @param propName The name of the property to update
  30386. * @param prefix Static value used for concatenation only.
  30387. * @param v0 Value checked for change.
  30388. * @param i0 Static value used for concatenation only.
  30389. * @param v1 Value checked for change.
  30390. * @param suffix Static value used for concatenation only.
  30391. * @param sanitizer An optional sanitizer function
  30392. * @returns itself, so that it may be chained.
  30393. * @codeGenApi
  30394. */
  30395. function ɵɵpropertyInterpolate2(propName, prefix, v0, i0, v1, suffix, sanitizer) {
  30396. const lView = getLView();
  30397. const interpolatedValue = interpolation2(lView, prefix, v0, i0, v1, suffix);
  30398. if (interpolatedValue !== NO_CHANGE) {
  30399. const tView = getTView();
  30400. const tNode = getSelectedTNode();
  30401. elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
  30402. ngDevMode &&
  30403. storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 2, prefix, i0, suffix);
  30404. }
  30405. return ɵɵpropertyInterpolate2;
  30406. }
  30407. /**
  30408. *
  30409. * Update an interpolated property on an element with 3 bound values surrounded by text.
  30410. *
  30411. * Used when the value passed to a property has 3 interpolated values in it:
  30412. *
  30413. * ```html
  30414. * <div title="prefix{{v0}}-{{v1}}-{{v2}}suffix"></div>
  30415. * ```
  30416. *
  30417. * Its compiled representation is::
  30418. *
  30419. * ```ts
  30420. * ɵɵpropertyInterpolate3(
  30421. * 'title', 'prefix', v0, '-', v1, '-', v2, 'suffix');
  30422. * ```
  30423. *
  30424. * If the property name also exists as an input property on one of the element's directives,
  30425. * the component property will be set instead of the element property. This check must
  30426. * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
  30427. *
  30428. * @param propName The name of the property to update
  30429. * @param prefix Static value used for concatenation only.
  30430. * @param v0 Value checked for change.
  30431. * @param i0 Static value used for concatenation only.
  30432. * @param v1 Value checked for change.
  30433. * @param i1 Static value used for concatenation only.
  30434. * @param v2 Value checked for change.
  30435. * @param suffix Static value used for concatenation only.
  30436. * @param sanitizer An optional sanitizer function
  30437. * @returns itself, so that it may be chained.
  30438. * @codeGenApi
  30439. */
  30440. function ɵɵpropertyInterpolate3(propName, prefix, v0, i0, v1, i1, v2, suffix, sanitizer) {
  30441. const lView = getLView();
  30442. const interpolatedValue = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix);
  30443. if (interpolatedValue !== NO_CHANGE) {
  30444. const tView = getTView();
  30445. const tNode = getSelectedTNode();
  30446. elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
  30447. ngDevMode &&
  30448. storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 3, prefix, i0, i1, suffix);
  30449. }
  30450. return ɵɵpropertyInterpolate3;
  30451. }
  30452. /**
  30453. *
  30454. * Update an interpolated property on an element with 4 bound values surrounded by text.
  30455. *
  30456. * Used when the value passed to a property has 4 interpolated values in it:
  30457. *
  30458. * ```html
  30459. * <div title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}suffix"></div>
  30460. * ```
  30461. *
  30462. * Its compiled representation is::
  30463. *
  30464. * ```ts
  30465. * ɵɵpropertyInterpolate4(
  30466. * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, 'suffix');
  30467. * ```
  30468. *
  30469. * If the property name also exists as an input property on one of the element's directives,
  30470. * the component property will be set instead of the element property. This check must
  30471. * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
  30472. *
  30473. * @param propName The name of the property to update
  30474. * @param prefix Static value used for concatenation only.
  30475. * @param v0 Value checked for change.
  30476. * @param i0 Static value used for concatenation only.
  30477. * @param v1 Value checked for change.
  30478. * @param i1 Static value used for concatenation only.
  30479. * @param v2 Value checked for change.
  30480. * @param i2 Static value used for concatenation only.
  30481. * @param v3 Value checked for change.
  30482. * @param suffix Static value used for concatenation only.
  30483. * @param sanitizer An optional sanitizer function
  30484. * @returns itself, so that it may be chained.
  30485. * @codeGenApi
  30486. */
  30487. function ɵɵpropertyInterpolate4(propName, prefix, v0, i0, v1, i1, v2, i2, v3, suffix, sanitizer) {
  30488. const lView = getLView();
  30489. const interpolatedValue = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix);
  30490. if (interpolatedValue !== NO_CHANGE) {
  30491. const tView = getTView();
  30492. const tNode = getSelectedTNode();
  30493. elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
  30494. ngDevMode &&
  30495. storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 4, prefix, i0, i1, i2, suffix);
  30496. }
  30497. return ɵɵpropertyInterpolate4;
  30498. }
  30499. /**
  30500. *
  30501. * Update an interpolated property on an element with 5 bound values surrounded by text.
  30502. *
  30503. * Used when the value passed to a property has 5 interpolated values in it:
  30504. *
  30505. * ```html
  30506. * <div title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}suffix"></div>
  30507. * ```
  30508. *
  30509. * Its compiled representation is::
  30510. *
  30511. * ```ts
  30512. * ɵɵpropertyInterpolate5(
  30513. * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, 'suffix');
  30514. * ```
  30515. *
  30516. * If the property name also exists as an input property on one of the element's directives,
  30517. * the component property will be set instead of the element property. This check must
  30518. * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
  30519. *
  30520. * @param propName The name of the property to update
  30521. * @param prefix Static value used for concatenation only.
  30522. * @param v0 Value checked for change.
  30523. * @param i0 Static value used for concatenation only.
  30524. * @param v1 Value checked for change.
  30525. * @param i1 Static value used for concatenation only.
  30526. * @param v2 Value checked for change.
  30527. * @param i2 Static value used for concatenation only.
  30528. * @param v3 Value checked for change.
  30529. * @param i3 Static value used for concatenation only.
  30530. * @param v4 Value checked for change.
  30531. * @param suffix Static value used for concatenation only.
  30532. * @param sanitizer An optional sanitizer function
  30533. * @returns itself, so that it may be chained.
  30534. * @codeGenApi
  30535. */
  30536. function ɵɵpropertyInterpolate5(propName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix, sanitizer) {
  30537. const lView = getLView();
  30538. const interpolatedValue = interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix);
  30539. if (interpolatedValue !== NO_CHANGE) {
  30540. const tView = getTView();
  30541. const tNode = getSelectedTNode();
  30542. elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
  30543. ngDevMode &&
  30544. storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 5, prefix, i0, i1, i2, i3, suffix);
  30545. }
  30546. return ɵɵpropertyInterpolate5;
  30547. }
  30548. /**
  30549. *
  30550. * Update an interpolated property on an element with 6 bound values surrounded by text.
  30551. *
  30552. * Used when the value passed to a property has 6 interpolated values in it:
  30553. *
  30554. * ```html
  30555. * <div title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}suffix"></div>
  30556. * ```
  30557. *
  30558. * Its compiled representation is::
  30559. *
  30560. * ```ts
  30561. * ɵɵpropertyInterpolate6(
  30562. * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, 'suffix');
  30563. * ```
  30564. *
  30565. * If the property name also exists as an input property on one of the element's directives,
  30566. * the component property will be set instead of the element property. This check must
  30567. * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
  30568. *
  30569. * @param propName The name of the property to update
  30570. * @param prefix Static value used for concatenation only.
  30571. * @param v0 Value checked for change.
  30572. * @param i0 Static value used for concatenation only.
  30573. * @param v1 Value checked for change.
  30574. * @param i1 Static value used for concatenation only.
  30575. * @param v2 Value checked for change.
  30576. * @param i2 Static value used for concatenation only.
  30577. * @param v3 Value checked for change.
  30578. * @param i3 Static value used for concatenation only.
  30579. * @param v4 Value checked for change.
  30580. * @param i4 Static value used for concatenation only.
  30581. * @param v5 Value checked for change.
  30582. * @param suffix Static value used for concatenation only.
  30583. * @param sanitizer An optional sanitizer function
  30584. * @returns itself, so that it may be chained.
  30585. * @codeGenApi
  30586. */
  30587. function ɵɵpropertyInterpolate6(propName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix, sanitizer) {
  30588. const lView = getLView();
  30589. const interpolatedValue = interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix);
  30590. if (interpolatedValue !== NO_CHANGE) {
  30591. const tView = getTView();
  30592. const tNode = getSelectedTNode();
  30593. elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
  30594. ngDevMode &&
  30595. storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 6, prefix, i0, i1, i2, i3, i4, suffix);
  30596. }
  30597. return ɵɵpropertyInterpolate6;
  30598. }
  30599. /**
  30600. *
  30601. * Update an interpolated property on an element with 7 bound values surrounded by text.
  30602. *
  30603. * Used when the value passed to a property has 7 interpolated values in it:
  30604. *
  30605. * ```html
  30606. * <div title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}suffix"></div>
  30607. * ```
  30608. *
  30609. * Its compiled representation is::
  30610. *
  30611. * ```ts
  30612. * ɵɵpropertyInterpolate7(
  30613. * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, 'suffix');
  30614. * ```
  30615. *
  30616. * If the property name also exists as an input property on one of the element's directives,
  30617. * the component property will be set instead of the element property. This check must
  30618. * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
  30619. *
  30620. * @param propName The name of the property to update
  30621. * @param prefix Static value used for concatenation only.
  30622. * @param v0 Value checked for change.
  30623. * @param i0 Static value used for concatenation only.
  30624. * @param v1 Value checked for change.
  30625. * @param i1 Static value used for concatenation only.
  30626. * @param v2 Value checked for change.
  30627. * @param i2 Static value used for concatenation only.
  30628. * @param v3 Value checked for change.
  30629. * @param i3 Static value used for concatenation only.
  30630. * @param v4 Value checked for change.
  30631. * @param i4 Static value used for concatenation only.
  30632. * @param v5 Value checked for change.
  30633. * @param i5 Static value used for concatenation only.
  30634. * @param v6 Value checked for change.
  30635. * @param suffix Static value used for concatenation only.
  30636. * @param sanitizer An optional sanitizer function
  30637. * @returns itself, so that it may be chained.
  30638. * @codeGenApi
  30639. */
  30640. function ɵɵpropertyInterpolate7(propName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix, sanitizer) {
  30641. const lView = getLView();
  30642. const interpolatedValue = interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix);
  30643. if (interpolatedValue !== NO_CHANGE) {
  30644. const tView = getTView();
  30645. const tNode = getSelectedTNode();
  30646. elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
  30647. ngDevMode &&
  30648. storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 7, prefix, i0, i1, i2, i3, i4, i5, suffix);
  30649. }
  30650. return ɵɵpropertyInterpolate7;
  30651. }
  30652. /**
  30653. *
  30654. * Update an interpolated property on an element with 8 bound values surrounded by text.
  30655. *
  30656. * Used when the value passed to a property has 8 interpolated values in it:
  30657. *
  30658. * ```html
  30659. * <div title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}suffix"></div>
  30660. * ```
  30661. *
  30662. * Its compiled representation is::
  30663. *
  30664. * ```ts
  30665. * ɵɵpropertyInterpolate8(
  30666. * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, 'suffix');
  30667. * ```
  30668. *
  30669. * If the property name also exists as an input property on one of the element's directives,
  30670. * the component property will be set instead of the element property. This check must
  30671. * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
  30672. *
  30673. * @param propName The name of the property to update
  30674. * @param prefix Static value used for concatenation only.
  30675. * @param v0 Value checked for change.
  30676. * @param i0 Static value used for concatenation only.
  30677. * @param v1 Value checked for change.
  30678. * @param i1 Static value used for concatenation only.
  30679. * @param v2 Value checked for change.
  30680. * @param i2 Static value used for concatenation only.
  30681. * @param v3 Value checked for change.
  30682. * @param i3 Static value used for concatenation only.
  30683. * @param v4 Value checked for change.
  30684. * @param i4 Static value used for concatenation only.
  30685. * @param v5 Value checked for change.
  30686. * @param i5 Static value used for concatenation only.
  30687. * @param v6 Value checked for change.
  30688. * @param i6 Static value used for concatenation only.
  30689. * @param v7 Value checked for change.
  30690. * @param suffix Static value used for concatenation only.
  30691. * @param sanitizer An optional sanitizer function
  30692. * @returns itself, so that it may be chained.
  30693. * @codeGenApi
  30694. */
  30695. function ɵɵpropertyInterpolate8(propName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix, sanitizer) {
  30696. const lView = getLView();
  30697. const interpolatedValue = interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix);
  30698. if (interpolatedValue !== NO_CHANGE) {
  30699. const tView = getTView();
  30700. const tNode = getSelectedTNode();
  30701. elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
  30702. ngDevMode &&
  30703. storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 8, prefix, i0, i1, i2, i3, i4, i5, i6, suffix);
  30704. }
  30705. return ɵɵpropertyInterpolate8;
  30706. }
  30707. /**
  30708. * Update an interpolated property on an element with 9 or more bound values surrounded by text.
  30709. *
  30710. * Used when the number of interpolated values exceeds 8.
  30711. *
  30712. * ```html
  30713. * <div
  30714. * title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}-{{v8}}-{{v9}}suffix"></div>
  30715. * ```
  30716. *
  30717. * Its compiled representation is::
  30718. *
  30719. * ```ts
  30720. * ɵɵpropertyInterpolateV(
  30721. * 'title', ['prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, '-', v9,
  30722. * 'suffix']);
  30723. * ```
  30724. *
  30725. * If the property name also exists as an input property on one of the element's directives,
  30726. * the component property will be set instead of the element property. This check must
  30727. * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
  30728. *
  30729. * @param propName The name of the property to update.
  30730. * @param values The collection of values and the strings in between those values, beginning with a
  30731. * string prefix and ending with a string suffix.
  30732. * (e.g. `['prefix', value0, '-', value1, '-', value2, ..., value99, 'suffix']`)
  30733. * @param sanitizer An optional sanitizer function
  30734. * @returns itself, so that it may be chained.
  30735. * @codeGenApi
  30736. */
  30737. function ɵɵpropertyInterpolateV(propName, values, sanitizer) {
  30738. const lView = getLView();
  30739. const interpolatedValue = interpolationV(lView, values);
  30740. if (interpolatedValue !== NO_CHANGE) {
  30741. const tView = getTView();
  30742. const tNode = getSelectedTNode();
  30743. elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
  30744. if (ngDevMode) {
  30745. const interpolationInBetween = [values[0]]; // prefix
  30746. for (let i = 2; i < values.length; i += 2) {
  30747. interpolationInBetween.push(values[i]);
  30748. }
  30749. storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - interpolationInBetween.length + 1, ...interpolationInBetween);
  30750. }
  30751. }
  30752. return ɵɵpropertyInterpolateV;
  30753. }
  30754. /**
  30755. * Registers a QueryList, associated with a content query, for later refresh (part of a view
  30756. * refresh).
  30757. *
  30758. * @param directiveIndex Current directive index
  30759. * @param predicate The type for which the query will search
  30760. * @param flags Flags associated with the query
  30761. * @param read What to save in the query
  30762. * @returns QueryList<T>
  30763. *
  30764. * @codeGenApi
  30765. */
  30766. function ɵɵcontentQuery(directiveIndex, predicate, flags, read) {
  30767. createContentQuery(directiveIndex, predicate, flags, read);
  30768. }
  30769. /**
  30770. * Creates a new view query by initializing internal data structures.
  30771. *
  30772. * @param predicate The type for which the query will search
  30773. * @param flags Flags associated with the query
  30774. * @param read What to save in the query
  30775. *
  30776. * @codeGenApi
  30777. */
  30778. function ɵɵviewQuery(predicate, flags, read) {
  30779. createViewQuery(predicate, flags, read);
  30780. }
  30781. /**
  30782. * Refreshes a query by combining matches from all active views and removing matches from deleted
  30783. * views.
  30784. *
  30785. * @returns `true` if a query got dirty during change detection or if this is a static query
  30786. * resolving in creation mode, `false` otherwise.
  30787. *
  30788. * @codeGenApi
  30789. */
  30790. function ɵɵqueryRefresh(queryList) {
  30791. const lView = getLView();
  30792. const tView = getTView();
  30793. const queryIndex = getCurrentQueryIndex();
  30794. setCurrentQueryIndex(queryIndex + 1);
  30795. const tQuery = getTQuery(tView, queryIndex);
  30796. if (queryList.dirty &&
  30797. isCreationMode(lView) ===
  30798. ((tQuery.metadata.flags & 2 /* QueryFlags.isStatic */) === 2 /* QueryFlags.isStatic */)) {
  30799. if (tQuery.matches === null) {
  30800. queryList.reset([]);
  30801. }
  30802. else {
  30803. const result = getQueryResults(lView, queryIndex);
  30804. queryList.reset(result, unwrapElementRef);
  30805. queryList.notifyOnChanges();
  30806. }
  30807. return true;
  30808. }
  30809. return false;
  30810. }
  30811. /**
  30812. * Loads a QueryList corresponding to the current view or content query.
  30813. *
  30814. * @codeGenApi
  30815. */
  30816. function ɵɵloadQuery() {
  30817. return loadQueryInternal(getLView(), getCurrentQueryIndex());
  30818. }
  30819. /**
  30820. * Creates a new content query and binds it to a signal created by an authoring function.
  30821. *
  30822. * @param directiveIndex Current directive index
  30823. * @param target The target signal to which the query should be bound
  30824. * @param predicate The type for which the query will search
  30825. * @param flags Flags associated with the query
  30826. * @param read What to save in the query
  30827. *
  30828. * @codeGenApi
  30829. */
  30830. function ɵɵcontentQuerySignal(directiveIndex, target, predicate, flags, read) {
  30831. bindQueryToSignal(target, createContentQuery(directiveIndex, predicate, flags, read));
  30832. }
  30833. /**
  30834. * Creates a new view query by initializing internal data structures and binding a new query to the
  30835. * target signal.
  30836. *
  30837. * @param target The target signal to assign the query results to.
  30838. * @param predicate The type or label that should match a given query
  30839. * @param flags Flags associated with the query
  30840. * @param read What to save in the query
  30841. *
  30842. * @codeGenApi
  30843. */
  30844. function ɵɵviewQuerySignal(target, predicate, flags, read) {
  30845. bindQueryToSignal(target, createViewQuery(predicate, flags, read));
  30846. }
  30847. /**
  30848. * Advances the current query index by a specified offset.
  30849. *
  30850. * Adjusting the current query index is necessary in cases where a given directive has a mix of
  30851. * zone-based and signal-based queries. The signal-based queries don't require tracking of the
  30852. * current index (those are refreshed on demand and not during change detection) so this instruction
  30853. * is only necessary for backward-compatibility.
  30854. *
  30855. * @param index offset to apply to the current query index (defaults to 1)
  30856. *
  30857. * @codeGenApi
  30858. */
  30859. function ɵɵqueryAdvance(indexOffset = 1) {
  30860. setCurrentQueryIndex(getCurrentQueryIndex() + indexOffset);
  30861. }
  30862. /**
  30863. * Retrieves a local reference from the current contextViewData.
  30864. *
  30865. * If the reference to retrieve is in a parent view, this instruction is used in conjunction
  30866. * with a nextContext() call, which walks up the tree and updates the contextViewData instance.
  30867. *
  30868. * @param index The index of the local ref in contextViewData.
  30869. *
  30870. * @codeGenApi
  30871. */
  30872. function ɵɵreference(index) {
  30873. const contextLView = getContextLView();
  30874. return load(contextLView, HEADER_OFFSET + index);
  30875. }
  30876. /**
  30877. *
  30878. * Update an interpolated style on an element with single bound value surrounded by text.
  30879. *
  30880. * Used when the value passed to a property has 1 interpolated value in it:
  30881. *
  30882. * ```html
  30883. * <div style="key: {{v0}}suffix"></div>
  30884. * ```
  30885. *
  30886. * Its compiled representation is:
  30887. *
  30888. * ```ts
  30889. * ɵɵstyleMapInterpolate1('key: ', v0, 'suffix');
  30890. * ```
  30891. *
  30892. * @param prefix Static value used for concatenation only.
  30893. * @param v0 Value checked for change.
  30894. * @param suffix Static value used for concatenation only.
  30895. * @codeGenApi
  30896. */
  30897. function ɵɵstyleMapInterpolate1(prefix, v0, suffix) {
  30898. const lView = getLView();
  30899. const interpolatedValue = interpolation1(lView, prefix, v0, suffix);
  30900. ɵɵstyleMap(interpolatedValue);
  30901. }
  30902. /**
  30903. *
  30904. * Update an interpolated style on an element with 2 bound values surrounded by text.
  30905. *
  30906. * Used when the value passed to a property has 2 interpolated values in it:
  30907. *
  30908. * ```html
  30909. * <div style="key: {{v0}}; key1: {{v1}}suffix"></div>
  30910. * ```
  30911. *
  30912. * Its compiled representation is:
  30913. *
  30914. * ```ts
  30915. * ɵɵstyleMapInterpolate2('key: ', v0, '; key1: ', v1, 'suffix');
  30916. * ```
  30917. *
  30918. * @param prefix Static value used for concatenation only.
  30919. * @param v0 Value checked for change.
  30920. * @param i0 Static value used for concatenation only.
  30921. * @param v1 Value checked for change.
  30922. * @param suffix Static value used for concatenation only.
  30923. * @codeGenApi
  30924. */
  30925. function ɵɵstyleMapInterpolate2(prefix, v0, i0, v1, suffix) {
  30926. const lView = getLView();
  30927. const interpolatedValue = interpolation2(lView, prefix, v0, i0, v1, suffix);
  30928. ɵɵstyleMap(interpolatedValue);
  30929. }
  30930. /**
  30931. *
  30932. * Update an interpolated style on an element with 3 bound values surrounded by text.
  30933. *
  30934. * Used when the value passed to a property has 3 interpolated values in it:
  30935. *
  30936. * ```html
  30937. * <div style="key: {{v0}}; key2: {{v1}}; key2: {{v2}}suffix"></div>
  30938. * ```
  30939. *
  30940. * Its compiled representation is:
  30941. *
  30942. * ```ts
  30943. * ɵɵstyleMapInterpolate3(
  30944. * 'key: ', v0, '; key1: ', v1, '; key2: ', v2, 'suffix');
  30945. * ```
  30946. *
  30947. * @param prefix Static value used for concatenation only.
  30948. * @param v0 Value checked for change.
  30949. * @param i0 Static value used for concatenation only.
  30950. * @param v1 Value checked for change.
  30951. * @param i1 Static value used for concatenation only.
  30952. * @param v2 Value checked for change.
  30953. * @param suffix Static value used for concatenation only.
  30954. * @codeGenApi
  30955. */
  30956. function ɵɵstyleMapInterpolate3(prefix, v0, i0, v1, i1, v2, suffix) {
  30957. const lView = getLView();
  30958. const interpolatedValue = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix);
  30959. ɵɵstyleMap(interpolatedValue);
  30960. }
  30961. /**
  30962. *
  30963. * Update an interpolated style on an element with 4 bound values surrounded by text.
  30964. *
  30965. * Used when the value passed to a property has 4 interpolated values in it:
  30966. *
  30967. * ```html
  30968. * <div style="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}suffix"></div>
  30969. * ```
  30970. *
  30971. * Its compiled representation is:
  30972. *
  30973. * ```ts
  30974. * ɵɵstyleMapInterpolate4(
  30975. * 'key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, 'suffix');
  30976. * ```
  30977. *
  30978. * @param prefix Static value used for concatenation only.
  30979. * @param v0 Value checked for change.
  30980. * @param i0 Static value used for concatenation only.
  30981. * @param v1 Value checked for change.
  30982. * @param i1 Static value used for concatenation only.
  30983. * @param v2 Value checked for change.
  30984. * @param i2 Static value used for concatenation only.
  30985. * @param v3 Value checked for change.
  30986. * @param suffix Static value used for concatenation only.
  30987. * @codeGenApi
  30988. */
  30989. function ɵɵstyleMapInterpolate4(prefix, v0, i0, v1, i1, v2, i2, v3, suffix) {
  30990. const lView = getLView();
  30991. const interpolatedValue = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix);
  30992. ɵɵstyleMap(interpolatedValue);
  30993. }
  30994. /**
  30995. *
  30996. * Update an interpolated style on an element with 5 bound values surrounded by text.
  30997. *
  30998. * Used when the value passed to a property has 5 interpolated values in it:
  30999. *
  31000. * ```html
  31001. * <div style="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}; key4: {{v4}}suffix"></div>
  31002. * ```
  31003. *
  31004. * Its compiled representation is:
  31005. *
  31006. * ```ts
  31007. * ɵɵstyleMapInterpolate5(
  31008. * 'key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, '; key4: ', v4, 'suffix');
  31009. * ```
  31010. *
  31011. * @param prefix Static value used for concatenation only.
  31012. * @param v0 Value checked for change.
  31013. * @param i0 Static value used for concatenation only.
  31014. * @param v1 Value checked for change.
  31015. * @param i1 Static value used for concatenation only.
  31016. * @param v2 Value checked for change.
  31017. * @param i2 Static value used for concatenation only.
  31018. * @param v3 Value checked for change.
  31019. * @param i3 Static value used for concatenation only.
  31020. * @param v4 Value checked for change.
  31021. * @param suffix Static value used for concatenation only.
  31022. * @codeGenApi
  31023. */
  31024. function ɵɵstyleMapInterpolate5(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix) {
  31025. const lView = getLView();
  31026. const interpolatedValue = interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix);
  31027. ɵɵstyleMap(interpolatedValue);
  31028. }
  31029. /**
  31030. *
  31031. * Update an interpolated style on an element with 6 bound values surrounded by text.
  31032. *
  31033. * Used when the value passed to a property has 6 interpolated values in it:
  31034. *
  31035. * ```html
  31036. * <div style="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}; key4: {{v4}};
  31037. * key5: {{v5}}suffix"></div>
  31038. * ```
  31039. *
  31040. * Its compiled representation is:
  31041. *
  31042. * ```ts
  31043. * ɵɵstyleMapInterpolate6(
  31044. * 'key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, '; key4: ', v4, '; key5: ', v5,
  31045. * 'suffix');
  31046. * ```
  31047. *
  31048. * @param prefix Static value used for concatenation only.
  31049. * @param v0 Value checked for change.
  31050. * @param i0 Static value used for concatenation only.
  31051. * @param v1 Value checked for change.
  31052. * @param i1 Static value used for concatenation only.
  31053. * @param v2 Value checked for change.
  31054. * @param i2 Static value used for concatenation only.
  31055. * @param v3 Value checked for change.
  31056. * @param i3 Static value used for concatenation only.
  31057. * @param v4 Value checked for change.
  31058. * @param i4 Static value used for concatenation only.
  31059. * @param v5 Value checked for change.
  31060. * @param suffix Static value used for concatenation only.
  31061. * @codeGenApi
  31062. */
  31063. function ɵɵstyleMapInterpolate6(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix) {
  31064. const lView = getLView();
  31065. const interpolatedValue = interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix);
  31066. ɵɵstyleMap(interpolatedValue);
  31067. }
  31068. /**
  31069. *
  31070. * Update an interpolated style on an element with 7 bound values surrounded by text.
  31071. *
  31072. * Used when the value passed to a property has 7 interpolated values in it:
  31073. *
  31074. * ```html
  31075. * <div style="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}; key4: {{v4}}; key5: {{v5}};
  31076. * key6: {{v6}}suffix"></div>
  31077. * ```
  31078. *
  31079. * Its compiled representation is:
  31080. *
  31081. * ```ts
  31082. * ɵɵstyleMapInterpolate7(
  31083. * 'key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, '; key4: ', v4, '; key5: ', v5,
  31084. * '; key6: ', v6, 'suffix');
  31085. * ```
  31086. *
  31087. * @param prefix Static value used for concatenation only.
  31088. * @param v0 Value checked for change.
  31089. * @param i0 Static value used for concatenation only.
  31090. * @param v1 Value checked for change.
  31091. * @param i1 Static value used for concatenation only.
  31092. * @param v2 Value checked for change.
  31093. * @param i2 Static value used for concatenation only.
  31094. * @param v3 Value checked for change.
  31095. * @param i3 Static value used for concatenation only.
  31096. * @param v4 Value checked for change.
  31097. * @param i4 Static value used for concatenation only.
  31098. * @param v5 Value checked for change.
  31099. * @param i5 Static value used for concatenation only.
  31100. * @param v6 Value checked for change.
  31101. * @param suffix Static value used for concatenation only.
  31102. * @codeGenApi
  31103. */
  31104. function ɵɵstyleMapInterpolate7(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix) {
  31105. const lView = getLView();
  31106. const interpolatedValue = interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix);
  31107. ɵɵstyleMap(interpolatedValue);
  31108. }
  31109. /**
  31110. *
  31111. * Update an interpolated style on an element with 8 bound values surrounded by text.
  31112. *
  31113. * Used when the value passed to a property has 8 interpolated values in it:
  31114. *
  31115. * ```html
  31116. * <div style="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}; key4: {{v4}}; key5: {{v5}};
  31117. * key6: {{v6}}; key7: {{v7}}suffix"></div>
  31118. * ```
  31119. *
  31120. * Its compiled representation is:
  31121. *
  31122. * ```ts
  31123. * ɵɵstyleMapInterpolate8(
  31124. * 'key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, '; key4: ', v4, '; key5: ', v5,
  31125. * '; key6: ', v6, '; key7: ', v7, 'suffix');
  31126. * ```
  31127. *
  31128. * @param prefix Static value used for concatenation only.
  31129. * @param v0 Value checked for change.
  31130. * @param i0 Static value used for concatenation only.
  31131. * @param v1 Value checked for change.
  31132. * @param i1 Static value used for concatenation only.
  31133. * @param v2 Value checked for change.
  31134. * @param i2 Static value used for concatenation only.
  31135. * @param v3 Value checked for change.
  31136. * @param i3 Static value used for concatenation only.
  31137. * @param v4 Value checked for change.
  31138. * @param i4 Static value used for concatenation only.
  31139. * @param v5 Value checked for change.
  31140. * @param i5 Static value used for concatenation only.
  31141. * @param v6 Value checked for change.
  31142. * @param i6 Static value used for concatenation only.
  31143. * @param v7 Value checked for change.
  31144. * @param suffix Static value used for concatenation only.
  31145. * @codeGenApi
  31146. */
  31147. function ɵɵstyleMapInterpolate8(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix) {
  31148. const lView = getLView();
  31149. const interpolatedValue = interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix);
  31150. ɵɵstyleMap(interpolatedValue);
  31151. }
  31152. /**
  31153. * Update an interpolated style on an element with 9 or more bound values surrounded by text.
  31154. *
  31155. * Used when the number of interpolated values exceeds 8.
  31156. *
  31157. * ```html
  31158. * <div
  31159. * class="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}; key4: {{v4}}; key5: {{v5}};
  31160. * key6: {{v6}}; key7: {{v7}}; key8: {{v8}}; key9: {{v9}}suffix"></div>
  31161. * ```
  31162. *
  31163. * Its compiled representation is:
  31164. *
  31165. * ```ts
  31166. * ɵɵstyleMapInterpolateV(
  31167. * ['key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, '; key4: ', v4, '; key5: ', v5,
  31168. * '; key6: ', v6, '; key7: ', v7, '; key8: ', v8, '; key9: ', v9, 'suffix']);
  31169. * ```
  31170. *.
  31171. * @param values The collection of values and the strings in-between those values, beginning with
  31172. * a string prefix and ending with a string suffix.
  31173. * (e.g. `['prefix', value0, '; key2: ', value1, '; key2: ', value2, ..., value99, 'suffix']`)
  31174. * @codeGenApi
  31175. */
  31176. function ɵɵstyleMapInterpolateV(values) {
  31177. const lView = getLView();
  31178. const interpolatedValue = interpolationV(lView, values);
  31179. ɵɵstyleMap(interpolatedValue);
  31180. }
  31181. /**
  31182. *
  31183. * Update an interpolated style property on an element with single bound value surrounded by text.
  31184. *
  31185. * Used when the value passed to a property has 1 interpolated value in it:
  31186. *
  31187. * ```html
  31188. * <div style.color="prefix{{v0}}suffix"></div>
  31189. * ```
  31190. *
  31191. * Its compiled representation is:
  31192. *
  31193. * ```ts
  31194. * ɵɵstylePropInterpolate1(0, 'prefix', v0, 'suffix');
  31195. * ```
  31196. *
  31197. * @param styleIndex Index of style to update. This index value refers to the
  31198. * index of the style in the style bindings array that was passed into
  31199. * `styling`.
  31200. * @param prefix Static value used for concatenation only.
  31201. * @param v0 Value checked for change.
  31202. * @param suffix Static value used for concatenation only.
  31203. * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
  31204. * @returns itself, so that it may be chained.
  31205. * @codeGenApi
  31206. */
  31207. function ɵɵstylePropInterpolate1(prop, prefix, v0, suffix, valueSuffix) {
  31208. const lView = getLView();
  31209. const interpolatedValue = interpolation1(lView, prefix, v0, suffix);
  31210. checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
  31211. return ɵɵstylePropInterpolate1;
  31212. }
  31213. /**
  31214. *
  31215. * Update an interpolated style property on an element with 2 bound values surrounded by text.
  31216. *
  31217. * Used when the value passed to a property has 2 interpolated values in it:
  31218. *
  31219. * ```html
  31220. * <div style.color="prefix{{v0}}-{{v1}}suffix"></div>
  31221. * ```
  31222. *
  31223. * Its compiled representation is:
  31224. *
  31225. * ```ts
  31226. * ɵɵstylePropInterpolate2(0, 'prefix', v0, '-', v1, 'suffix');
  31227. * ```
  31228. *
  31229. * @param styleIndex Index of style to update. This index value refers to the
  31230. * index of the style in the style bindings array that was passed into
  31231. * `styling`.
  31232. * @param prefix Static value used for concatenation only.
  31233. * @param v0 Value checked for change.
  31234. * @param i0 Static value used for concatenation only.
  31235. * @param v1 Value checked for change.
  31236. * @param suffix Static value used for concatenation only.
  31237. * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
  31238. * @returns itself, so that it may be chained.
  31239. * @codeGenApi
  31240. */
  31241. function ɵɵstylePropInterpolate2(prop, prefix, v0, i0, v1, suffix, valueSuffix) {
  31242. const lView = getLView();
  31243. const interpolatedValue = interpolation2(lView, prefix, v0, i0, v1, suffix);
  31244. checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
  31245. return ɵɵstylePropInterpolate2;
  31246. }
  31247. /**
  31248. *
  31249. * Update an interpolated style property on an element with 3 bound values surrounded by text.
  31250. *
  31251. * Used when the value passed to a property has 3 interpolated values in it:
  31252. *
  31253. * ```html
  31254. * <div style.color="prefix{{v0}}-{{v1}}-{{v2}}suffix"></div>
  31255. * ```
  31256. *
  31257. * Its compiled representation is:
  31258. *
  31259. * ```ts
  31260. * ɵɵstylePropInterpolate3(0, 'prefix', v0, '-', v1, '-', v2, 'suffix');
  31261. * ```
  31262. *
  31263. * @param styleIndex Index of style to update. This index value refers to the
  31264. * index of the style in the style bindings array that was passed into
  31265. * `styling`.
  31266. * @param prefix Static value used for concatenation only.
  31267. * @param v0 Value checked for change.
  31268. * @param i0 Static value used for concatenation only.
  31269. * @param v1 Value checked for change.
  31270. * @param i1 Static value used for concatenation only.
  31271. * @param v2 Value checked for change.
  31272. * @param suffix Static value used for concatenation only.
  31273. * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
  31274. * @returns itself, so that it may be chained.
  31275. * @codeGenApi
  31276. */
  31277. function ɵɵstylePropInterpolate3(prop, prefix, v0, i0, v1, i1, v2, suffix, valueSuffix) {
  31278. const lView = getLView();
  31279. const interpolatedValue = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix);
  31280. checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
  31281. return ɵɵstylePropInterpolate3;
  31282. }
  31283. /**
  31284. *
  31285. * Update an interpolated style property on an element with 4 bound values surrounded by text.
  31286. *
  31287. * Used when the value passed to a property has 4 interpolated values in it:
  31288. *
  31289. * ```html
  31290. * <div style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}suffix"></div>
  31291. * ```
  31292. *
  31293. * Its compiled representation is:
  31294. *
  31295. * ```ts
  31296. * ɵɵstylePropInterpolate4(0, 'prefix', v0, '-', v1, '-', v2, '-', v3, 'suffix');
  31297. * ```
  31298. *
  31299. * @param styleIndex Index of style to update. This index value refers to the
  31300. * index of the style in the style bindings array that was passed into
  31301. * `styling`.
  31302. * @param prefix Static value used for concatenation only.
  31303. * @param v0 Value checked for change.
  31304. * @param i0 Static value used for concatenation only.
  31305. * @param v1 Value checked for change.
  31306. * @param i1 Static value used for concatenation only.
  31307. * @param v2 Value checked for change.
  31308. * @param i2 Static value used for concatenation only.
  31309. * @param v3 Value checked for change.
  31310. * @param suffix Static value used for concatenation only.
  31311. * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
  31312. * @returns itself, so that it may be chained.
  31313. * @codeGenApi
  31314. */
  31315. function ɵɵstylePropInterpolate4(prop, prefix, v0, i0, v1, i1, v2, i2, v3, suffix, valueSuffix) {
  31316. const lView = getLView();
  31317. const interpolatedValue = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix);
  31318. checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
  31319. return ɵɵstylePropInterpolate4;
  31320. }
  31321. /**
  31322. *
  31323. * Update an interpolated style property on an element with 5 bound values surrounded by text.
  31324. *
  31325. * Used when the value passed to a property has 5 interpolated values in it:
  31326. *
  31327. * ```html
  31328. * <div style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}suffix"></div>
  31329. * ```
  31330. *
  31331. * Its compiled representation is:
  31332. *
  31333. * ```ts
  31334. * ɵɵstylePropInterpolate5(0, 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, 'suffix');
  31335. * ```
  31336. *
  31337. * @param styleIndex Index of style to update. This index value refers to the
  31338. * index of the style in the style bindings array that was passed into
  31339. * `styling`.
  31340. * @param prefix Static value used for concatenation only.
  31341. * @param v0 Value checked for change.
  31342. * @param i0 Static value used for concatenation only.
  31343. * @param v1 Value checked for change.
  31344. * @param i1 Static value used for concatenation only.
  31345. * @param v2 Value checked for change.
  31346. * @param i2 Static value used for concatenation only.
  31347. * @param v3 Value checked for change.
  31348. * @param i3 Static value used for concatenation only.
  31349. * @param v4 Value checked for change.
  31350. * @param suffix Static value used for concatenation only.
  31351. * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
  31352. * @returns itself, so that it may be chained.
  31353. * @codeGenApi
  31354. */
  31355. function ɵɵstylePropInterpolate5(prop, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix, valueSuffix) {
  31356. const lView = getLView();
  31357. const interpolatedValue = interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix);
  31358. checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
  31359. return ɵɵstylePropInterpolate5;
  31360. }
  31361. /**
  31362. *
  31363. * Update an interpolated style property on an element with 6 bound values surrounded by text.
  31364. *
  31365. * Used when the value passed to a property has 6 interpolated values in it:
  31366. *
  31367. * ```html
  31368. * <div style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}suffix"></div>
  31369. * ```
  31370. *
  31371. * Its compiled representation is:
  31372. *
  31373. * ```ts
  31374. * ɵɵstylePropInterpolate6(0, 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, 'suffix');
  31375. * ```
  31376. *
  31377. * @param styleIndex Index of style to update. This index value refers to the
  31378. * index of the style in the style bindings array that was passed into
  31379. * `styling`.
  31380. * @param prefix Static value used for concatenation only.
  31381. * @param v0 Value checked for change.
  31382. * @param i0 Static value used for concatenation only.
  31383. * @param v1 Value checked for change.
  31384. * @param i1 Static value used for concatenation only.
  31385. * @param v2 Value checked for change.
  31386. * @param i2 Static value used for concatenation only.
  31387. * @param v3 Value checked for change.
  31388. * @param i3 Static value used for concatenation only.
  31389. * @param v4 Value checked for change.
  31390. * @param i4 Static value used for concatenation only.
  31391. * @param v5 Value checked for change.
  31392. * @param suffix Static value used for concatenation only.
  31393. * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
  31394. * @returns itself, so that it may be chained.
  31395. * @codeGenApi
  31396. */
  31397. function ɵɵstylePropInterpolate6(prop, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix, valueSuffix) {
  31398. const lView = getLView();
  31399. const interpolatedValue = interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix);
  31400. checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
  31401. return ɵɵstylePropInterpolate6;
  31402. }
  31403. /**
  31404. *
  31405. * Update an interpolated style property on an element with 7 bound values surrounded by text.
  31406. *
  31407. * Used when the value passed to a property has 7 interpolated values in it:
  31408. *
  31409. * ```html
  31410. * <div style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}suffix"></div>
  31411. * ```
  31412. *
  31413. * Its compiled representation is:
  31414. *
  31415. * ```ts
  31416. * ɵɵstylePropInterpolate7(
  31417. * 0, 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, 'suffix');
  31418. * ```
  31419. *
  31420. * @param styleIndex Index of style to update. This index value refers to the
  31421. * index of the style in the style bindings array that was passed into
  31422. * `styling`.
  31423. * @param prefix Static value used for concatenation only.
  31424. * @param v0 Value checked for change.
  31425. * @param i0 Static value used for concatenation only.
  31426. * @param v1 Value checked for change.
  31427. * @param i1 Static value used for concatenation only.
  31428. * @param v2 Value checked for change.
  31429. * @param i2 Static value used for concatenation only.
  31430. * @param v3 Value checked for change.
  31431. * @param i3 Static value used for concatenation only.
  31432. * @param v4 Value checked for change.
  31433. * @param i4 Static value used for concatenation only.
  31434. * @param v5 Value checked for change.
  31435. * @param i5 Static value used for concatenation only.
  31436. * @param v6 Value checked for change.
  31437. * @param suffix Static value used for concatenation only.
  31438. * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
  31439. * @returns itself, so that it may be chained.
  31440. * @codeGenApi
  31441. */
  31442. function ɵɵstylePropInterpolate7(prop, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix, valueSuffix) {
  31443. const lView = getLView();
  31444. const interpolatedValue = interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix);
  31445. checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
  31446. return ɵɵstylePropInterpolate7;
  31447. }
  31448. /**
  31449. *
  31450. * Update an interpolated style property on an element with 8 bound values surrounded by text.
  31451. *
  31452. * Used when the value passed to a property has 8 interpolated values in it:
  31453. *
  31454. * ```html
  31455. * <div style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}suffix"></div>
  31456. * ```
  31457. *
  31458. * Its compiled representation is:
  31459. *
  31460. * ```ts
  31461. * ɵɵstylePropInterpolate8(0, 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6,
  31462. * '-', v7, 'suffix');
  31463. * ```
  31464. *
  31465. * @param styleIndex Index of style to update. This index value refers to the
  31466. * index of the style in the style bindings array that was passed into
  31467. * `styling`.
  31468. * @param prefix Static value used for concatenation only.
  31469. * @param v0 Value checked for change.
  31470. * @param i0 Static value used for concatenation only.
  31471. * @param v1 Value checked for change.
  31472. * @param i1 Static value used for concatenation only.
  31473. * @param v2 Value checked for change.
  31474. * @param i2 Static value used for concatenation only.
  31475. * @param v3 Value checked for change.
  31476. * @param i3 Static value used for concatenation only.
  31477. * @param v4 Value checked for change.
  31478. * @param i4 Static value used for concatenation only.
  31479. * @param v5 Value checked for change.
  31480. * @param i5 Static value used for concatenation only.
  31481. * @param v6 Value checked for change.
  31482. * @param i6 Static value used for concatenation only.
  31483. * @param v7 Value checked for change.
  31484. * @param suffix Static value used for concatenation only.
  31485. * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
  31486. * @returns itself, so that it may be chained.
  31487. * @codeGenApi
  31488. */
  31489. function ɵɵstylePropInterpolate8(prop, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix, valueSuffix) {
  31490. const lView = getLView();
  31491. const interpolatedValue = interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix);
  31492. checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
  31493. return ɵɵstylePropInterpolate8;
  31494. }
  31495. /**
  31496. * Update an interpolated style property on an element with 9 or more bound values surrounded by
  31497. * text.
  31498. *
  31499. * Used when the number of interpolated values exceeds 8.
  31500. *
  31501. * ```html
  31502. * <div
  31503. * style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}-{{v8}}-{{v9}}suffix">
  31504. * </div>
  31505. * ```
  31506. *
  31507. * Its compiled representation is:
  31508. *
  31509. * ```ts
  31510. * ɵɵstylePropInterpolateV(
  31511. * 0, ['prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, '-', v9,
  31512. * 'suffix']);
  31513. * ```
  31514. *
  31515. * @param styleIndex Index of style to update. This index value refers to the
  31516. * index of the style in the style bindings array that was passed into
  31517. * `styling`..
  31518. * @param values The collection of values and the strings in-between those values, beginning with
  31519. * a string prefix and ending with a string suffix.
  31520. * (e.g. `['prefix', value0, '-', value1, '-', value2, ..., value99, 'suffix']`)
  31521. * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
  31522. * @returns itself, so that it may be chained.
  31523. * @codeGenApi
  31524. */
  31525. function ɵɵstylePropInterpolateV(prop, values, valueSuffix) {
  31526. const lView = getLView();
  31527. const interpolatedValue = interpolationV(lView, values);
  31528. checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
  31529. return ɵɵstylePropInterpolateV;
  31530. }
  31531. /**
  31532. * Create static text node
  31533. *
  31534. * @param index Index of the node in the data array
  31535. * @param value Static string value to write.
  31536. *
  31537. * @codeGenApi
  31538. */
  31539. function ɵɵtext(index, value = '') {
  31540. const lView = getLView();
  31541. const tView = getTView();
  31542. const adjustedIndex = index + HEADER_OFFSET;
  31543. ngDevMode &&
  31544. assertEqual(getBindingIndex(), tView.bindingStartIndex, 'text nodes should be created before any bindings');
  31545. ngDevMode && assertIndexInRange(lView, adjustedIndex);
  31546. const tNode = tView.firstCreatePass
  31547. ? getOrCreateTNode(tView, adjustedIndex, 1 /* TNodeType.Text */, value, null)
  31548. : tView.data[adjustedIndex];
  31549. const textNative = _locateOrCreateTextNode(tView, lView, tNode, value, index);
  31550. lView[adjustedIndex] = textNative;
  31551. if (wasLastNodeCreated()) {
  31552. appendChild(tView, lView, textNative, tNode);
  31553. }
  31554. // Text nodes are self closing.
  31555. setCurrentTNode(tNode, false);
  31556. }
  31557. let _locateOrCreateTextNode = (tView, lView, tNode, value, index) => {
  31558. lastNodeWasCreated(true);
  31559. return createTextNode(lView[RENDERER], value);
  31560. };
  31561. /**
  31562. * Enables hydration code path (to lookup existing elements in DOM)
  31563. * in addition to the regular creation mode of text nodes.
  31564. */
  31565. function locateOrCreateTextNodeImpl(tView, lView, tNode, value, index) {
  31566. const hydrationInfo = lView[HYDRATION];
  31567. const isNodeCreationMode = !hydrationInfo ||
  31568. isInSkipHydrationBlock$1() ||
  31569. isDetachedByI18n(tNode) ||
  31570. isDisconnectedNode$1(hydrationInfo, index);
  31571. lastNodeWasCreated(isNodeCreationMode);
  31572. // Regular creation mode.
  31573. if (isNodeCreationMode) {
  31574. return createTextNode(lView[RENDERER], value);
  31575. }
  31576. // Hydration mode, looking up an existing element in DOM.
  31577. const textNative = locateNextRNode(hydrationInfo, tView, lView, tNode);
  31578. ngDevMode && validateMatchingNode(textNative, Node.TEXT_NODE, null, lView, tNode);
  31579. ngDevMode && markRNodeAsClaimedByHydration(textNative);
  31580. return textNative;
  31581. }
  31582. function enableLocateOrCreateTextNodeImpl() {
  31583. _locateOrCreateTextNode = locateOrCreateTextNodeImpl;
  31584. }
  31585. /**
  31586. *
  31587. * Update text content with a lone bound value
  31588. *
  31589. * Used when a text node has 1 interpolated value in it, an no additional text
  31590. * surrounds that interpolated value:
  31591. *
  31592. * ```html
  31593. * <div>{{v0}}</div>
  31594. * ```
  31595. *
  31596. * Its compiled representation is:
  31597. *
  31598. * ```ts
  31599. * ɵɵtextInterpolate(v0);
  31600. * ```
  31601. * @returns itself, so that it may be chained.
  31602. * @see textInterpolateV
  31603. * @codeGenApi
  31604. */
  31605. function ɵɵtextInterpolate(v0) {
  31606. ɵɵtextInterpolate1('', v0, '');
  31607. return ɵɵtextInterpolate;
  31608. }
  31609. /**
  31610. *
  31611. * Update text content with single bound value surrounded by other text.
  31612. *
  31613. * Used when a text node has 1 interpolated value in it:
  31614. *
  31615. * ```html
  31616. * <div>prefix{{v0}}suffix</div>
  31617. * ```
  31618. *
  31619. * Its compiled representation is:
  31620. *
  31621. * ```ts
  31622. * ɵɵtextInterpolate1('prefix', v0, 'suffix');
  31623. * ```
  31624. * @returns itself, so that it may be chained.
  31625. * @see textInterpolateV
  31626. * @codeGenApi
  31627. */
  31628. function ɵɵtextInterpolate1(prefix, v0, suffix) {
  31629. const lView = getLView();
  31630. const interpolated = interpolation1(lView, prefix, v0, suffix);
  31631. if (interpolated !== NO_CHANGE) {
  31632. textBindingInternal(lView, getSelectedIndex(), interpolated);
  31633. }
  31634. return ɵɵtextInterpolate1;
  31635. }
  31636. /**
  31637. *
  31638. * Update text content with 2 bound values surrounded by other text.
  31639. *
  31640. * Used when a text node has 2 interpolated values in it:
  31641. *
  31642. * ```html
  31643. * <div>prefix{{v0}}-{{v1}}suffix</div>
  31644. * ```
  31645. *
  31646. * Its compiled representation is:
  31647. *
  31648. * ```ts
  31649. * ɵɵtextInterpolate2('prefix', v0, '-', v1, 'suffix');
  31650. * ```
  31651. * @returns itself, so that it may be chained.
  31652. * @see textInterpolateV
  31653. * @codeGenApi
  31654. */
  31655. function ɵɵtextInterpolate2(prefix, v0, i0, v1, suffix) {
  31656. const lView = getLView();
  31657. const interpolated = interpolation2(lView, prefix, v0, i0, v1, suffix);
  31658. if (interpolated !== NO_CHANGE) {
  31659. textBindingInternal(lView, getSelectedIndex(), interpolated);
  31660. }
  31661. return ɵɵtextInterpolate2;
  31662. }
  31663. /**
  31664. *
  31665. * Update text content with 3 bound values surrounded by other text.
  31666. *
  31667. * Used when a text node has 3 interpolated values in it:
  31668. *
  31669. * ```html
  31670. * <div>prefix{{v0}}-{{v1}}-{{v2}}suffix</div>
  31671. * ```
  31672. *
  31673. * Its compiled representation is:
  31674. *
  31675. * ```ts
  31676. * ɵɵtextInterpolate3(
  31677. * 'prefix', v0, '-', v1, '-', v2, 'suffix');
  31678. * ```
  31679. * @returns itself, so that it may be chained.
  31680. * @see textInterpolateV
  31681. * @codeGenApi
  31682. */
  31683. function ɵɵtextInterpolate3(prefix, v0, i0, v1, i1, v2, suffix) {
  31684. const lView = getLView();
  31685. const interpolated = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix);
  31686. if (interpolated !== NO_CHANGE) {
  31687. textBindingInternal(lView, getSelectedIndex(), interpolated);
  31688. }
  31689. return ɵɵtextInterpolate3;
  31690. }
  31691. /**
  31692. *
  31693. * Update text content with 4 bound values surrounded by other text.
  31694. *
  31695. * Used when a text node has 4 interpolated values in it:
  31696. *
  31697. * ```html
  31698. * <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}suffix</div>
  31699. * ```
  31700. *
  31701. * Its compiled representation is:
  31702. *
  31703. * ```ts
  31704. * ɵɵtextInterpolate4(
  31705. * 'prefix', v0, '-', v1, '-', v2, '-', v3, 'suffix');
  31706. * ```
  31707. * @returns itself, so that it may be chained.
  31708. * @see ɵɵtextInterpolateV
  31709. * @codeGenApi
  31710. */
  31711. function ɵɵtextInterpolate4(prefix, v0, i0, v1, i1, v2, i2, v3, suffix) {
  31712. const lView = getLView();
  31713. const interpolated = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix);
  31714. if (interpolated !== NO_CHANGE) {
  31715. textBindingInternal(lView, getSelectedIndex(), interpolated);
  31716. }
  31717. return ɵɵtextInterpolate4;
  31718. }
  31719. /**
  31720. *
  31721. * Update text content with 5 bound values surrounded by other text.
  31722. *
  31723. * Used when a text node has 5 interpolated values in it:
  31724. *
  31725. * ```html
  31726. * <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}suffix</div>
  31727. * ```
  31728. *
  31729. * Its compiled representation is:
  31730. *
  31731. * ```ts
  31732. * ɵɵtextInterpolate5(
  31733. * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, 'suffix');
  31734. * ```
  31735. * @returns itself, so that it may be chained.
  31736. * @see textInterpolateV
  31737. * @codeGenApi
  31738. */
  31739. function ɵɵtextInterpolate5(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix) {
  31740. const lView = getLView();
  31741. const interpolated = interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix);
  31742. if (interpolated !== NO_CHANGE) {
  31743. textBindingInternal(lView, getSelectedIndex(), interpolated);
  31744. }
  31745. return ɵɵtextInterpolate5;
  31746. }
  31747. /**
  31748. *
  31749. * Update text content with 6 bound values surrounded by other text.
  31750. *
  31751. * Used when a text node has 6 interpolated values in it:
  31752. *
  31753. * ```html
  31754. * <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}suffix</div>
  31755. * ```
  31756. *
  31757. * Its compiled representation is:
  31758. *
  31759. * ```ts
  31760. * ɵɵtextInterpolate6(
  31761. * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, 'suffix');
  31762. * ```
  31763. *
  31764. * @param i4 Static value used for concatenation only.
  31765. * @param v5 Value checked for change. @returns itself, so that it may be chained.
  31766. * @see textInterpolateV
  31767. * @codeGenApi
  31768. */
  31769. function ɵɵtextInterpolate6(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix) {
  31770. const lView = getLView();
  31771. const interpolated = interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix);
  31772. if (interpolated !== NO_CHANGE) {
  31773. textBindingInternal(lView, getSelectedIndex(), interpolated);
  31774. }
  31775. return ɵɵtextInterpolate6;
  31776. }
  31777. /**
  31778. *
  31779. * Update text content with 7 bound values surrounded by other text.
  31780. *
  31781. * Used when a text node has 7 interpolated values in it:
  31782. *
  31783. * ```html
  31784. * <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}suffix</div>
  31785. * ```
  31786. *
  31787. * Its compiled representation is:
  31788. *
  31789. * ```ts
  31790. * ɵɵtextInterpolate7(
  31791. * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, 'suffix');
  31792. * ```
  31793. * @returns itself, so that it may be chained.
  31794. * @see textInterpolateV
  31795. * @codeGenApi
  31796. */
  31797. function ɵɵtextInterpolate7(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix) {
  31798. const lView = getLView();
  31799. const interpolated = interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix);
  31800. if (interpolated !== NO_CHANGE) {
  31801. textBindingInternal(lView, getSelectedIndex(), interpolated);
  31802. }
  31803. return ɵɵtextInterpolate7;
  31804. }
  31805. /**
  31806. *
  31807. * Update text content with 8 bound values surrounded by other text.
  31808. *
  31809. * Used when a text node has 8 interpolated values in it:
  31810. *
  31811. * ```html
  31812. * <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}suffix</div>
  31813. * ```
  31814. *
  31815. * Its compiled representation is:
  31816. *
  31817. * ```ts
  31818. * ɵɵtextInterpolate8(
  31819. * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, 'suffix');
  31820. * ```
  31821. * @returns itself, so that it may be chained.
  31822. * @see textInterpolateV
  31823. * @codeGenApi
  31824. */
  31825. function ɵɵtextInterpolate8(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix) {
  31826. const lView = getLView();
  31827. const interpolated = interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix);
  31828. if (interpolated !== NO_CHANGE) {
  31829. textBindingInternal(lView, getSelectedIndex(), interpolated);
  31830. }
  31831. return ɵɵtextInterpolate8;
  31832. }
  31833. /**
  31834. * Update text content with 9 or more bound values other surrounded by text.
  31835. *
  31836. * Used when the number of interpolated values exceeds 8.
  31837. *
  31838. * ```html
  31839. * <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}-{{v8}}-{{v9}}suffix</div>
  31840. * ```
  31841. *
  31842. * Its compiled representation is:
  31843. *
  31844. * ```ts
  31845. * ɵɵtextInterpolateV(
  31846. * ['prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, '-', v9,
  31847. * 'suffix']);
  31848. * ```
  31849. *.
  31850. * @param values The collection of values and the strings in between those values, beginning with
  31851. * a string prefix and ending with a string suffix.
  31852. * (e.g. `['prefix', value0, '-', value1, '-', value2, ..., value99, 'suffix']`)
  31853. *
  31854. * @returns itself, so that it may be chained.
  31855. * @codeGenApi
  31856. */
  31857. function ɵɵtextInterpolateV(values) {
  31858. const lView = getLView();
  31859. const interpolated = interpolationV(lView, values);
  31860. if (interpolated !== NO_CHANGE) {
  31861. textBindingInternal(lView, getSelectedIndex(), interpolated);
  31862. }
  31863. return ɵɵtextInterpolateV;
  31864. }
  31865. /**
  31866. * Updates a text binding at a given index in a given LView.
  31867. */
  31868. function textBindingInternal(lView, index, value) {
  31869. ngDevMode && assertString(value, 'Value should be a string');
  31870. ngDevMode && assertNotSame(value, NO_CHANGE, 'value should not be NO_CHANGE');
  31871. ngDevMode && assertIndexInRange(lView, index);
  31872. const element = getNativeByIndex(index, lView);
  31873. ngDevMode && assertDefined(element, 'native element should exist');
  31874. updateTextNode(lView[RENDERER], element, value);
  31875. }
  31876. /*!
  31877. * @license
  31878. * Copyright Google LLC All Rights Reserved.
  31879. *
  31880. * Use of this source code is governed by an MIT-style license that can be
  31881. * found in the LICENSE file at https://angular.dev/license
  31882. */
  31883. /**
  31884. * Update a two-way bound property on a selected element.
  31885. *
  31886. * Operates on the element selected by index via the {@link select} instruction.
  31887. *
  31888. * @param propName Name of property.
  31889. * @param value New value to write.
  31890. * @param sanitizer An optional function used to sanitize the value.
  31891. * @returns This function returns itself so that it may be chained
  31892. * (e.g. `twoWayProperty('name', ctx.name)('title', ctx.title)`)
  31893. *
  31894. * @codeGenApi
  31895. */
  31896. function ɵɵtwoWayProperty(propName, value, sanitizer) {
  31897. // TODO(crisbeto): perf impact of re-evaluating this on each change detection?
  31898. if (isWritableSignal(value)) {
  31899. value = value();
  31900. }
  31901. const lView = getLView();
  31902. const bindingIndex = nextBindingIndex();
  31903. if (bindingUpdated(lView, bindingIndex, value)) {
  31904. const tView = getTView();
  31905. const tNode = getSelectedTNode();
  31906. elementPropertyInternal(tView, tNode, lView, propName, value, lView[RENDERER], sanitizer, false);
  31907. ngDevMode && storePropertyBindingMetadata(tView.data, tNode, propName, bindingIndex);
  31908. }
  31909. return ɵɵtwoWayProperty;
  31910. }
  31911. /**
  31912. * Function used inside two-way listeners to conditionally set the value of the bound expression.
  31913. *
  31914. * @param target Field on which to set the value.
  31915. * @param value Value to be set to the field.
  31916. *
  31917. * @codeGenApi
  31918. */
  31919. function ɵɵtwoWayBindingSet(target, value) {
  31920. const canWrite = isWritableSignal(target);
  31921. canWrite && target.set(value);
  31922. return canWrite;
  31923. }
  31924. /**
  31925. * Adds an event listener that updates a two-way binding to the current node.
  31926. *
  31927. * @param eventName Name of the event.
  31928. * @param listenerFn The function to be called when event emits.
  31929. *
  31930. * @codeGenApi
  31931. */
  31932. function ɵɵtwoWayListener(eventName, listenerFn) {
  31933. const lView = getLView();
  31934. const tView = getTView();
  31935. const tNode = getCurrentTNode();
  31936. listenerInternal(tView, lView, lView[RENDERER], tNode, eventName, listenerFn);
  31937. return ɵɵtwoWayListener;
  31938. }
  31939. /*!
  31940. * @license
  31941. * Copyright Google LLC All Rights Reserved.
  31942. *
  31943. * Use of this source code is governed by an MIT-style license that can be
  31944. * found in the LICENSE file at https://angular.dev/license
  31945. */
  31946. /** Object that indicates the value of a `@let` declaration that hasn't been initialized yet. */
  31947. const UNINITIALIZED_LET = {};
  31948. /**
  31949. * Declares an `@let` at a specific data slot. Returns itself to allow chaining.
  31950. *
  31951. * @param index Index at which to declare the `@let`.
  31952. *
  31953. * @codeGenApi
  31954. */
  31955. function ɵɵdeclareLet(index) {
  31956. const tView = getTView();
  31957. const lView = getLView();
  31958. const adjustedIndex = index + HEADER_OFFSET;
  31959. const tNode = getOrCreateTNode(tView, adjustedIndex, 128 /* TNodeType.LetDeclaration */, null, null);
  31960. setCurrentTNode(tNode, false);
  31961. store(tView, lView, adjustedIndex, UNINITIALIZED_LET);
  31962. return ɵɵdeclareLet;
  31963. }
  31964. /**
  31965. * Instruction that stores the value of a `@let` declaration on the current view.
  31966. * Returns the value to allow usage inside variable initializers.
  31967. *
  31968. * @codeGenApi
  31969. */
  31970. function ɵɵstoreLet(value) {
  31971. performanceMarkFeature('NgLet');
  31972. const tView = getTView();
  31973. const lView = getLView();
  31974. const index = getSelectedIndex();
  31975. store(tView, lView, index, value);
  31976. return value;
  31977. }
  31978. /**
  31979. * Retrieves the value of a `@let` declaration defined in a parent view.
  31980. *
  31981. * @param index Index of the declaration within the view.
  31982. *
  31983. * @codeGenApi
  31984. */
  31985. function ɵɵreadContextLet(index) {
  31986. const contextLView = getContextLView();
  31987. const value = load(contextLView, HEADER_OFFSET + index);
  31988. if (value === UNINITIALIZED_LET) {
  31989. throw new RuntimeError(314 /* RuntimeErrorCode.UNINITIALIZED_LET_ACCESS */, ngDevMode && 'Attempting to access a @let declaration whose value is not available yet');
  31990. }
  31991. return value;
  31992. }
  31993. /*!
  31994. * @license
  31995. * Copyright Google LLC All Rights Reserved.
  31996. *
  31997. * Use of this source code is governed by an MIT-style license that can be
  31998. * found in the LICENSE file at https://angular.dev/license
  31999. */
  32000. /**
  32001. * Sets the location within the source template at which
  32002. * each element in the current view was defined.
  32003. *
  32004. * @param index Index at which the DOM node was created.
  32005. * @param templatePath Path to the template at which the node was defined.
  32006. * @param locations Element locations to which to attach the source location.
  32007. *
  32008. * @codeGenApi
  32009. */
  32010. function ɵɵattachSourceLocations(templatePath, locations) {
  32011. const tView = getTView();
  32012. const lView = getLView();
  32013. const renderer = lView[RENDERER];
  32014. const attributeName = 'data-ng-source-location';
  32015. for (const [index, offset, line, column] of locations) {
  32016. const tNode = getTNode(tView, index + HEADER_OFFSET);
  32017. // The compiler shouldn't generate the instruction for non-element nodes, but assert just in case.
  32018. ngDevMode && assertTNodeType(tNode, 2 /* TNodeType.Element */);
  32019. const node = getNativeByIndex(index + HEADER_OFFSET, lView);
  32020. // Set the attribute directly in the DOM so it doesn't participate in directive matching.
  32021. if (!node.hasAttribute(attributeName)) {
  32022. const attributeValue = `${templatePath}@o:${offset},l:${line},c:${column}`;
  32023. renderer.setAttribute(node, attributeName, attributeValue);
  32024. }
  32025. }
  32026. }
  32027. /**
  32028. * Resolves the providers which are defined in the DirectiveDef.
  32029. *
  32030. * When inserting the tokens and the factories in their respective arrays, we can assume that
  32031. * this method is called first for the component (if any), and then for other directives on the same
  32032. * node.
  32033. * As a consequence,the providers are always processed in that order:
  32034. * 1) The view providers of the component
  32035. * 2) The providers of the component
  32036. * 3) The providers of the other directives
  32037. * This matches the structure of the injectables arrays of a view (for each node).
  32038. * So the tokens and the factories can be pushed at the end of the arrays, except
  32039. * in one case for multi providers.
  32040. *
  32041. * @param def the directive definition
  32042. * @param providers: Array of `providers`.
  32043. * @param viewProviders: Array of `viewProviders`.
  32044. */
  32045. function providersResolver(def, providers, viewProviders) {
  32046. const tView = getTView();
  32047. if (tView.firstCreatePass) {
  32048. const isComponent = isComponentDef(def);
  32049. // The list of view providers is processed first, and the flags are updated
  32050. resolveProvider(viewProviders, tView.data, tView.blueprint, isComponent, true);
  32051. // Then, the list of providers is processed, and the flags are updated
  32052. resolveProvider(providers, tView.data, tView.blueprint, isComponent, false);
  32053. }
  32054. }
  32055. /**
  32056. * Resolves a provider and publishes it to the DI system.
  32057. */
  32058. function resolveProvider(provider, tInjectables, lInjectablesBlueprint, isComponent, isViewProvider) {
  32059. provider = resolveForwardRef(provider);
  32060. if (Array.isArray(provider)) {
  32061. // Recursively call `resolveProvider`
  32062. // Recursion is OK in this case because this code will not be in hot-path once we implement
  32063. // cloning of the initial state.
  32064. for (let i = 0; i < provider.length; i++) {
  32065. resolveProvider(provider[i], tInjectables, lInjectablesBlueprint, isComponent, isViewProvider);
  32066. }
  32067. }
  32068. else {
  32069. const tView = getTView();
  32070. const lView = getLView();
  32071. const tNode = getCurrentTNode();
  32072. let token = isTypeProvider(provider) ? provider : resolveForwardRef(provider.provide);
  32073. const providerFactory = providerToFactory(provider);
  32074. if (ngDevMode) {
  32075. const injector = new NodeInjector(tNode, lView);
  32076. runInInjectorProfilerContext(injector, token, () => {
  32077. emitProviderConfiguredEvent(provider, isViewProvider);
  32078. });
  32079. }
  32080. const beginIndex = tNode.providerIndexes & 1048575 /* TNodeProviderIndexes.ProvidersStartIndexMask */;
  32081. const endIndex = tNode.directiveStart;
  32082. const cptViewProvidersCount = tNode.providerIndexes >> 20 /* TNodeProviderIndexes.CptViewProvidersCountShift */;
  32083. if (isTypeProvider(provider) || !provider.multi) {
  32084. // Single provider case: the factory is created and pushed immediately
  32085. const factory = new NodeInjectorFactory(providerFactory, isViewProvider, ɵɵdirectiveInject);
  32086. const existingFactoryIndex = indexOf(token, tInjectables, isViewProvider ? beginIndex : beginIndex + cptViewProvidersCount, endIndex);
  32087. if (existingFactoryIndex === -1) {
  32088. diPublicInInjector(getOrCreateNodeInjectorForNode(tNode, lView), tView, token);
  32089. registerDestroyHooksIfSupported(tView, provider, tInjectables.length);
  32090. tInjectables.push(token);
  32091. tNode.directiveStart++;
  32092. tNode.directiveEnd++;
  32093. if (isViewProvider) {
  32094. tNode.providerIndexes += 1048576 /* TNodeProviderIndexes.CptViewProvidersCountShifter */;
  32095. }
  32096. lInjectablesBlueprint.push(factory);
  32097. lView.push(factory);
  32098. }
  32099. else {
  32100. lInjectablesBlueprint[existingFactoryIndex] = factory;
  32101. lView[existingFactoryIndex] = factory;
  32102. }
  32103. }
  32104. else {
  32105. // Multi provider case:
  32106. // We create a multi factory which is going to aggregate all the values.
  32107. // Since the output of such a factory depends on content or view injection,
  32108. // we create two of them, which are linked together.
  32109. //
  32110. // The first one (for view providers) is always in the first block of the injectables array,
  32111. // and the second one (for providers) is always in the second block.
  32112. // This is important because view providers have higher priority. When a multi token
  32113. // is being looked up, the view providers should be found first.
  32114. // Note that it is not possible to have a multi factory in the third block (directive block).
  32115. //
  32116. // The algorithm to process multi providers is as follows:
  32117. // 1) If the multi provider comes from the `viewProviders` of the component:
  32118. // a) If the special view providers factory doesn't exist, it is created and pushed.
  32119. // b) Else, the multi provider is added to the existing multi factory.
  32120. // 2) If the multi provider comes from the `providers` of the component or of another
  32121. // directive:
  32122. // a) If the multi factory doesn't exist, it is created and provider pushed into it.
  32123. // It is also linked to the multi factory for view providers, if it exists.
  32124. // b) Else, the multi provider is added to the existing multi factory.
  32125. const existingProvidersFactoryIndex = indexOf(token, tInjectables, beginIndex + cptViewProvidersCount, endIndex);
  32126. const existingViewProvidersFactoryIndex = indexOf(token, tInjectables, beginIndex, beginIndex + cptViewProvidersCount);
  32127. const doesProvidersFactoryExist = existingProvidersFactoryIndex >= 0 && lInjectablesBlueprint[existingProvidersFactoryIndex];
  32128. const doesViewProvidersFactoryExist = existingViewProvidersFactoryIndex >= 0 &&
  32129. lInjectablesBlueprint[existingViewProvidersFactoryIndex];
  32130. if ((isViewProvider && !doesViewProvidersFactoryExist) ||
  32131. (!isViewProvider && !doesProvidersFactoryExist)) {
  32132. // Cases 1.a and 2.a
  32133. diPublicInInjector(getOrCreateNodeInjectorForNode(tNode, lView), tView, token);
  32134. const factory = multiFactory(isViewProvider ? multiViewProvidersFactoryResolver : multiProvidersFactoryResolver, lInjectablesBlueprint.length, isViewProvider, isComponent, providerFactory);
  32135. if (!isViewProvider && doesViewProvidersFactoryExist) {
  32136. lInjectablesBlueprint[existingViewProvidersFactoryIndex].providerFactory = factory;
  32137. }
  32138. registerDestroyHooksIfSupported(tView, provider, tInjectables.length, 0);
  32139. tInjectables.push(token);
  32140. tNode.directiveStart++;
  32141. tNode.directiveEnd++;
  32142. if (isViewProvider) {
  32143. tNode.providerIndexes += 1048576 /* TNodeProviderIndexes.CptViewProvidersCountShifter */;
  32144. }
  32145. lInjectablesBlueprint.push(factory);
  32146. lView.push(factory);
  32147. }
  32148. else {
  32149. // Cases 1.b and 2.b
  32150. const indexInFactory = multiFactoryAdd(lInjectablesBlueprint[isViewProvider ? existingViewProvidersFactoryIndex : existingProvidersFactoryIndex], providerFactory, !isViewProvider && isComponent);
  32151. registerDestroyHooksIfSupported(tView, provider, existingProvidersFactoryIndex > -1
  32152. ? existingProvidersFactoryIndex
  32153. : existingViewProvidersFactoryIndex, indexInFactory);
  32154. }
  32155. if (!isViewProvider && isComponent && doesViewProvidersFactoryExist) {
  32156. lInjectablesBlueprint[existingViewProvidersFactoryIndex].componentProviders++;
  32157. }
  32158. }
  32159. }
  32160. }
  32161. /**
  32162. * Registers the `ngOnDestroy` hook of a provider, if the provider supports destroy hooks.
  32163. * @param tView `TView` in which to register the hook.
  32164. * @param provider Provider whose hook should be registered.
  32165. * @param contextIndex Index under which to find the context for the hook when it's being invoked.
  32166. * @param indexInFactory Only required for `multi` providers. Index of the provider in the multi
  32167. * provider factory.
  32168. */
  32169. function registerDestroyHooksIfSupported(tView, provider, contextIndex, indexInFactory) {
  32170. const providerIsTypeProvider = isTypeProvider(provider);
  32171. const providerIsClassProvider = isClassProvider(provider);
  32172. if (providerIsTypeProvider || providerIsClassProvider) {
  32173. // Resolve forward references as `useClass` can hold a forward reference.
  32174. const classToken = providerIsClassProvider ? resolveForwardRef(provider.useClass) : provider;
  32175. const prototype = classToken.prototype;
  32176. const ngOnDestroy = prototype.ngOnDestroy;
  32177. if (ngOnDestroy) {
  32178. const hooks = tView.destroyHooks || (tView.destroyHooks = []);
  32179. if (!providerIsTypeProvider && provider.multi) {
  32180. ngDevMode &&
  32181. assertDefined(indexInFactory, 'indexInFactory when registering multi factory destroy hook');
  32182. const existingCallbacksIndex = hooks.indexOf(contextIndex);
  32183. if (existingCallbacksIndex === -1) {
  32184. hooks.push(contextIndex, [indexInFactory, ngOnDestroy]);
  32185. }
  32186. else {
  32187. hooks[existingCallbacksIndex + 1].push(indexInFactory, ngOnDestroy);
  32188. }
  32189. }
  32190. else {
  32191. hooks.push(contextIndex, ngOnDestroy);
  32192. }
  32193. }
  32194. }
  32195. }
  32196. /**
  32197. * Add a factory in a multi factory.
  32198. * @returns Index at which the factory was inserted.
  32199. */
  32200. function multiFactoryAdd(multiFactory, factory, isComponentProvider) {
  32201. if (isComponentProvider) {
  32202. multiFactory.componentProviders++;
  32203. }
  32204. return multiFactory.multi.push(factory) - 1;
  32205. }
  32206. /**
  32207. * Returns the index of item in the array, but only in the begin to end range.
  32208. */
  32209. function indexOf(item, arr, begin, end) {
  32210. for (let i = begin; i < end; i++) {
  32211. if (arr[i] === item)
  32212. return i;
  32213. }
  32214. return -1;
  32215. }
  32216. /**
  32217. * Use this with `multi` `providers`.
  32218. */
  32219. function multiProvidersFactoryResolver(_, flags, tData, lData, tNode) {
  32220. return multiResolve(this.multi, []);
  32221. }
  32222. /**
  32223. * Use this with `multi` `viewProviders`.
  32224. *
  32225. * This factory knows how to concatenate itself with the existing `multi` `providers`.
  32226. */
  32227. function multiViewProvidersFactoryResolver(_, _flags, _tData, lView, tNode) {
  32228. const factories = this.multi;
  32229. let result;
  32230. if (this.providerFactory) {
  32231. const componentCount = this.providerFactory.componentProviders;
  32232. const multiProviders = getNodeInjectable(lView, lView[TVIEW], this.providerFactory.index, tNode);
  32233. // Copy the section of the array which contains `multi` `providers` from the component
  32234. result = multiProviders.slice(0, componentCount);
  32235. // Insert the `viewProvider` instances.
  32236. multiResolve(factories, result);
  32237. // Copy the section of the array which contains `multi` `providers` from other directives
  32238. for (let i = componentCount; i < multiProviders.length; i++) {
  32239. result.push(multiProviders[i]);
  32240. }
  32241. }
  32242. else {
  32243. result = [];
  32244. // Insert the `viewProvider` instances.
  32245. multiResolve(factories, result);
  32246. }
  32247. return result;
  32248. }
  32249. /**
  32250. * Maps an array of factories into an array of values.
  32251. */
  32252. function multiResolve(factories, result) {
  32253. for (let i = 0; i < factories.length; i++) {
  32254. const factory = factories[i];
  32255. result.push(factory());
  32256. }
  32257. return result;
  32258. }
  32259. /**
  32260. * Creates a multi factory.
  32261. */
  32262. function multiFactory(factoryFn, index, isViewProvider, isComponent, f) {
  32263. const factory = new NodeInjectorFactory(factoryFn, isViewProvider, ɵɵdirectiveInject);
  32264. factory.multi = [];
  32265. factory.index = index;
  32266. factory.componentProviders = 0;
  32267. multiFactoryAdd(factory, f, isComponent && !isViewProvider);
  32268. return factory;
  32269. }
  32270. /**
  32271. * This feature resolves the providers of a directive (or component),
  32272. * and publish them into the DI system, making it visible to others for injection.
  32273. *
  32274. * For example:
  32275. * ```ts
  32276. * class ComponentWithProviders {
  32277. * constructor(private greeter: GreeterDE) {}
  32278. *
  32279. * static ɵcmp = defineComponent({
  32280. * type: ComponentWithProviders,
  32281. * selectors: [['component-with-providers']],
  32282. * factory: () => new ComponentWithProviders(directiveInject(GreeterDE as any)),
  32283. * decls: 1,
  32284. * vars: 1,
  32285. * template: function(fs: RenderFlags, ctx: ComponentWithProviders) {
  32286. * if (fs & RenderFlags.Create) {
  32287. * ɵɵtext(0);
  32288. * }
  32289. * if (fs & RenderFlags.Update) {
  32290. * ɵɵtextInterpolate(ctx.greeter.greet());
  32291. * }
  32292. * },
  32293. * features: [ɵɵProvidersFeature([GreeterDE])]
  32294. * });
  32295. * }
  32296. * ```
  32297. *
  32298. * @param definition
  32299. *
  32300. * @codeGenApi
  32301. */
  32302. function ɵɵProvidersFeature(providers, viewProviders = []) {
  32303. return (definition) => {
  32304. definition.providersResolver = (def, processProvidersFn) => {
  32305. return providersResolver(def, //
  32306. processProvidersFn ? processProvidersFn(providers) : providers, //
  32307. viewProviders);
  32308. };
  32309. };
  32310. }
  32311. /**
  32312. * A feature that adds support for external runtime styles for a component.
  32313. * An external runtime style is a URL to a CSS stylesheet that contains the styles
  32314. * for a given component. For browsers, this URL will be used in an appended `link` element
  32315. * when the component is rendered. This feature is typically used for Hot Module Replacement
  32316. * (HMR) of component stylesheets by leveraging preexisting global stylesheet HMR available
  32317. * in most development servers.
  32318. *
  32319. * @codeGenApi
  32320. */
  32321. function ɵɵExternalStylesFeature(styleUrls) {
  32322. return (definition) => {
  32323. if (styleUrls.length < 1) {
  32324. return;
  32325. }
  32326. definition.getExternalStyles = (encapsulationId) => {
  32327. // Add encapsulation ID search parameter `ngcomp` to support external style encapsulation as well as the encapsulation mode
  32328. // for usage tracking.
  32329. const urls = styleUrls.map((value) => value +
  32330. '?ngcomp' +
  32331. (encapsulationId ? '=' + encodeURIComponent(encapsulationId) : '') +
  32332. '&e=' +
  32333. definition.encapsulation);
  32334. return urls;
  32335. };
  32336. };
  32337. }
  32338. /**
  32339. * Generated next to NgModules to monkey-patch directive and pipe references onto a component's
  32340. * definition, when generating a direct reference in the component file would otherwise create an
  32341. * import cycle.
  32342. *
  32343. * See [this explanation](https://hackmd.io/Odw80D0pR6yfsOjg_7XCJg?view) for more details.
  32344. *
  32345. * @codeGenApi
  32346. */
  32347. function ɵɵsetComponentScope(type, directives, pipes) {
  32348. const def = type.ɵcmp;
  32349. def.directiveDefs = extractDefListOrFactory(directives, /* pipeDef */ false);
  32350. def.pipeDefs = extractDefListOrFactory(pipes, /* pipeDef */ true);
  32351. }
  32352. /**
  32353. * Adds the module metadata that is necessary to compute the module's transitive scope to an
  32354. * existing module definition.
  32355. *
  32356. * Scope metadata of modules is not used in production builds, so calls to this function can be
  32357. * marked pure to tree-shake it from the bundle, allowing for all referenced declarations
  32358. * to become eligible for tree-shaking as well.
  32359. *
  32360. * @codeGenApi
  32361. */
  32362. function ɵɵsetNgModuleScope(type, scope) {
  32363. return noSideEffects(() => {
  32364. const ngModuleDef = getNgModuleDef(type, true);
  32365. ngModuleDef.declarations = convertToTypeArray(scope.declarations || EMPTY_ARRAY);
  32366. ngModuleDef.imports = convertToTypeArray(scope.imports || EMPTY_ARRAY);
  32367. ngModuleDef.exports = convertToTypeArray(scope.exports || EMPTY_ARRAY);
  32368. if (scope.bootstrap) {
  32369. // This only happens in local compilation mode.
  32370. ngModuleDef.bootstrap = convertToTypeArray(scope.bootstrap);
  32371. }
  32372. depsTracker.registerNgModule(type, scope);
  32373. });
  32374. }
  32375. function convertToTypeArray(values) {
  32376. if (typeof values === 'function') {
  32377. return values;
  32378. }
  32379. const flattenValues = flatten(values);
  32380. if (flattenValues.some(isForwardRef)) {
  32381. return () => flattenValues.map(resolveForwardRef).map(maybeUnwrapModuleWithProviders);
  32382. }
  32383. else {
  32384. return flattenValues.map(maybeUnwrapModuleWithProviders);
  32385. }
  32386. }
  32387. function maybeUnwrapModuleWithProviders(value) {
  32388. return isModuleWithProviders(value) ? value.ngModule : value;
  32389. }
  32390. /**
  32391. * Bindings for pure functions are stored after regular bindings.
  32392. *
  32393. * |-------decls------|---------vars---------| |----- hostVars (dir1) ------|
  32394. * ------------------------------------------------------------------------------------------
  32395. * | nodes/refs/pipes | bindings | fn slots | injector | dir1 | host bindings | host slots |
  32396. * ------------------------------------------------------------------------------------------
  32397. * ^ ^
  32398. * TView.bindingStartIndex TView.expandoStartIndex
  32399. *
  32400. * Pure function instructions are given an offset from the binding root. Adding the offset to the
  32401. * binding root gives the first index where the bindings are stored. In component views, the binding
  32402. * root is the bindingStartIndex. In host bindings, the binding root is the expandoStartIndex +
  32403. * any directive instances + any hostVars in directives evaluated before it.
  32404. *
  32405. * See VIEW_DATA.md for more information about host binding resolution.
  32406. */
  32407. /**
  32408. * If the value hasn't been saved, calls the pure function to store and return the
  32409. * value. If it has been saved, returns the saved value.
  32410. *
  32411. * @param slotOffset the offset from binding root to the reserved slot
  32412. * @param pureFn Function that returns a value
  32413. * @param thisArg Optional calling context of pureFn
  32414. * @returns value
  32415. *
  32416. * @codeGenApi
  32417. */
  32418. function ɵɵpureFunction0(slotOffset, pureFn, thisArg) {
  32419. const bindingIndex = getBindingRoot() + slotOffset;
  32420. const lView = getLView();
  32421. return lView[bindingIndex] === NO_CHANGE
  32422. ? updateBinding(lView, bindingIndex, thisArg ? pureFn.call(thisArg) : pureFn())
  32423. : getBinding(lView, bindingIndex);
  32424. }
  32425. /**
  32426. * If the value of the provided exp has changed, calls the pure function to return
  32427. * an updated value. Or if the value has not changed, returns cached value.
  32428. *
  32429. * @param slotOffset the offset from binding root to the reserved slot
  32430. * @param pureFn Function that returns an updated value
  32431. * @param exp Updated expression value
  32432. * @param thisArg Optional calling context of pureFn
  32433. * @returns Updated or cached value
  32434. *
  32435. * @codeGenApi
  32436. */
  32437. function ɵɵpureFunction1(slotOffset, pureFn, exp, thisArg) {
  32438. return pureFunction1Internal(getLView(), getBindingRoot(), slotOffset, pureFn, exp, thisArg);
  32439. }
  32440. /**
  32441. * If the value of any provided exp has changed, calls the pure function to return
  32442. * an updated value. Or if no values have changed, returns cached value.
  32443. *
  32444. * @param slotOffset the offset from binding root to the reserved slot
  32445. * @param pureFn
  32446. * @param exp1
  32447. * @param exp2
  32448. * @param thisArg Optional calling context of pureFn
  32449. * @returns Updated or cached value
  32450. *
  32451. * @codeGenApi
  32452. */
  32453. function ɵɵpureFunction2(slotOffset, pureFn, exp1, exp2, thisArg) {
  32454. return pureFunction2Internal(getLView(), getBindingRoot(), slotOffset, pureFn, exp1, exp2, thisArg);
  32455. }
  32456. /**
  32457. * If the value of any provided exp has changed, calls the pure function to return
  32458. * an updated value. Or if no values have changed, returns cached value.
  32459. *
  32460. * @param slotOffset the offset from binding root to the reserved slot
  32461. * @param pureFn
  32462. * @param exp1
  32463. * @param exp2
  32464. * @param exp3
  32465. * @param thisArg Optional calling context of pureFn
  32466. * @returns Updated or cached value
  32467. *
  32468. * @codeGenApi
  32469. */
  32470. function ɵɵpureFunction3(slotOffset, pureFn, exp1, exp2, exp3, thisArg) {
  32471. return pureFunction3Internal(getLView(), getBindingRoot(), slotOffset, pureFn, exp1, exp2, exp3, thisArg);
  32472. }
  32473. /**
  32474. * If the value of any provided exp has changed, calls the pure function to return
  32475. * an updated value. Or if no values have changed, returns cached value.
  32476. *
  32477. * @param slotOffset the offset from binding root to the reserved slot
  32478. * @param pureFn
  32479. * @param exp1
  32480. * @param exp2
  32481. * @param exp3
  32482. * @param exp4
  32483. * @param thisArg Optional calling context of pureFn
  32484. * @returns Updated or cached value
  32485. *
  32486. * @codeGenApi
  32487. */
  32488. function ɵɵpureFunction4(slotOffset, pureFn, exp1, exp2, exp3, exp4, thisArg) {
  32489. return pureFunction4Internal(getLView(), getBindingRoot(), slotOffset, pureFn, exp1, exp2, exp3, exp4, thisArg);
  32490. }
  32491. /**
  32492. * If the value of any provided exp has changed, calls the pure function to return
  32493. * an updated value. Or if no values have changed, returns cached value.
  32494. *
  32495. * @param slotOffset the offset from binding root to the reserved slot
  32496. * @param pureFn
  32497. * @param exp1
  32498. * @param exp2
  32499. * @param exp3
  32500. * @param exp4
  32501. * @param exp5
  32502. * @param thisArg Optional calling context of pureFn
  32503. * @returns Updated or cached value
  32504. *
  32505. * @codeGenApi
  32506. */
  32507. function ɵɵpureFunction5(slotOffset, pureFn, exp1, exp2, exp3, exp4, exp5, thisArg) {
  32508. const bindingIndex = getBindingRoot() + slotOffset;
  32509. const lView = getLView();
  32510. const different = bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4);
  32511. return bindingUpdated(lView, bindingIndex + 4, exp5) || different
  32512. ? updateBinding(lView, bindingIndex + 5, thisArg
  32513. ? pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5)
  32514. : pureFn(exp1, exp2, exp3, exp4, exp5))
  32515. : getBinding(lView, bindingIndex + 5);
  32516. }
  32517. /**
  32518. * If the value of any provided exp has changed, calls the pure function to return
  32519. * an updated value. Or if no values have changed, returns cached value.
  32520. *
  32521. * @param slotOffset the offset from binding root to the reserved slot
  32522. * @param pureFn
  32523. * @param exp1
  32524. * @param exp2
  32525. * @param exp3
  32526. * @param exp4
  32527. * @param exp5
  32528. * @param exp6
  32529. * @param thisArg Optional calling context of pureFn
  32530. * @returns Updated or cached value
  32531. *
  32532. * @codeGenApi
  32533. */
  32534. function ɵɵpureFunction6(slotOffset, pureFn, exp1, exp2, exp3, exp4, exp5, exp6, thisArg) {
  32535. const bindingIndex = getBindingRoot() + slotOffset;
  32536. const lView = getLView();
  32537. const different = bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4);
  32538. return bindingUpdated2(lView, bindingIndex + 4, exp5, exp6) || different
  32539. ? updateBinding(lView, bindingIndex + 6, thisArg
  32540. ? pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5, exp6)
  32541. : pureFn(exp1, exp2, exp3, exp4, exp5, exp6))
  32542. : getBinding(lView, bindingIndex + 6);
  32543. }
  32544. /**
  32545. * If the value of any provided exp has changed, calls the pure function to return
  32546. * an updated value. Or if no values have changed, returns cached value.
  32547. *
  32548. * @param slotOffset the offset from binding root to the reserved slot
  32549. * @param pureFn
  32550. * @param exp1
  32551. * @param exp2
  32552. * @param exp3
  32553. * @param exp4
  32554. * @param exp5
  32555. * @param exp6
  32556. * @param exp7
  32557. * @param thisArg Optional calling context of pureFn
  32558. * @returns Updated or cached value
  32559. *
  32560. * @codeGenApi
  32561. */
  32562. function ɵɵpureFunction7(slotOffset, pureFn, exp1, exp2, exp3, exp4, exp5, exp6, exp7, thisArg) {
  32563. const bindingIndex = getBindingRoot() + slotOffset;
  32564. const lView = getLView();
  32565. let different = bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4);
  32566. return bindingUpdated3(lView, bindingIndex + 4, exp5, exp6, exp7) || different
  32567. ? updateBinding(lView, bindingIndex + 7, thisArg
  32568. ? pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5, exp6, exp7)
  32569. : pureFn(exp1, exp2, exp3, exp4, exp5, exp6, exp7))
  32570. : getBinding(lView, bindingIndex + 7);
  32571. }
  32572. /**
  32573. * If the value of any provided exp has changed, calls the pure function to return
  32574. * an updated value. Or if no values have changed, returns cached value.
  32575. *
  32576. * @param slotOffset the offset from binding root to the reserved slot
  32577. * @param pureFn
  32578. * @param exp1
  32579. * @param exp2
  32580. * @param exp3
  32581. * @param exp4
  32582. * @param exp5
  32583. * @param exp6
  32584. * @param exp7
  32585. * @param exp8
  32586. * @param thisArg Optional calling context of pureFn
  32587. * @returns Updated or cached value
  32588. *
  32589. * @codeGenApi
  32590. */
  32591. function ɵɵpureFunction8(slotOffset, pureFn, exp1, exp2, exp3, exp4, exp5, exp6, exp7, exp8, thisArg) {
  32592. const bindingIndex = getBindingRoot() + slotOffset;
  32593. const lView = getLView();
  32594. const different = bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4);
  32595. return bindingUpdated4(lView, bindingIndex + 4, exp5, exp6, exp7, exp8) || different
  32596. ? updateBinding(lView, bindingIndex + 8, thisArg
  32597. ? pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5, exp6, exp7, exp8)
  32598. : pureFn(exp1, exp2, exp3, exp4, exp5, exp6, exp7, exp8))
  32599. : getBinding(lView, bindingIndex + 8);
  32600. }
  32601. /**
  32602. * pureFunction instruction that can support any number of bindings.
  32603. *
  32604. * If the value of any provided exp has changed, calls the pure function to return
  32605. * an updated value. Or if no values have changed, returns cached value.
  32606. *
  32607. * @param slotOffset the offset from binding root to the reserved slot
  32608. * @param pureFn A pure function that takes binding values and builds an object or array
  32609. * containing those values.
  32610. * @param exps An array of binding values
  32611. * @param thisArg Optional calling context of pureFn
  32612. * @returns Updated or cached value
  32613. *
  32614. * @codeGenApi
  32615. */
  32616. function ɵɵpureFunctionV(slotOffset, pureFn, exps, thisArg) {
  32617. return pureFunctionVInternal(getLView(), getBindingRoot(), slotOffset, pureFn, exps, thisArg);
  32618. }
  32619. /**
  32620. * Results of a pure function invocation are stored in LView in a dedicated slot that is initialized
  32621. * to NO_CHANGE. In rare situations a pure pipe might throw an exception on the very first
  32622. * invocation and not produce any valid results. In this case LView would keep holding the NO_CHANGE
  32623. * value. The NO_CHANGE is not something that we can use in expressions / bindings thus we convert
  32624. * it to `undefined`.
  32625. */
  32626. function getPureFunctionReturnValue(lView, returnValueIndex) {
  32627. ngDevMode && assertIndexInRange(lView, returnValueIndex);
  32628. const lastReturnValue = lView[returnValueIndex];
  32629. return lastReturnValue === NO_CHANGE ? undefined : lastReturnValue;
  32630. }
  32631. /**
  32632. * If the value of the provided exp has changed, calls the pure function to return
  32633. * an updated value. Or if the value has not changed, returns cached value.
  32634. *
  32635. * @param lView LView in which the function is being executed.
  32636. * @param bindingRoot Binding root index.
  32637. * @param slotOffset the offset from binding root to the reserved slot
  32638. * @param pureFn Function that returns an updated value
  32639. * @param exp Updated expression value
  32640. * @param thisArg Optional calling context of pureFn
  32641. * @returns Updated or cached value
  32642. */
  32643. function pureFunction1Internal(lView, bindingRoot, slotOffset, pureFn, exp, thisArg) {
  32644. const bindingIndex = bindingRoot + slotOffset;
  32645. return bindingUpdated(lView, bindingIndex, exp)
  32646. ? updateBinding(lView, bindingIndex + 1, thisArg ? pureFn.call(thisArg, exp) : pureFn(exp))
  32647. : getPureFunctionReturnValue(lView, bindingIndex + 1);
  32648. }
  32649. /**
  32650. * If the value of any provided exp has changed, calls the pure function to return
  32651. * an updated value. Or if no values have changed, returns cached value.
  32652. *
  32653. * @param lView LView in which the function is being executed.
  32654. * @param bindingRoot Binding root index.
  32655. * @param slotOffset the offset from binding root to the reserved slot
  32656. * @param pureFn
  32657. * @param exp1
  32658. * @param exp2
  32659. * @param thisArg Optional calling context of pureFn
  32660. * @returns Updated or cached value
  32661. */
  32662. function pureFunction2Internal(lView, bindingRoot, slotOffset, pureFn, exp1, exp2, thisArg) {
  32663. const bindingIndex = bindingRoot + slotOffset;
  32664. return bindingUpdated2(lView, bindingIndex, exp1, exp2)
  32665. ? updateBinding(lView, bindingIndex + 2, thisArg ? pureFn.call(thisArg, exp1, exp2) : pureFn(exp1, exp2))
  32666. : getPureFunctionReturnValue(lView, bindingIndex + 2);
  32667. }
  32668. /**
  32669. * If the value of any provided exp has changed, calls the pure function to return
  32670. * an updated value. Or if no values have changed, returns cached value.
  32671. *
  32672. * @param lView LView in which the function is being executed.
  32673. * @param bindingRoot Binding root index.
  32674. * @param slotOffset the offset from binding root to the reserved slot
  32675. * @param pureFn
  32676. * @param exp1
  32677. * @param exp2
  32678. * @param exp3
  32679. * @param thisArg Optional calling context of pureFn
  32680. * @returns Updated or cached value
  32681. */
  32682. function pureFunction3Internal(lView, bindingRoot, slotOffset, pureFn, exp1, exp2, exp3, thisArg) {
  32683. const bindingIndex = bindingRoot + slotOffset;
  32684. return bindingUpdated3(lView, bindingIndex, exp1, exp2, exp3)
  32685. ? updateBinding(lView, bindingIndex + 3, thisArg ? pureFn.call(thisArg, exp1, exp2, exp3) : pureFn(exp1, exp2, exp3))
  32686. : getPureFunctionReturnValue(lView, bindingIndex + 3);
  32687. }
  32688. /**
  32689. * If the value of any provided exp has changed, calls the pure function to return
  32690. * an updated value. Or if no values have changed, returns cached value.
  32691. *
  32692. * @param lView LView in which the function is being executed.
  32693. * @param bindingRoot Binding root index.
  32694. * @param slotOffset the offset from binding root to the reserved slot
  32695. * @param pureFn
  32696. * @param exp1
  32697. * @param exp2
  32698. * @param exp3
  32699. * @param exp4
  32700. * @param thisArg Optional calling context of pureFn
  32701. * @returns Updated or cached value
  32702. *
  32703. */
  32704. function pureFunction4Internal(lView, bindingRoot, slotOffset, pureFn, exp1, exp2, exp3, exp4, thisArg) {
  32705. const bindingIndex = bindingRoot + slotOffset;
  32706. return bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4)
  32707. ? updateBinding(lView, bindingIndex + 4, thisArg ? pureFn.call(thisArg, exp1, exp2, exp3, exp4) : pureFn(exp1, exp2, exp3, exp4))
  32708. : getPureFunctionReturnValue(lView, bindingIndex + 4);
  32709. }
  32710. /**
  32711. * pureFunction instruction that can support any number of bindings.
  32712. *
  32713. * If the value of any provided exp has changed, calls the pure function to return
  32714. * an updated value. Or if no values have changed, returns cached value.
  32715. *
  32716. * @param lView LView in which the function is being executed.
  32717. * @param bindingRoot Binding root index.
  32718. * @param slotOffset the offset from binding root to the reserved slot
  32719. * @param pureFn A pure function that takes binding values and builds an object or array
  32720. * containing those values.
  32721. * @param exps An array of binding values
  32722. * @param thisArg Optional calling context of pureFn
  32723. * @returns Updated or cached value
  32724. */
  32725. function pureFunctionVInternal(lView, bindingRoot, slotOffset, pureFn, exps, thisArg) {
  32726. let bindingIndex = bindingRoot + slotOffset;
  32727. let different = false;
  32728. for (let i = 0; i < exps.length; i++) {
  32729. bindingUpdated(lView, bindingIndex++, exps[i]) && (different = true);
  32730. }
  32731. return different
  32732. ? updateBinding(lView, bindingIndex, pureFn.apply(thisArg, exps))
  32733. : getPureFunctionReturnValue(lView, bindingIndex);
  32734. }
  32735. /**
  32736. * Create a pipe.
  32737. *
  32738. * @param index Pipe index where the pipe will be stored.
  32739. * @param pipeName The name of the pipe
  32740. * @returns T the instance of the pipe.
  32741. *
  32742. * @codeGenApi
  32743. */
  32744. function ɵɵpipe(index, pipeName) {
  32745. const tView = getTView();
  32746. let pipeDef;
  32747. const adjustedIndex = index + HEADER_OFFSET;
  32748. if (tView.firstCreatePass) {
  32749. // The `getPipeDef` throws if a pipe with a given name is not found
  32750. // (so we use non-null assertion below).
  32751. pipeDef = getPipeDef(pipeName, tView.pipeRegistry);
  32752. tView.data[adjustedIndex] = pipeDef;
  32753. if (pipeDef.onDestroy) {
  32754. (tView.destroyHooks ??= []).push(adjustedIndex, pipeDef.onDestroy);
  32755. }
  32756. }
  32757. else {
  32758. pipeDef = tView.data[adjustedIndex];
  32759. }
  32760. const pipeFactory = pipeDef.factory || (pipeDef.factory = getFactoryDef(pipeDef.type, true));
  32761. let previousInjectorProfilerContext;
  32762. if (ngDevMode) {
  32763. previousInjectorProfilerContext = setInjectorProfilerContext({
  32764. injector: new NodeInjector(getCurrentTNode(), getLView()),
  32765. token: pipeDef.type,
  32766. });
  32767. }
  32768. const previousInjectImplementation = setInjectImplementation(ɵɵdirectiveInject);
  32769. try {
  32770. // DI for pipes is supposed to behave like directives when placed on a component
  32771. // host node, which means that we have to disable access to `viewProviders`.
  32772. const previousIncludeViewProviders = setIncludeViewProviders(false);
  32773. const pipeInstance = pipeFactory();
  32774. setIncludeViewProviders(previousIncludeViewProviders);
  32775. store(tView, getLView(), adjustedIndex, pipeInstance);
  32776. return pipeInstance;
  32777. }
  32778. finally {
  32779. // we have to restore the injector implementation in finally, just in case the creation of the
  32780. // pipe throws an error.
  32781. setInjectImplementation(previousInjectImplementation);
  32782. ngDevMode && setInjectorProfilerContext(previousInjectorProfilerContext);
  32783. }
  32784. }
  32785. /**
  32786. * Searches the pipe registry for a pipe with the given name. If one is found,
  32787. * returns the pipe. Otherwise, an error is thrown because the pipe cannot be resolved.
  32788. *
  32789. * @param name Name of pipe to resolve
  32790. * @param registry Full list of available pipes
  32791. * @returns Matching PipeDef
  32792. */
  32793. function getPipeDef(name, registry) {
  32794. if (registry) {
  32795. if (ngDevMode) {
  32796. const pipes = registry.filter((pipe) => pipe.name === name);
  32797. // TODO: Throw an error in the next major
  32798. if (pipes.length > 1) {
  32799. console.warn(formatRuntimeError(313 /* RuntimeErrorCode.MULTIPLE_MATCHING_PIPES */, getMultipleMatchingPipesMessage(name)));
  32800. }
  32801. }
  32802. for (let i = registry.length - 1; i >= 0; i--) {
  32803. const pipeDef = registry[i];
  32804. if (name === pipeDef.name) {
  32805. return pipeDef;
  32806. }
  32807. }
  32808. }
  32809. if (ngDevMode) {
  32810. throw new RuntimeError(-302 /* RuntimeErrorCode.PIPE_NOT_FOUND */, getPipeNotFoundErrorMessage(name));
  32811. }
  32812. return;
  32813. }
  32814. /**
  32815. * Generates a helpful error message for the user when multiple pipes match the name.
  32816. *
  32817. * @param name Name of the pipe
  32818. * @returns The error message
  32819. */
  32820. function getMultipleMatchingPipesMessage(name) {
  32821. const lView = getLView();
  32822. const declarationLView = lView[DECLARATION_COMPONENT_VIEW];
  32823. const context = declarationLView[CONTEXT];
  32824. const hostIsStandalone = isHostComponentStandalone(lView);
  32825. const componentInfoMessage = context ? ` in the '${context.constructor.name}' component` : '';
  32826. const verifyMessage = `check ${hostIsStandalone ? "'@Component.imports' of this component" : 'the imports of this module'}`;
  32827. const errorMessage = `Multiple pipes match the name \`${name}\`${componentInfoMessage}. ${verifyMessage}`;
  32828. return errorMessage;
  32829. }
  32830. /**
  32831. * Generates a helpful error message for the user when a pipe is not found.
  32832. *
  32833. * @param name Name of the missing pipe
  32834. * @returns The error message
  32835. */
  32836. function getPipeNotFoundErrorMessage(name) {
  32837. const lView = getLView();
  32838. const declarationLView = lView[DECLARATION_COMPONENT_VIEW];
  32839. const context = declarationLView[CONTEXT];
  32840. const hostIsStandalone = isHostComponentStandalone(lView);
  32841. const componentInfoMessage = context ? ` in the '${context.constructor.name}' component` : '';
  32842. const verifyMessage = `Verify that it is ${hostIsStandalone
  32843. ? "included in the '@Component.imports' of this component"
  32844. : 'declared or imported in this module'}`;
  32845. const errorMessage = `The pipe '${name}' could not be found${componentInfoMessage}. ${verifyMessage}`;
  32846. return errorMessage;
  32847. }
  32848. /**
  32849. * Invokes a pipe with 1 arguments.
  32850. *
  32851. * This instruction acts as a guard to {@link PipeTransform#transform} invoking
  32852. * the pipe only when an input to the pipe changes.
  32853. *
  32854. * @param index Pipe index where the pipe was stored on creation.
  32855. * @param offset the binding offset
  32856. * @param v1 1st argument to {@link PipeTransform#transform}.
  32857. *
  32858. * @codeGenApi
  32859. */
  32860. function ɵɵpipeBind1(index, offset, v1) {
  32861. const adjustedIndex = index + HEADER_OFFSET;
  32862. const lView = getLView();
  32863. const pipeInstance = load(lView, adjustedIndex);
  32864. return isPure(lView, adjustedIndex)
  32865. ? pureFunction1Internal(lView, getBindingRoot(), offset, pipeInstance.transform, v1, pipeInstance)
  32866. : pipeInstance.transform(v1);
  32867. }
  32868. /**
  32869. * Invokes a pipe with 2 arguments.
  32870. *
  32871. * This instruction acts as a guard to {@link PipeTransform#transform} invoking
  32872. * the pipe only when an input to the pipe changes.
  32873. *
  32874. * @param index Pipe index where the pipe was stored on creation.
  32875. * @param slotOffset the offset in the reserved slot space
  32876. * @param v1 1st argument to {@link PipeTransform#transform}.
  32877. * @param v2 2nd argument to {@link PipeTransform#transform}.
  32878. *
  32879. * @codeGenApi
  32880. */
  32881. function ɵɵpipeBind2(index, slotOffset, v1, v2) {
  32882. const adjustedIndex = index + HEADER_OFFSET;
  32883. const lView = getLView();
  32884. const pipeInstance = load(lView, adjustedIndex);
  32885. return isPure(lView, adjustedIndex)
  32886. ? pureFunction2Internal(lView, getBindingRoot(), slotOffset, pipeInstance.transform, v1, v2, pipeInstance)
  32887. : pipeInstance.transform(v1, v2);
  32888. }
  32889. /**
  32890. * Invokes a pipe with 3 arguments.
  32891. *
  32892. * This instruction acts as a guard to {@link PipeTransform#transform} invoking
  32893. * the pipe only when an input to the pipe changes.
  32894. *
  32895. * @param index Pipe index where the pipe was stored on creation.
  32896. * @param slotOffset the offset in the reserved slot space
  32897. * @param v1 1st argument to {@link PipeTransform#transform}.
  32898. * @param v2 2nd argument to {@link PipeTransform#transform}.
  32899. * @param v3 4rd argument to {@link PipeTransform#transform}.
  32900. *
  32901. * @codeGenApi
  32902. */
  32903. function ɵɵpipeBind3(index, slotOffset, v1, v2, v3) {
  32904. const adjustedIndex = index + HEADER_OFFSET;
  32905. const lView = getLView();
  32906. const pipeInstance = load(lView, adjustedIndex);
  32907. return isPure(lView, adjustedIndex)
  32908. ? pureFunction3Internal(lView, getBindingRoot(), slotOffset, pipeInstance.transform, v1, v2, v3, pipeInstance)
  32909. : pipeInstance.transform(v1, v2, v3);
  32910. }
  32911. /**
  32912. * Invokes a pipe with 4 arguments.
  32913. *
  32914. * This instruction acts as a guard to {@link PipeTransform#transform} invoking
  32915. * the pipe only when an input to the pipe changes.
  32916. *
  32917. * @param index Pipe index where the pipe was stored on creation.
  32918. * @param slotOffset the offset in the reserved slot space
  32919. * @param v1 1st argument to {@link PipeTransform#transform}.
  32920. * @param v2 2nd argument to {@link PipeTransform#transform}.
  32921. * @param v3 3rd argument to {@link PipeTransform#transform}.
  32922. * @param v4 4th argument to {@link PipeTransform#transform}.
  32923. *
  32924. * @codeGenApi
  32925. */
  32926. function ɵɵpipeBind4(index, slotOffset, v1, v2, v3, v4) {
  32927. const adjustedIndex = index + HEADER_OFFSET;
  32928. const lView = getLView();
  32929. const pipeInstance = load(lView, adjustedIndex);
  32930. return isPure(lView, adjustedIndex)
  32931. ? pureFunction4Internal(lView, getBindingRoot(), slotOffset, pipeInstance.transform, v1, v2, v3, v4, pipeInstance)
  32932. : pipeInstance.transform(v1, v2, v3, v4);
  32933. }
  32934. /**
  32935. * Invokes a pipe with variable number of arguments.
  32936. *
  32937. * This instruction acts as a guard to {@link PipeTransform#transform} invoking
  32938. * the pipe only when an input to the pipe changes.
  32939. *
  32940. * @param index Pipe index where the pipe was stored on creation.
  32941. * @param slotOffset the offset in the reserved slot space
  32942. * @param values Array of arguments to pass to {@link PipeTransform#transform} method.
  32943. *
  32944. * @codeGenApi
  32945. */
  32946. function ɵɵpipeBindV(index, slotOffset, values) {
  32947. const adjustedIndex = index + HEADER_OFFSET;
  32948. const lView = getLView();
  32949. const pipeInstance = load(lView, adjustedIndex);
  32950. return isPure(lView, adjustedIndex)
  32951. ? pureFunctionVInternal(lView, getBindingRoot(), slotOffset, pipeInstance.transform, values, pipeInstance)
  32952. : pipeInstance.transform.apply(pipeInstance, values);
  32953. }
  32954. function isPure(lView, index) {
  32955. return lView[TVIEW].data[index].pure;
  32956. }
  32957. /**
  32958. * Retrieves `TemplateRef` instance from `Injector` when a local reference is placed on the
  32959. * `<ng-template>` element.
  32960. *
  32961. * @codeGenApi
  32962. */
  32963. function ɵɵtemplateRefExtractor(tNode, lView) {
  32964. return createTemplateRef(tNode, lView);
  32965. }
  32966. function ɵɵgetComponentDepsFactory(type, rawImports) {
  32967. return () => {
  32968. try {
  32969. return depsTracker.getComponentDependencies(type, rawImports).dependencies;
  32970. }
  32971. catch (e) {
  32972. console.error(`Computing dependencies in local compilation mode for the component "${type.name}" failed with the exception:`, e);
  32973. throw e;
  32974. }
  32975. };
  32976. }
  32977. /**
  32978. * Sets the debug info for an Angular class.
  32979. *
  32980. * This runtime is guarded by ngDevMode flag.
  32981. */
  32982. function ɵsetClassDebugInfo(type, debugInfo) {
  32983. const def = getComponentDef(type);
  32984. if (def !== null) {
  32985. def.debugInfo = debugInfo;
  32986. }
  32987. }
  32988. /*!
  32989. * @license
  32990. * Copyright Google LLC All Rights Reserved.
  32991. *
  32992. * Use of this source code is governed by an MIT-style license that can be
  32993. * found in the LICENSE file at https://angular.dev/license
  32994. */
  32995. /**
  32996. * Gets the URL from which the client will fetch a new version of a component's metadata so it
  32997. * can be replaced during hot module reloading.
  32998. * @param id Unique ID for the component, generated during compile time.
  32999. * @param timestamp Time at which the request happened.
  33000. * @param base Base URL against which to resolve relative paths.
  33001. * @codeGenApi
  33002. */
  33003. function ɵɵgetReplaceMetadataURL(id, timestamp, base) {
  33004. const url = `./@ng/component?c=${id}&t=${encodeURIComponent(timestamp)}`;
  33005. return new URL(url, base).href;
  33006. }
  33007. /**
  33008. * Replaces the metadata of a component type and re-renders all live instances of the component.
  33009. * @param type Class whose metadata will be replaced.
  33010. * @param applyMetadata Callback that will apply a new set of metadata on the `type` when invoked.
  33011. * @param environment Syntehtic namespace imports that need to be passed along to the callback.
  33012. * @param locals Local symbols from the source location that have to be exposed to the callback.
  33013. * @param importMeta `import.meta` from the call site of the replacement function. Optional since
  33014. * it isn't used internally.
  33015. * @param id ID to the class being replaced. **Not** the same as the component definition ID.
  33016. * Optional since the ID might not be available internally.
  33017. * @codeGenApi
  33018. */
  33019. function ɵɵreplaceMetadata(type, applyMetadata, namespaces, locals, importMeta = null, id = null) {
  33020. ngDevMode && assertComponentDef(type);
  33021. const currentDef = getComponentDef(type);
  33022. // The reason `applyMetadata` is a callback that is invoked (almost) immediately is because
  33023. // the compiler usually produces more code than just the component definition, e.g. there
  33024. // can be functions for embedded views, the variables for the constant pool and `setClassMetadata`
  33025. // calls. The callback allows us to keep them isolate from the rest of the app and to invoke
  33026. // them at the right time.
  33027. applyMetadata.apply(null, [type, namespaces, ...locals]);
  33028. const { newDef, oldDef } = mergeWithExistingDefinition(currentDef, getComponentDef(type));
  33029. // TODO(crisbeto): the `applyMetadata` call above will replace the definition on the type.
  33030. // Ideally we should adjust the compiler output so the metadata is returned, however that'll
  33031. // require some internal changes. We re-add the metadata here manually.
  33032. type[NG_COMP_DEF] = newDef;
  33033. // If a `tView` hasn't been created yet, it means that this component hasn't been instantianted
  33034. // before. In this case there's nothing left for us to do aside from patching it in.
  33035. if (oldDef.tView) {
  33036. const trackedViews = getTrackedLViews().values();
  33037. for (const root of trackedViews) {
  33038. // Note: we have the additional check, because `IsRoot` can also indicate
  33039. // a component created through something like `createComponent`.
  33040. if (isRootView(root) && root[PARENT] === null) {
  33041. recreateMatchingLViews(importMeta, id, newDef, oldDef, root);
  33042. }
  33043. }
  33044. }
  33045. }
  33046. /**
  33047. * Merges two component definitions while preseving the original one in place.
  33048. * @param currentDef Definition that should receive the new metadata.
  33049. * @param newDef Source of the new metadata.
  33050. */
  33051. function mergeWithExistingDefinition(currentDef, newDef) {
  33052. // Clone the current definition since we reference its original data further
  33053. // down in the replacement process (e.g. when destroying the renderer).
  33054. const clone = { ...currentDef };
  33055. // Assign the new metadata in place while preserving the object literal. It's important to
  33056. // Keep the object in place, because there can be references to it, for example in the
  33057. // `directiveDefs` of another definition.
  33058. const replacement = Object.assign(currentDef, newDef, {
  33059. // We need to keep the existing directive and pipe defs, because they can get patched on
  33060. // by a call to `setComponentScope` from a module file. That call won't make it into the
  33061. // HMR replacement function, because it lives in an entirely different file.
  33062. directiveDefs: clone.directiveDefs,
  33063. pipeDefs: clone.pipeDefs,
  33064. // Preserve the old `setInput` function, because it has some state.
  33065. // This is fine, because the component instance is preserved as well.
  33066. setInput: clone.setInput,
  33067. // Externally this is redundant since we redeclare the definition using the original type.
  33068. // Internally we may receive a definition with an alternate, but identical, type so we have
  33069. // to ensure that the original one is preserved.
  33070. type: clone.type,
  33071. });
  33072. ngDevMode && assertEqual(replacement, currentDef, 'Expected definition to be merged in place');
  33073. return { newDef: replacement, oldDef: clone };
  33074. }
  33075. /**
  33076. * Finds all LViews matching a specific component definition and recreates them.
  33077. * @param importMeta `import.meta` information.
  33078. * @param id HMR ID of the component.
  33079. * @param oldDef Component definition to search for.
  33080. * @param rootLView View from which to start the search.
  33081. */
  33082. function recreateMatchingLViews(importMeta, id, newDef, oldDef, rootLView) {
  33083. ngDevMode &&
  33084. assertDefined(oldDef.tView, 'Expected a component definition that has been instantiated at least once');
  33085. const tView = rootLView[TVIEW];
  33086. // Use `tView` to match the LView since `instanceof` can
  33087. // produce false positives when using inheritance.
  33088. if (tView === oldDef.tView) {
  33089. ngDevMode && assertComponentDef(oldDef.type);
  33090. recreateLView(importMeta, id, newDef, oldDef, rootLView);
  33091. return;
  33092. }
  33093. for (let i = HEADER_OFFSET; i < tView.bindingStartIndex; i++) {
  33094. const current = rootLView[i];
  33095. if (isLContainer(current)) {
  33096. // The host can be an LView if a component is injecting `ViewContainerRef`.
  33097. if (isLView(current[HOST])) {
  33098. recreateMatchingLViews(importMeta, id, newDef, oldDef, current[HOST]);
  33099. }
  33100. for (let j = CONTAINER_HEADER_OFFSET; j < current.length; j++) {
  33101. recreateMatchingLViews(importMeta, id, newDef, oldDef, current[j]);
  33102. }
  33103. }
  33104. else if (isLView(current)) {
  33105. recreateMatchingLViews(importMeta, id, newDef, oldDef, current);
  33106. }
  33107. }
  33108. }
  33109. /**
  33110. * Removes any cached renderers from the factory for the provided type.
  33111. * This is currently used by the HMR logic to ensure Renderers are kept
  33112. * synchronized with any definition metadata updates.
  33113. * @param factory A RendererFactory2 instance.
  33114. * @param def A ComponentDef instance.
  33115. */
  33116. function clearRendererCache(factory, def) {
  33117. // Cast to read a private field.
  33118. // NOTE: This must be kept synchronized with the renderer factory implementation in
  33119. // platform-browser and platform-browser/animations.
  33120. factory.componentReplaced?.(def.id);
  33121. }
  33122. /**
  33123. * Recreates an LView in-place from a new component definition.
  33124. * @param importMeta `import.meta` information.
  33125. * @param id HMR ID for the component.
  33126. * @param newDef Definition from which to recreate the view.
  33127. * @param oldDef Previous component definition being swapped out.
  33128. * @param lView View to be recreated.
  33129. */
  33130. function recreateLView(importMeta, id, newDef, oldDef, lView) {
  33131. const instance = lView[CONTEXT];
  33132. let host = lView[HOST];
  33133. // In theory the parent can also be an LContainer, but it appears like that's
  33134. // only the case for embedded views which we won't be replacing here.
  33135. const parentLView = lView[PARENT];
  33136. ngDevMode && assertLView(parentLView);
  33137. const tNode = lView[T_HOST];
  33138. ngDevMode && assertTNodeType(tNode, 2 /* TNodeType.Element */);
  33139. ngDevMode && assertNotEqual(newDef, oldDef, 'Expected different component definition');
  33140. const zone = lView[INJECTOR].get(NgZone, null);
  33141. const recreate = () => {
  33142. // If we're recreating a component with shadow DOM encapsulation, it will have attached a
  33143. // shadow root. The browser will throw if we attempt to attach another one and there's no way
  33144. // to detach it. Our only option is to make a clone only of the root node, replace the node
  33145. // with the clone and use it for the newly-created LView.
  33146. if (oldDef.encapsulation === ViewEncapsulation.ShadowDom) {
  33147. const newHost = host.cloneNode(false);
  33148. host.replaceWith(newHost);
  33149. host = newHost;
  33150. }
  33151. // Recreate the TView since the template might've changed.
  33152. const newTView = getOrCreateComponentTView(newDef);
  33153. // Create a new LView from the new TView, but reusing the existing TNode and DOM node.
  33154. 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.
  33155. null, null, null);
  33156. // Detach the LView from its current place in the tree so we don't
  33157. // start traversing any siblings and modifying their structure.
  33158. replaceLViewInTree(parentLView, lView, newLView, tNode.index);
  33159. // Destroy the detached LView.
  33160. destroyLView(lView[TVIEW], lView);
  33161. // Always force the creation of a new renderer to ensure state captured during construction
  33162. // stays consistent with the new component definition by clearing any old ached factories.
  33163. const rendererFactory = lView[ENVIRONMENT].rendererFactory;
  33164. clearRendererCache(rendererFactory, oldDef);
  33165. // Patch a brand-new renderer onto the new view only after the old
  33166. // view is destroyed so that the runtime doesn't try to reuse it.
  33167. newLView[RENDERER] = rendererFactory.createRenderer(host, newDef);
  33168. // Remove the nodes associated with the destroyed LView. This removes the
  33169. // descendants, but not the host which we want to stay in place.
  33170. removeViewFromDOM(lView[TVIEW], lView);
  33171. // Reset the content projection state of the TNode before the first render.
  33172. // Note that this has to happen after the LView has been destroyed or we
  33173. // risk some projected nodes not being removed correctly.
  33174. resetProjectionState(tNode);
  33175. // Creation pass for the new view.
  33176. renderView(newTView, newLView, instance);
  33177. // Update pass for the new view.
  33178. refreshView(newTView, newLView, newTView.template, instance);
  33179. };
  33180. // The callback isn't guaranteed to be inside the Zone so we need to bring it in ourselves.
  33181. if (zone === null) {
  33182. executeWithInvalidateFallback(importMeta, id, recreate);
  33183. }
  33184. else {
  33185. zone.run(() => executeWithInvalidateFallback(importMeta, id, recreate));
  33186. }
  33187. }
  33188. /**
  33189. * Runs an HMR-related function and falls back to
  33190. * invalidating the HMR data if it throws an error.
  33191. */
  33192. function executeWithInvalidateFallback(importMeta, id, callback) {
  33193. try {
  33194. callback();
  33195. }
  33196. catch (e) {
  33197. const error = e;
  33198. // If we have all the necessary information and APIs to send off the invalidation
  33199. // request, send it before rethrowing so the dev server can decide what to do.
  33200. if (id !== null && error.message) {
  33201. const toLog = error.message + (error.stack ? '\n' + error.stack : '');
  33202. importMeta?.hot?.send?.('angular:invalidate', { id, message: toLog, error: true });
  33203. }
  33204. // Throw the error in case the page doesn't get refreshed.
  33205. throw e;
  33206. }
  33207. }
  33208. /**
  33209. * Replaces one LView in the tree with another one.
  33210. * @param parentLView Parent of the LView being replaced.
  33211. * @param oldLView LView being replaced.
  33212. * @param newLView Replacement LView to be inserted.
  33213. * @param index Index at which the LView should be inserted.
  33214. */
  33215. function replaceLViewInTree(parentLView, oldLView, newLView, index) {
  33216. // Update the sibling whose `NEXT` pointer refers to the old view.
  33217. for (let i = HEADER_OFFSET; i < parentLView[TVIEW].bindingStartIndex; i++) {
  33218. const current = parentLView[i];
  33219. if ((isLView(current) || isLContainer(current)) && current[NEXT] === oldLView) {
  33220. current[NEXT] = newLView;
  33221. break;
  33222. }
  33223. }
  33224. // Set the new view as the head, if the old view was first.
  33225. if (parentLView[CHILD_HEAD] === oldLView) {
  33226. parentLView[CHILD_HEAD] = newLView;
  33227. }
  33228. // Set the new view as the tail, if the old view was last.
  33229. if (parentLView[CHILD_TAIL] === oldLView) {
  33230. parentLView[CHILD_TAIL] = newLView;
  33231. }
  33232. // Update the `NEXT` pointer to the same as the old view.
  33233. newLView[NEXT] = oldLView[NEXT];
  33234. // Clear out the `NEXT` of the old view.
  33235. oldLView[NEXT] = null;
  33236. // Insert the new LView at the correct index.
  33237. parentLView[index] = newLView;
  33238. }
  33239. /**
  33240. * Child nodes mutate the `projection` state of their parent node as they're being projected.
  33241. * This function resets the `project` back to its initial state.
  33242. * @param tNode
  33243. */
  33244. function resetProjectionState(tNode) {
  33245. // The `projection` is mutated by child nodes as they're being projected. We need to
  33246. // reset it to the initial state so projection works after the template is swapped out.
  33247. if (tNode.projection !== null) {
  33248. for (const current of tNode.projection) {
  33249. if (isTNodeShape(current)) {
  33250. // Reset `projectionNext` since it can affect the traversal order during projection.
  33251. current.projectionNext = null;
  33252. current.flags &= -3 /* TNodeFlags.isProjected */;
  33253. }
  33254. }
  33255. tNode.projection = null;
  33256. }
  33257. }
  33258. /**
  33259. * A mapping of the @angular/core API surface used in generated expressions to the actual symbols.
  33260. *
  33261. * This should be kept up to date with the public exports of @angular/core.
  33262. */
  33263. const angularCoreEnv = (() => ({
  33264. 'ɵɵattribute': ɵɵattribute,
  33265. 'ɵɵattributeInterpolate1': ɵɵattributeInterpolate1,
  33266. 'ɵɵattributeInterpolate2': ɵɵattributeInterpolate2,
  33267. 'ɵɵattributeInterpolate3': ɵɵattributeInterpolate3,
  33268. 'ɵɵattributeInterpolate4': ɵɵattributeInterpolate4,
  33269. 'ɵɵattributeInterpolate5': ɵɵattributeInterpolate5,
  33270. 'ɵɵattributeInterpolate6': ɵɵattributeInterpolate6,
  33271. 'ɵɵattributeInterpolate7': ɵɵattributeInterpolate7,
  33272. 'ɵɵattributeInterpolate8': ɵɵattributeInterpolate8,
  33273. 'ɵɵattributeInterpolateV': ɵɵattributeInterpolateV,
  33274. 'ɵɵdefineComponent': ɵɵdefineComponent,
  33275. 'ɵɵdefineDirective': ɵɵdefineDirective,
  33276. 'ɵɵdefineInjectable': ɵɵdefineInjectable,
  33277. 'ɵɵdefineInjector': ɵɵdefineInjector,
  33278. 'ɵɵdefineNgModule': ɵɵdefineNgModule,
  33279. 'ɵɵdefinePipe': ɵɵdefinePipe,
  33280. 'ɵɵdirectiveInject': ɵɵdirectiveInject,
  33281. 'ɵɵgetInheritedFactory': ɵɵgetInheritedFactory,
  33282. 'ɵɵinject': ɵɵinject,
  33283. 'ɵɵinjectAttribute': ɵɵinjectAttribute,
  33284. 'ɵɵinvalidFactory': ɵɵinvalidFactory,
  33285. 'ɵɵinvalidFactoryDep': ɵɵinvalidFactoryDep,
  33286. 'ɵɵtemplateRefExtractor': ɵɵtemplateRefExtractor,
  33287. 'ɵɵresetView': ɵɵresetView,
  33288. 'ɵɵHostDirectivesFeature': ɵɵHostDirectivesFeature,
  33289. 'ɵɵNgOnChangesFeature': ɵɵNgOnChangesFeature,
  33290. 'ɵɵProvidersFeature': ɵɵProvidersFeature,
  33291. 'ɵɵCopyDefinitionFeature': ɵɵCopyDefinitionFeature,
  33292. 'ɵɵInheritDefinitionFeature': ɵɵInheritDefinitionFeature,
  33293. 'ɵɵExternalStylesFeature': ɵɵExternalStylesFeature,
  33294. 'ɵɵnextContext': ɵɵnextContext,
  33295. 'ɵɵnamespaceHTML': ɵɵnamespaceHTML,
  33296. 'ɵɵnamespaceMathML': ɵɵnamespaceMathML,
  33297. 'ɵɵnamespaceSVG': ɵɵnamespaceSVG,
  33298. 'ɵɵenableBindings': ɵɵenableBindings,
  33299. 'ɵɵdisableBindings': ɵɵdisableBindings,
  33300. 'ɵɵelementStart': ɵɵelementStart,
  33301. 'ɵɵelementEnd': ɵɵelementEnd,
  33302. 'ɵɵelement': ɵɵelement,
  33303. 'ɵɵelementContainerStart': ɵɵelementContainerStart,
  33304. 'ɵɵelementContainerEnd': ɵɵelementContainerEnd,
  33305. 'ɵɵelementContainer': ɵɵelementContainer,
  33306. 'ɵɵpureFunction0': ɵɵpureFunction0,
  33307. 'ɵɵpureFunction1': ɵɵpureFunction1,
  33308. 'ɵɵpureFunction2': ɵɵpureFunction2,
  33309. 'ɵɵpureFunction3': ɵɵpureFunction3,
  33310. 'ɵɵpureFunction4': ɵɵpureFunction4,
  33311. 'ɵɵpureFunction5': ɵɵpureFunction5,
  33312. 'ɵɵpureFunction6': ɵɵpureFunction6,
  33313. 'ɵɵpureFunction7': ɵɵpureFunction7,
  33314. 'ɵɵpureFunction8': ɵɵpureFunction8,
  33315. 'ɵɵpureFunctionV': ɵɵpureFunctionV,
  33316. 'ɵɵgetCurrentView': ɵɵgetCurrentView,
  33317. 'ɵɵrestoreView': ɵɵrestoreView,
  33318. 'ɵɵlistener': ɵɵlistener,
  33319. 'ɵɵprojection': ɵɵprojection,
  33320. 'ɵɵsyntheticHostProperty': ɵɵsyntheticHostProperty,
  33321. 'ɵɵsyntheticHostListener': ɵɵsyntheticHostListener,
  33322. 'ɵɵpipeBind1': ɵɵpipeBind1,
  33323. 'ɵɵpipeBind2': ɵɵpipeBind2,
  33324. 'ɵɵpipeBind3': ɵɵpipeBind3,
  33325. 'ɵɵpipeBind4': ɵɵpipeBind4,
  33326. 'ɵɵpipeBindV': ɵɵpipeBindV,
  33327. 'ɵɵprojectionDef': ɵɵprojectionDef,
  33328. 'ɵɵhostProperty': ɵɵhostProperty,
  33329. 'ɵɵproperty': ɵɵproperty,
  33330. 'ɵɵpropertyInterpolate': ɵɵpropertyInterpolate,
  33331. 'ɵɵpropertyInterpolate1': ɵɵpropertyInterpolate1,
  33332. 'ɵɵpropertyInterpolate2': ɵɵpropertyInterpolate2,
  33333. 'ɵɵpropertyInterpolate3': ɵɵpropertyInterpolate3,
  33334. 'ɵɵpropertyInterpolate4': ɵɵpropertyInterpolate4,
  33335. 'ɵɵpropertyInterpolate5': ɵɵpropertyInterpolate5,
  33336. 'ɵɵpropertyInterpolate6': ɵɵpropertyInterpolate6,
  33337. 'ɵɵpropertyInterpolate7': ɵɵpropertyInterpolate7,
  33338. 'ɵɵpropertyInterpolate8': ɵɵpropertyInterpolate8,
  33339. 'ɵɵpropertyInterpolateV': ɵɵpropertyInterpolateV,
  33340. 'ɵɵpipe': ɵɵpipe,
  33341. 'ɵɵqueryRefresh': ɵɵqueryRefresh,
  33342. 'ɵɵqueryAdvance': ɵɵqueryAdvance,
  33343. 'ɵɵviewQuery': ɵɵviewQuery,
  33344. 'ɵɵviewQuerySignal': ɵɵviewQuerySignal,
  33345. 'ɵɵloadQuery': ɵɵloadQuery,
  33346. 'ɵɵcontentQuery': ɵɵcontentQuery,
  33347. 'ɵɵcontentQuerySignal': ɵɵcontentQuerySignal,
  33348. 'ɵɵreference': ɵɵreference,
  33349. 'ɵɵclassMap': ɵɵclassMap,
  33350. 'ɵɵclassMapInterpolate1': ɵɵclassMapInterpolate1,
  33351. 'ɵɵclassMapInterpolate2': ɵɵclassMapInterpolate2,
  33352. 'ɵɵclassMapInterpolate3': ɵɵclassMapInterpolate3,
  33353. 'ɵɵclassMapInterpolate4': ɵɵclassMapInterpolate4,
  33354. 'ɵɵclassMapInterpolate5': ɵɵclassMapInterpolate5,
  33355. 'ɵɵclassMapInterpolate6': ɵɵclassMapInterpolate6,
  33356. 'ɵɵclassMapInterpolate7': ɵɵclassMapInterpolate7,
  33357. 'ɵɵclassMapInterpolate8': ɵɵclassMapInterpolate8,
  33358. 'ɵɵclassMapInterpolateV': ɵɵclassMapInterpolateV,
  33359. 'ɵɵstyleMap': ɵɵstyleMap,
  33360. 'ɵɵstyleMapInterpolate1': ɵɵstyleMapInterpolate1,
  33361. 'ɵɵstyleMapInterpolate2': ɵɵstyleMapInterpolate2,
  33362. 'ɵɵstyleMapInterpolate3': ɵɵstyleMapInterpolate3,
  33363. 'ɵɵstyleMapInterpolate4': ɵɵstyleMapInterpolate4,
  33364. 'ɵɵstyleMapInterpolate5': ɵɵstyleMapInterpolate5,
  33365. 'ɵɵstyleMapInterpolate6': ɵɵstyleMapInterpolate6,
  33366. 'ɵɵstyleMapInterpolate7': ɵɵstyleMapInterpolate7,
  33367. 'ɵɵstyleMapInterpolate8': ɵɵstyleMapInterpolate8,
  33368. 'ɵɵstyleMapInterpolateV': ɵɵstyleMapInterpolateV,
  33369. 'ɵɵstyleProp': ɵɵstyleProp,
  33370. 'ɵɵstylePropInterpolate1': ɵɵstylePropInterpolate1,
  33371. 'ɵɵstylePropInterpolate2': ɵɵstylePropInterpolate2,
  33372. 'ɵɵstylePropInterpolate3': ɵɵstylePropInterpolate3,
  33373. 'ɵɵstylePropInterpolate4': ɵɵstylePropInterpolate4,
  33374. 'ɵɵstylePropInterpolate5': ɵɵstylePropInterpolate5,
  33375. 'ɵɵstylePropInterpolate6': ɵɵstylePropInterpolate6,
  33376. 'ɵɵstylePropInterpolate7': ɵɵstylePropInterpolate7,
  33377. 'ɵɵstylePropInterpolate8': ɵɵstylePropInterpolate8,
  33378. 'ɵɵstylePropInterpolateV': ɵɵstylePropInterpolateV,
  33379. 'ɵɵclassProp': ɵɵclassProp,
  33380. 'ɵɵadvance': ɵɵadvance,
  33381. 'ɵɵtemplate': ɵɵtemplate,
  33382. 'ɵɵconditional': ɵɵconditional,
  33383. 'ɵɵdefer': ɵɵdefer,
  33384. 'ɵɵdeferWhen': ɵɵdeferWhen,
  33385. 'ɵɵdeferOnIdle': ɵɵdeferOnIdle,
  33386. 'ɵɵdeferOnImmediate': ɵɵdeferOnImmediate,
  33387. 'ɵɵdeferOnTimer': ɵɵdeferOnTimer,
  33388. 'ɵɵdeferOnHover': ɵɵdeferOnHover,
  33389. 'ɵɵdeferOnInteraction': ɵɵdeferOnInteraction,
  33390. 'ɵɵdeferOnViewport': ɵɵdeferOnViewport,
  33391. 'ɵɵdeferPrefetchWhen': ɵɵdeferPrefetchWhen,
  33392. 'ɵɵdeferPrefetchOnIdle': ɵɵdeferPrefetchOnIdle,
  33393. 'ɵɵdeferPrefetchOnImmediate': ɵɵdeferPrefetchOnImmediate,
  33394. 'ɵɵdeferPrefetchOnTimer': ɵɵdeferPrefetchOnTimer,
  33395. 'ɵɵdeferPrefetchOnHover': ɵɵdeferPrefetchOnHover,
  33396. 'ɵɵdeferPrefetchOnInteraction': ɵɵdeferPrefetchOnInteraction,
  33397. 'ɵɵdeferPrefetchOnViewport': ɵɵdeferPrefetchOnViewport,
  33398. 'ɵɵdeferHydrateWhen': ɵɵdeferHydrateWhen,
  33399. 'ɵɵdeferHydrateNever': ɵɵdeferHydrateNever,
  33400. 'ɵɵdeferHydrateOnIdle': ɵɵdeferHydrateOnIdle,
  33401. 'ɵɵdeferHydrateOnImmediate': ɵɵdeferHydrateOnImmediate,
  33402. 'ɵɵdeferHydrateOnTimer': ɵɵdeferHydrateOnTimer,
  33403. 'ɵɵdeferHydrateOnHover': ɵɵdeferHydrateOnHover,
  33404. 'ɵɵdeferHydrateOnInteraction': ɵɵdeferHydrateOnInteraction,
  33405. 'ɵɵdeferHydrateOnViewport': ɵɵdeferHydrateOnViewport,
  33406. 'ɵɵdeferEnableTimerScheduling': ɵɵdeferEnableTimerScheduling,
  33407. 'ɵɵrepeater': ɵɵrepeater,
  33408. 'ɵɵrepeaterCreate': ɵɵrepeaterCreate,
  33409. 'ɵɵrepeaterTrackByIndex': ɵɵrepeaterTrackByIndex,
  33410. 'ɵɵrepeaterTrackByIdentity': ɵɵrepeaterTrackByIdentity,
  33411. 'ɵɵcomponentInstance': ɵɵcomponentInstance,
  33412. 'ɵɵtext': ɵɵtext,
  33413. 'ɵɵtextInterpolate': ɵɵtextInterpolate,
  33414. 'ɵɵtextInterpolate1': ɵɵtextInterpolate1,
  33415. 'ɵɵtextInterpolate2': ɵɵtextInterpolate2,
  33416. 'ɵɵtextInterpolate3': ɵɵtextInterpolate3,
  33417. 'ɵɵtextInterpolate4': ɵɵtextInterpolate4,
  33418. 'ɵɵtextInterpolate5': ɵɵtextInterpolate5,
  33419. 'ɵɵtextInterpolate6': ɵɵtextInterpolate6,
  33420. 'ɵɵtextInterpolate7': ɵɵtextInterpolate7,
  33421. 'ɵɵtextInterpolate8': ɵɵtextInterpolate8,
  33422. 'ɵɵtextInterpolateV': ɵɵtextInterpolateV,
  33423. 'ɵɵi18n': ɵɵi18n,
  33424. 'ɵɵi18nAttributes': ɵɵi18nAttributes,
  33425. 'ɵɵi18nExp': ɵɵi18nExp,
  33426. 'ɵɵi18nStart': ɵɵi18nStart,
  33427. 'ɵɵi18nEnd': ɵɵi18nEnd,
  33428. 'ɵɵi18nApply': ɵɵi18nApply,
  33429. 'ɵɵi18nPostprocess': ɵɵi18nPostprocess,
  33430. 'ɵɵresolveWindow': ɵɵresolveWindow,
  33431. 'ɵɵresolveDocument': ɵɵresolveDocument,
  33432. 'ɵɵresolveBody': ɵɵresolveBody,
  33433. 'ɵɵsetComponentScope': ɵɵsetComponentScope,
  33434. 'ɵɵsetNgModuleScope': ɵɵsetNgModuleScope,
  33435. 'ɵɵregisterNgModuleType': registerNgModuleType,
  33436. 'ɵɵgetComponentDepsFactory': ɵɵgetComponentDepsFactory,
  33437. 'ɵsetClassDebugInfo': ɵsetClassDebugInfo,
  33438. 'ɵɵdeclareLet': ɵɵdeclareLet,
  33439. 'ɵɵstoreLet': ɵɵstoreLet,
  33440. 'ɵɵreadContextLet': ɵɵreadContextLet,
  33441. 'ɵɵattachSourceLocations': ɵɵattachSourceLocations,
  33442. 'ɵɵsanitizeHtml': ɵɵsanitizeHtml,
  33443. 'ɵɵsanitizeStyle': ɵɵsanitizeStyle,
  33444. 'ɵɵsanitizeResourceUrl': ɵɵsanitizeResourceUrl,
  33445. 'ɵɵsanitizeScript': ɵɵsanitizeScript,
  33446. 'ɵɵsanitizeUrl': ɵɵsanitizeUrl,
  33447. 'ɵɵsanitizeUrlOrResourceUrl': ɵɵsanitizeUrlOrResourceUrl,
  33448. 'ɵɵtrustConstantHtml': ɵɵtrustConstantHtml,
  33449. 'ɵɵtrustConstantResourceUrl': ɵɵtrustConstantResourceUrl,
  33450. 'ɵɵvalidateIframeAttribute': ɵɵvalidateIframeAttribute,
  33451. 'forwardRef': forwardRef,
  33452. 'resolveForwardRef': resolveForwardRef,
  33453. 'ɵɵtwoWayProperty': ɵɵtwoWayProperty,
  33454. 'ɵɵtwoWayBindingSet': ɵɵtwoWayBindingSet,
  33455. 'ɵɵtwoWayListener': ɵɵtwoWayListener,
  33456. 'ɵɵreplaceMetadata': ɵɵreplaceMetadata,
  33457. 'ɵɵgetReplaceMetadataURL': ɵɵgetReplaceMetadataURL,
  33458. }))();
  33459. let jitOptions = null;
  33460. function setJitOptions(options) {
  33461. if (jitOptions !== null) {
  33462. if (options.defaultEncapsulation !== jitOptions.defaultEncapsulation) {
  33463. ngDevMode &&
  33464. console.error('Provided value for `defaultEncapsulation` can not be changed once it has been set.');
  33465. return;
  33466. }
  33467. if (options.preserveWhitespaces !== jitOptions.preserveWhitespaces) {
  33468. ngDevMode &&
  33469. console.error('Provided value for `preserveWhitespaces` can not be changed once it has been set.');
  33470. return;
  33471. }
  33472. }
  33473. jitOptions = options;
  33474. }
  33475. function getJitOptions() {
  33476. return jitOptions;
  33477. }
  33478. function resetJitOptions() {
  33479. jitOptions = null;
  33480. }
  33481. const moduleQueue = [];
  33482. /**
  33483. * Enqueues moduleDef to be checked later to see if scope can be set on its
  33484. * component declarations.
  33485. */
  33486. function enqueueModuleForDelayedScoping(moduleType, ngModule) {
  33487. moduleQueue.push({ moduleType, ngModule });
  33488. }
  33489. let flushingModuleQueue = false;
  33490. /**
  33491. * Loops over queued module definitions, if a given module definition has all of its
  33492. * declarations resolved, it dequeues that module definition and sets the scope on
  33493. * its declarations.
  33494. */
  33495. function flushModuleScopingQueueAsMuchAsPossible() {
  33496. if (!flushingModuleQueue) {
  33497. flushingModuleQueue = true;
  33498. try {
  33499. for (let i = moduleQueue.length - 1; i >= 0; i--) {
  33500. const { moduleType, ngModule } = moduleQueue[i];
  33501. if (ngModule.declarations && ngModule.declarations.every(isResolvedDeclaration)) {
  33502. // dequeue
  33503. moduleQueue.splice(i, 1);
  33504. setScopeOnDeclaredComponents(moduleType, ngModule);
  33505. }
  33506. }
  33507. }
  33508. finally {
  33509. flushingModuleQueue = false;
  33510. }
  33511. }
  33512. }
  33513. /**
  33514. * Returns truthy if a declaration has resolved. If the declaration happens to be
  33515. * an array of declarations, it will recurse to check each declaration in that array
  33516. * (which may also be arrays).
  33517. */
  33518. function isResolvedDeclaration(declaration) {
  33519. if (Array.isArray(declaration)) {
  33520. return declaration.every(isResolvedDeclaration);
  33521. }
  33522. return !!resolveForwardRef(declaration);
  33523. }
  33524. /**
  33525. * Compiles a module in JIT mode.
  33526. *
  33527. * This function automatically gets called when a class has a `@NgModule` decorator.
  33528. */
  33529. function compileNgModule(moduleType, ngModule = {}) {
  33530. compileNgModuleDefs(moduleType, ngModule);
  33531. if (ngModule.id !== undefined) {
  33532. registerNgModuleType(moduleType, ngModule.id);
  33533. }
  33534. // Because we don't know if all declarations have resolved yet at the moment the
  33535. // NgModule decorator is executing, we're enqueueing the setting of module scope
  33536. // on its declarations to be run at a later time when all declarations for the module,
  33537. // including forward refs, have resolved.
  33538. enqueueModuleForDelayedScoping(moduleType, ngModule);
  33539. }
  33540. /**
  33541. * Compiles and adds the `ɵmod`, `ɵfac` and `ɵinj` properties to the module class.
  33542. *
  33543. * It's possible to compile a module via this API which will allow duplicate declarations in its
  33544. * root.
  33545. */
  33546. function compileNgModuleDefs(moduleType, ngModule, allowDuplicateDeclarationsInRoot = false) {
  33547. ngDevMode && assertDefined(moduleType, 'Required value moduleType');
  33548. ngDevMode && assertDefined(ngModule, 'Required value ngModule');
  33549. const declarations = flatten(ngModule.declarations || EMPTY_ARRAY);
  33550. let ngModuleDef = null;
  33551. Object.defineProperty(moduleType, NG_MOD_DEF, {
  33552. configurable: true,
  33553. get: () => {
  33554. if (ngModuleDef === null) {
  33555. if (ngDevMode && ngModule.imports && ngModule.imports.indexOf(moduleType) > -1) {
  33556. // We need to assert this immediately, because allowing it to continue will cause it to
  33557. // go into an infinite loop before we've reached the point where we throw all the errors.
  33558. throw new Error(`'${stringifyForError(moduleType)}' module can't import itself`);
  33559. }
  33560. const compiler = getCompilerFacade({
  33561. usage: 0 /* JitCompilerUsage.Decorator */,
  33562. kind: 'NgModule',
  33563. type: moduleType,
  33564. });
  33565. ngModuleDef = compiler.compileNgModule(angularCoreEnv, `ng:///${moduleType.name}/ɵmod.js`, {
  33566. type: moduleType,
  33567. bootstrap: flatten(ngModule.bootstrap || EMPTY_ARRAY).map(resolveForwardRef),
  33568. declarations: declarations.map(resolveForwardRef),
  33569. imports: flatten(ngModule.imports || EMPTY_ARRAY)
  33570. .map(resolveForwardRef)
  33571. .map(expandModuleWithProviders),
  33572. exports: flatten(ngModule.exports || EMPTY_ARRAY)
  33573. .map(resolveForwardRef)
  33574. .map(expandModuleWithProviders),
  33575. schemas: ngModule.schemas ? flatten(ngModule.schemas) : null,
  33576. id: ngModule.id || null,
  33577. });
  33578. // Set `schemas` on ngModuleDef to an empty array in JIT mode to indicate that runtime
  33579. // should verify that there are no unknown elements in a template. In AOT mode, that check
  33580. // happens at compile time and `schemas` information is not present on Component and Module
  33581. // defs after compilation (so the check doesn't happen the second time at runtime).
  33582. if (!ngModuleDef.schemas) {
  33583. ngModuleDef.schemas = [];
  33584. }
  33585. }
  33586. return ngModuleDef;
  33587. },
  33588. });
  33589. let ngFactoryDef = null;
  33590. Object.defineProperty(moduleType, NG_FACTORY_DEF, {
  33591. get: () => {
  33592. if (ngFactoryDef === null) {
  33593. const compiler = getCompilerFacade({
  33594. usage: 0 /* JitCompilerUsage.Decorator */,
  33595. kind: 'NgModule',
  33596. type: moduleType,
  33597. });
  33598. ngFactoryDef = compiler.compileFactory(angularCoreEnv, `ng:///${moduleType.name}/ɵfac.js`, {
  33599. name: moduleType.name,
  33600. type: moduleType,
  33601. deps: reflectDependencies(moduleType),
  33602. target: compiler.FactoryTarget.NgModule,
  33603. typeArgumentCount: 0,
  33604. });
  33605. }
  33606. return ngFactoryDef;
  33607. },
  33608. // Make the property configurable in dev mode to allow overriding in tests
  33609. configurable: !!ngDevMode,
  33610. });
  33611. let ngInjectorDef = null;
  33612. Object.defineProperty(moduleType, NG_INJ_DEF, {
  33613. get: () => {
  33614. if (ngInjectorDef === null) {
  33615. ngDevMode && verifySemanticsOfNgModuleDef(moduleType, allowDuplicateDeclarationsInRoot);
  33616. const meta = {
  33617. name: moduleType.name,
  33618. type: moduleType,
  33619. providers: ngModule.providers || EMPTY_ARRAY,
  33620. imports: [
  33621. (ngModule.imports || EMPTY_ARRAY).map(resolveForwardRef),
  33622. (ngModule.exports || EMPTY_ARRAY).map(resolveForwardRef),
  33623. ],
  33624. };
  33625. const compiler = getCompilerFacade({
  33626. usage: 0 /* JitCompilerUsage.Decorator */,
  33627. kind: 'NgModule',
  33628. type: moduleType,
  33629. });
  33630. ngInjectorDef = compiler.compileInjector(angularCoreEnv, `ng:///${moduleType.name}/ɵinj.js`, meta);
  33631. }
  33632. return ngInjectorDef;
  33633. },
  33634. // Make the property configurable in dev mode to allow overriding in tests
  33635. configurable: !!ngDevMode,
  33636. });
  33637. }
  33638. function generateStandaloneInDeclarationsError(type, location) {
  33639. const prefix = `Unexpected "${stringifyForError(type)}" found in the "declarations" array of the`;
  33640. const suffix = `"${stringifyForError(type)}" is marked as standalone and can't be declared ` +
  33641. 'in any NgModule - did you intend to import it instead (by adding it to the "imports" array)?';
  33642. return `${prefix} ${location}, ${suffix}`;
  33643. }
  33644. function verifySemanticsOfNgModuleDef(moduleType, allowDuplicateDeclarationsInRoot, importingModule) {
  33645. if (verifiedNgModule.get(moduleType))
  33646. return;
  33647. // skip verifications of standalone components, directives, and pipes
  33648. if (isStandalone(moduleType))
  33649. return;
  33650. verifiedNgModule.set(moduleType, true);
  33651. moduleType = resolveForwardRef(moduleType);
  33652. let ngModuleDef;
  33653. if (importingModule) {
  33654. ngModuleDef = getNgModuleDef(moduleType);
  33655. if (!ngModuleDef) {
  33656. throw new Error(`Unexpected value '${moduleType.name}' imported by the module '${importingModule.name}'. Please add an @NgModule annotation.`);
  33657. }
  33658. }
  33659. else {
  33660. ngModuleDef = getNgModuleDef(moduleType, true);
  33661. }
  33662. const errors = [];
  33663. const declarations = maybeUnwrapFn(ngModuleDef.declarations);
  33664. const imports = maybeUnwrapFn(ngModuleDef.imports);
  33665. flatten(imports)
  33666. .map(unwrapModuleWithProvidersImports)
  33667. .forEach((modOrStandaloneCmpt) => {
  33668. verifySemanticsOfNgModuleImport(modOrStandaloneCmpt, moduleType);
  33669. verifySemanticsOfNgModuleDef(modOrStandaloneCmpt, false, moduleType);
  33670. });
  33671. const exports = maybeUnwrapFn(ngModuleDef.exports);
  33672. declarations.forEach(verifyDeclarationsHaveDefinitions);
  33673. declarations.forEach(verifyDirectivesHaveSelector);
  33674. declarations.forEach((declarationType) => verifyNotStandalone(declarationType, moduleType));
  33675. const combinedDeclarations = [
  33676. ...declarations.map(resolveForwardRef),
  33677. ...flatten(imports.map(computeCombinedExports)).map(resolveForwardRef),
  33678. ];
  33679. exports.forEach(verifyExportsAreDeclaredOrReExported);
  33680. declarations.forEach((decl) => verifyDeclarationIsUnique(decl, allowDuplicateDeclarationsInRoot));
  33681. const ngModule = getAnnotation(moduleType, 'NgModule');
  33682. if (ngModule) {
  33683. ngModule.imports &&
  33684. flatten(ngModule.imports)
  33685. .map(unwrapModuleWithProvidersImports)
  33686. .forEach((mod) => {
  33687. verifySemanticsOfNgModuleImport(mod, moduleType);
  33688. verifySemanticsOfNgModuleDef(mod, false, moduleType);
  33689. });
  33690. ngModule.bootstrap && deepForEach(ngModule.bootstrap, verifyCorrectBootstrapType);
  33691. ngModule.bootstrap && deepForEach(ngModule.bootstrap, verifyComponentIsPartOfNgModule);
  33692. }
  33693. // Throw Error if any errors were detected.
  33694. if (errors.length) {
  33695. throw new Error(errors.join('\n'));
  33696. }
  33697. ////////////////////////////////////////////////////////////////////////////////////////////////
  33698. function verifyDeclarationsHaveDefinitions(type) {
  33699. type = resolveForwardRef(type);
  33700. const def = getComponentDef(type) || getDirectiveDef(type) || getPipeDef$1(type);
  33701. if (!def) {
  33702. errors.push(`Unexpected value '${stringifyForError(type)}' declared by the module '${stringifyForError(moduleType)}'. Please add a @Pipe/@Directive/@Component annotation.`);
  33703. }
  33704. }
  33705. function verifyDirectivesHaveSelector(type) {
  33706. type = resolveForwardRef(type);
  33707. const def = getDirectiveDef(type);
  33708. if (!getComponentDef(type) && def && def.selectors.length == 0) {
  33709. errors.push(`Directive ${stringifyForError(type)} has no selector, please add it!`);
  33710. }
  33711. }
  33712. function verifyNotStandalone(type, moduleType) {
  33713. type = resolveForwardRef(type);
  33714. const def = getComponentDef(type) || getDirectiveDef(type) || getPipeDef$1(type);
  33715. if (def?.standalone) {
  33716. const location = `"${stringifyForError(moduleType)}" NgModule`;
  33717. errors.push(generateStandaloneInDeclarationsError(type, location));
  33718. }
  33719. }
  33720. function verifyExportsAreDeclaredOrReExported(type) {
  33721. type = resolveForwardRef(type);
  33722. const kind = (getComponentDef(type) && 'component') ||
  33723. (getDirectiveDef(type) && 'directive') ||
  33724. (getPipeDef$1(type) && 'pipe');
  33725. if (kind) {
  33726. // only checked if we are declared as Component, Directive, or Pipe
  33727. // Modules don't need to be declared or imported.
  33728. if (combinedDeclarations.lastIndexOf(type) === -1) {
  33729. // We are exporting something which we don't explicitly declare or import.
  33730. errors.push(`Can't export ${kind} ${stringifyForError(type)} from ${stringifyForError(moduleType)} as it was neither declared nor imported!`);
  33731. }
  33732. }
  33733. }
  33734. function verifyDeclarationIsUnique(type, suppressErrors) {
  33735. type = resolveForwardRef(type);
  33736. const existingModule = ownerNgModule.get(type);
  33737. if (existingModule && existingModule !== moduleType) {
  33738. if (!suppressErrors) {
  33739. const modules = [existingModule, moduleType].map(stringifyForError).sort();
  33740. errors.push(`Type ${stringifyForError(type)} is part of the declarations of 2 modules: ${modules[0]} and ${modules[1]}! ` +
  33741. `Please consider moving ${stringifyForError(type)} to a higher module that imports ${modules[0]} and ${modules[1]}. ` +
  33742. `You can also create a new NgModule that exports and includes ${stringifyForError(type)} then import that NgModule in ${modules[0]} and ${modules[1]}.`);
  33743. }
  33744. }
  33745. else {
  33746. // Mark type as having owner.
  33747. ownerNgModule.set(type, moduleType);
  33748. }
  33749. }
  33750. function verifyComponentIsPartOfNgModule(type) {
  33751. type = resolveForwardRef(type);
  33752. const existingModule = ownerNgModule.get(type);
  33753. if (!existingModule && !isStandalone(type)) {
  33754. errors.push(`Component ${stringifyForError(type)} is not part of any NgModule or the module has not been imported into your module.`);
  33755. }
  33756. }
  33757. function verifyCorrectBootstrapType(type) {
  33758. type = resolveForwardRef(type);
  33759. if (!getComponentDef(type)) {
  33760. errors.push(`${stringifyForError(type)} cannot be used as an entry component.`);
  33761. }
  33762. if (isStandalone(type)) {
  33763. // Note: this error should be the same as the
  33764. // `NGMODULE_BOOTSTRAP_IS_STANDALONE` one in AOT compiler.
  33765. errors.push(`The \`${stringifyForError(type)}\` class is a standalone component, which can ` +
  33766. `not be used in the \`@NgModule.bootstrap\` array. Use the \`bootstrapApplication\` ` +
  33767. `function for bootstrap instead.`);
  33768. }
  33769. }
  33770. function verifySemanticsOfNgModuleImport(type, importingModule) {
  33771. type = resolveForwardRef(type);
  33772. const directiveDef = getComponentDef(type) || getDirectiveDef(type);
  33773. if (directiveDef !== null && !directiveDef.standalone) {
  33774. throw new Error(`Unexpected directive '${type.name}' imported by the module '${importingModule.name}'. Please add an @NgModule annotation.`);
  33775. }
  33776. const pipeDef = getPipeDef$1(type);
  33777. if (pipeDef !== null && !pipeDef.standalone) {
  33778. throw new Error(`Unexpected pipe '${type.name}' imported by the module '${importingModule.name}'. Please add an @NgModule annotation.`);
  33779. }
  33780. }
  33781. }
  33782. function unwrapModuleWithProvidersImports(typeOrWithProviders) {
  33783. typeOrWithProviders = resolveForwardRef(typeOrWithProviders);
  33784. return typeOrWithProviders.ngModule || typeOrWithProviders;
  33785. }
  33786. function getAnnotation(type, name) {
  33787. let annotation = null;
  33788. collect(type.__annotations__);
  33789. collect(type.decorators);
  33790. return annotation;
  33791. function collect(annotations) {
  33792. if (annotations) {
  33793. annotations.forEach(readAnnotation);
  33794. }
  33795. }
  33796. function readAnnotation(decorator) {
  33797. if (!annotation) {
  33798. const proto = Object.getPrototypeOf(decorator);
  33799. if (proto.ngMetadataName == name) {
  33800. annotation = decorator;
  33801. }
  33802. else if (decorator.type) {
  33803. const proto = Object.getPrototypeOf(decorator.type);
  33804. if (proto.ngMetadataName == name) {
  33805. annotation = decorator.args[0];
  33806. }
  33807. }
  33808. }
  33809. }
  33810. }
  33811. /**
  33812. * Keep track of compiled components. This is needed because in tests we often want to compile the
  33813. * same component with more than one NgModule. This would cause an error unless we reset which
  33814. * NgModule the component belongs to. We keep the list of compiled components here so that the
  33815. * TestBed can reset it later.
  33816. */
  33817. let ownerNgModule = new WeakMap();
  33818. let verifiedNgModule = new WeakMap();
  33819. function resetCompiledComponents() {
  33820. ownerNgModule = new WeakMap();
  33821. verifiedNgModule = new WeakMap();
  33822. moduleQueue.length = 0;
  33823. GENERATED_COMP_IDS.clear();
  33824. }
  33825. /**
  33826. * Computes the combined declarations of explicit declarations, as well as declarations inherited by
  33827. * traversing the exports of imported modules.
  33828. * @param type
  33829. */
  33830. function computeCombinedExports(type) {
  33831. type = resolveForwardRef(type);
  33832. const ngModuleDef = getNgModuleDef(type);
  33833. // a standalone component, directive or pipe
  33834. if (ngModuleDef === null) {
  33835. return [type];
  33836. }
  33837. return flatten(maybeUnwrapFn(ngModuleDef.exports).map((type) => {
  33838. const ngModuleDef = getNgModuleDef(type);
  33839. if (ngModuleDef) {
  33840. verifySemanticsOfNgModuleDef(type, false);
  33841. return computeCombinedExports(type);
  33842. }
  33843. else {
  33844. return type;
  33845. }
  33846. }));
  33847. }
  33848. /**
  33849. * Some declared components may be compiled asynchronously, and thus may not have their
  33850. * ɵcmp set yet. If this is the case, then a reference to the module is written into
  33851. * the `ngSelectorScope` property of the declared type.
  33852. */
  33853. function setScopeOnDeclaredComponents(moduleType, ngModule) {
  33854. const declarations = flatten(ngModule.declarations || EMPTY_ARRAY);
  33855. const transitiveScopes = transitiveScopesFor(moduleType);
  33856. declarations.forEach((declaration) => {
  33857. declaration = resolveForwardRef(declaration);
  33858. if (declaration.hasOwnProperty(NG_COMP_DEF)) {
  33859. // A `ɵcmp` field exists - go ahead and patch the component directly.
  33860. const component = declaration;
  33861. const componentDef = getComponentDef(component);
  33862. patchComponentDefWithScope(componentDef, transitiveScopes);
  33863. }
  33864. else if (!declaration.hasOwnProperty(NG_DIR_DEF) &&
  33865. !declaration.hasOwnProperty(NG_PIPE_DEF)) {
  33866. // Set `ngSelectorScope` for future reference when the component compilation finishes.
  33867. declaration.ngSelectorScope = moduleType;
  33868. }
  33869. });
  33870. }
  33871. /**
  33872. * Patch the definition of a component with directives and pipes from the compilation scope of
  33873. * a given module.
  33874. */
  33875. function patchComponentDefWithScope(componentDef, transitiveScopes) {
  33876. componentDef.directiveDefs = () => Array.from(transitiveScopes.compilation.directives)
  33877. .map((dir) => dir.hasOwnProperty(NG_COMP_DEF) ? getComponentDef(dir) : getDirectiveDef(dir))
  33878. .filter((def) => !!def);
  33879. componentDef.pipeDefs = () => Array.from(transitiveScopes.compilation.pipes).map((pipe) => getPipeDef$1(pipe));
  33880. componentDef.schemas = transitiveScopes.schemas;
  33881. // Since we avoid Components/Directives/Pipes recompiling in case there are no overrides, we
  33882. // may face a problem where previously compiled defs available to a given Component/Directive
  33883. // are cached in TView and may become stale (in case any of these defs gets recompiled). In
  33884. // order to avoid this problem, we force fresh TView to be created.
  33885. componentDef.tView = null;
  33886. }
  33887. /**
  33888. * Compute the pair of transitive scopes (compilation scope and exported scope) for a given type
  33889. * (either a NgModule or a standalone component / directive / pipe).
  33890. */
  33891. function transitiveScopesFor(type) {
  33892. if (isNgModule(type)) {
  33893. {
  33894. const scope = depsTracker.getNgModuleScope(type);
  33895. const def = getNgModuleDef(type, true);
  33896. return {
  33897. schemas: def.schemas || null,
  33898. ...scope,
  33899. };
  33900. }
  33901. }
  33902. else if (isStandalone(type)) {
  33903. const directiveDef = getComponentDef(type) || getDirectiveDef(type);
  33904. if (directiveDef !== null) {
  33905. return {
  33906. schemas: null,
  33907. compilation: {
  33908. directives: new Set(),
  33909. pipes: new Set(),
  33910. },
  33911. exported: {
  33912. directives: new Set([type]),
  33913. pipes: new Set(),
  33914. },
  33915. };
  33916. }
  33917. const pipeDef = getPipeDef$1(type);
  33918. if (pipeDef !== null) {
  33919. return {
  33920. schemas: null,
  33921. compilation: {
  33922. directives: new Set(),
  33923. pipes: new Set(),
  33924. },
  33925. exported: {
  33926. directives: new Set(),
  33927. pipes: new Set([type]),
  33928. },
  33929. };
  33930. }
  33931. }
  33932. // TODO: change the error message to be more user-facing and take standalone into account
  33933. throw new Error(`${type.name} does not have a module def (ɵmod property)`);
  33934. }
  33935. function expandModuleWithProviders(value) {
  33936. if (isModuleWithProviders(value)) {
  33937. return value.ngModule;
  33938. }
  33939. return value;
  33940. }
  33941. /**
  33942. * Keep track of the compilation depth to avoid reentrancy issues during JIT compilation. This
  33943. * matters in the following scenario:
  33944. *
  33945. * Consider a component 'A' that extends component 'B', both declared in module 'M'. During
  33946. * the compilation of 'A' the definition of 'B' is requested to capture the inheritance chain,
  33947. * potentially triggering compilation of 'B'. If this nested compilation were to trigger
  33948. * `flushModuleScopingQueueAsMuchAsPossible` it may happen that module 'M' is still pending in the
  33949. * queue, resulting in 'A' and 'B' to be patched with the NgModule scope. As the compilation of
  33950. * 'A' is still in progress, this would introduce a circular dependency on its compilation. To avoid
  33951. * this issue, the module scope queue is only flushed for compilations at the depth 0, to ensure
  33952. * all compilations have finished.
  33953. */
  33954. let compilationDepth = 0;
  33955. /**
  33956. * Compile an Angular component according to its decorator metadata, and patch the resulting
  33957. * component def (ɵcmp) onto the component type.
  33958. *
  33959. * Compilation may be asynchronous (due to the need to resolve URLs for the component template or
  33960. * other resources, for example). In the event that compilation is not immediate, `compileComponent`
  33961. * will enqueue resource resolution into a global queue and will fail to return the `ɵcmp`
  33962. * until the global queue has been resolved with a call to `resolveComponentResources`.
  33963. */
  33964. function compileComponent(type, metadata) {
  33965. // Initialize ngDevMode. This must be the first statement in compileComponent.
  33966. // See the `initNgDevMode` docstring for more information.
  33967. (typeof ngDevMode === 'undefined' || ngDevMode) && initNgDevMode();
  33968. let ngComponentDef = null;
  33969. // Metadata may have resources which need to be resolved.
  33970. maybeQueueResolutionOfComponentResources(type, metadata);
  33971. // Note that we're using the same function as `Directive`, because that's only subset of metadata
  33972. // that we need to create the ngFactoryDef. We're avoiding using the component metadata
  33973. // because we'd have to resolve the asynchronous templates.
  33974. addDirectiveFactoryDef(type, metadata);
  33975. Object.defineProperty(type, NG_COMP_DEF, {
  33976. get: () => {
  33977. if (ngComponentDef === null) {
  33978. const compiler = getCompilerFacade({
  33979. usage: 0 /* JitCompilerUsage.Decorator */,
  33980. kind: 'component',
  33981. type: type,
  33982. });
  33983. if (componentNeedsResolution(metadata)) {
  33984. const error = [`Component '${type.name}' is not resolved:`];
  33985. if (metadata.templateUrl) {
  33986. error.push(` - templateUrl: ${metadata.templateUrl}`);
  33987. }
  33988. if (metadata.styleUrls && metadata.styleUrls.length) {
  33989. error.push(` - styleUrls: ${JSON.stringify(metadata.styleUrls)}`);
  33990. }
  33991. if (metadata.styleUrl) {
  33992. error.push(` - styleUrl: ${metadata.styleUrl}`);
  33993. }
  33994. error.push(`Did you run and wait for 'resolveComponentResources()'?`);
  33995. throw new Error(error.join('\n'));
  33996. }
  33997. // This const was called `jitOptions` previously but had to be renamed to `options` because
  33998. // of a bug with Terser that caused optimized JIT builds to throw a `ReferenceError`.
  33999. // This bug was investigated in https://github.com/angular/angular-cli/issues/17264.
  34000. // We should not rename it back until https://github.com/terser/terser/issues/615 is fixed.
  34001. const options = getJitOptions();
  34002. let preserveWhitespaces = metadata.preserveWhitespaces;
  34003. if (preserveWhitespaces === undefined) {
  34004. if (options !== null && options.preserveWhitespaces !== undefined) {
  34005. preserveWhitespaces = options.preserveWhitespaces;
  34006. }
  34007. else {
  34008. preserveWhitespaces = false;
  34009. }
  34010. }
  34011. let encapsulation = metadata.encapsulation;
  34012. if (encapsulation === undefined) {
  34013. if (options !== null && options.defaultEncapsulation !== undefined) {
  34014. encapsulation = options.defaultEncapsulation;
  34015. }
  34016. else {
  34017. encapsulation = ViewEncapsulation.Emulated;
  34018. }
  34019. }
  34020. const templateUrl = metadata.templateUrl || `ng:///${type.name}/template.html`;
  34021. const meta = {
  34022. ...directiveMetadata(type, metadata),
  34023. typeSourceSpan: compiler.createParseSourceSpan('Component', type.name, templateUrl),
  34024. template: metadata.template || '',
  34025. preserveWhitespaces,
  34026. styles: typeof metadata.styles === 'string'
  34027. ? [metadata.styles]
  34028. : metadata.styles || EMPTY_ARRAY,
  34029. animations: metadata.animations,
  34030. // JIT components are always compiled against an empty set of `declarations`. Instead, the
  34031. // `directiveDefs` and `pipeDefs` are updated at a later point:
  34032. // * for NgModule-based components, they're set when the NgModule which declares the
  34033. // component resolves in the module scoping queue
  34034. // * for standalone components, they're set just below, after `compileComponent`.
  34035. declarations: [],
  34036. changeDetection: metadata.changeDetection,
  34037. encapsulation,
  34038. interpolation: metadata.interpolation,
  34039. viewProviders: metadata.viewProviders || null,
  34040. };
  34041. compilationDepth++;
  34042. try {
  34043. if (meta.usesInheritance) {
  34044. addDirectiveDefToUndecoratedParents(type);
  34045. }
  34046. ngComponentDef = compiler.compileComponent(angularCoreEnv, templateUrl, meta);
  34047. if (meta.isStandalone) {
  34048. // Patch the component definition for standalone components with `directiveDefs` and
  34049. // `pipeDefs` functions which lazily compute the directives/pipes available in the
  34050. // standalone component. Also set `dependencies` to the lazily resolved list of imports.
  34051. const imports = flatten(metadata.imports || EMPTY_ARRAY);
  34052. const { directiveDefs, pipeDefs } = getStandaloneDefFunctions(type, imports);
  34053. ngComponentDef.directiveDefs = directiveDefs;
  34054. ngComponentDef.pipeDefs = pipeDefs;
  34055. ngComponentDef.dependencies = () => imports.map(resolveForwardRef);
  34056. }
  34057. }
  34058. finally {
  34059. // Ensure that the compilation depth is decremented even when the compilation failed.
  34060. compilationDepth--;
  34061. }
  34062. if (compilationDepth === 0) {
  34063. // When NgModule decorator executed, we enqueued the module definition such that
  34064. // it would only dequeue and add itself as module scope to all of its declarations,
  34065. // but only if if all of its declarations had resolved. This call runs the check
  34066. // to see if any modules that are in the queue can be dequeued and add scope to
  34067. // their declarations.
  34068. flushModuleScopingQueueAsMuchAsPossible();
  34069. }
  34070. // If component compilation is async, then the @NgModule annotation which declares the
  34071. // component may execute and set an ngSelectorScope property on the component type. This
  34072. // allows the component to patch itself with directiveDefs from the module after it
  34073. // finishes compiling.
  34074. if (hasSelectorScope(type)) {
  34075. const scopes = transitiveScopesFor(type.ngSelectorScope);
  34076. patchComponentDefWithScope(ngComponentDef, scopes);
  34077. }
  34078. if (metadata.schemas) {
  34079. if (meta.isStandalone) {
  34080. ngComponentDef.schemas = metadata.schemas;
  34081. }
  34082. else {
  34083. throw new Error(`The 'schemas' was specified for the ${stringifyForError(type)} but is only valid on a component that is standalone.`);
  34084. }
  34085. }
  34086. else if (meta.isStandalone) {
  34087. ngComponentDef.schemas = [];
  34088. }
  34089. }
  34090. return ngComponentDef;
  34091. },
  34092. set: (def) => {
  34093. ngComponentDef = def;
  34094. },
  34095. // Make the property configurable in dev mode to allow overriding in tests
  34096. configurable: !!ngDevMode,
  34097. });
  34098. }
  34099. /**
  34100. * Build memoized `directiveDefs` and `pipeDefs` functions for the component definition of a
  34101. * standalone component, which process `imports` and filter out directives and pipes. The use of
  34102. * memoized functions here allows for the delayed resolution of any `forwardRef`s present in the
  34103. * component's `imports`.
  34104. */
  34105. function getStandaloneDefFunctions(type, imports) {
  34106. const directiveDefs = () => {
  34107. {
  34108. if (ngDevMode) {
  34109. for (const rawDep of imports) {
  34110. verifyStandaloneImport(rawDep, type);
  34111. }
  34112. }
  34113. if (!isComponent(type)) {
  34114. return [];
  34115. }
  34116. const scope = depsTracker.getStandaloneComponentScope(type, imports);
  34117. return [...scope.compilation.directives]
  34118. .map((p) => (getComponentDef(p) || getDirectiveDef(p)))
  34119. .filter((d) => d !== null);
  34120. }
  34121. };
  34122. const pipeDefs = () => {
  34123. {
  34124. if (ngDevMode) {
  34125. for (const rawDep of imports) {
  34126. verifyStandaloneImport(rawDep, type);
  34127. }
  34128. }
  34129. if (!isComponent(type)) {
  34130. return [];
  34131. }
  34132. const scope = depsTracker.getStandaloneComponentScope(type, imports);
  34133. return [...scope.compilation.pipes].map((p) => getPipeDef$1(p)).filter((d) => d !== null);
  34134. }
  34135. };
  34136. return {
  34137. directiveDefs,
  34138. pipeDefs,
  34139. };
  34140. }
  34141. function hasSelectorScope(component) {
  34142. return component.ngSelectorScope !== undefined;
  34143. }
  34144. /**
  34145. * Compile an Angular directive according to its decorator metadata, and patch the resulting
  34146. * directive def onto the component type.
  34147. *
  34148. * In the event that compilation is not immediate, `compileDirective` will return a `Promise` which
  34149. * will resolve when compilation completes and the directive becomes usable.
  34150. */
  34151. function compileDirective(type, directive) {
  34152. let ngDirectiveDef = null;
  34153. addDirectiveFactoryDef(type, directive || {});
  34154. Object.defineProperty(type, NG_DIR_DEF, {
  34155. get: () => {
  34156. if (ngDirectiveDef === null) {
  34157. // `directive` can be null in the case of abstract directives as a base class
  34158. // that use `@Directive()` with no selector. In that case, pass empty object to the
  34159. // `directiveMetadata` function instead of null.
  34160. const meta = getDirectiveMetadata(type, directive || {});
  34161. const compiler = getCompilerFacade({
  34162. usage: 0 /* JitCompilerUsage.Decorator */,
  34163. kind: 'directive',
  34164. type,
  34165. });
  34166. ngDirectiveDef = compiler.compileDirective(angularCoreEnv, meta.sourceMapUrl, meta.metadata);
  34167. }
  34168. return ngDirectiveDef;
  34169. },
  34170. // Make the property configurable in dev mode to allow overriding in tests
  34171. configurable: !!ngDevMode,
  34172. });
  34173. }
  34174. function getDirectiveMetadata(type, metadata) {
  34175. const name = type && type.name;
  34176. const sourceMapUrl = `ng:///${name}/ɵdir.js`;
  34177. const compiler = getCompilerFacade({ usage: 0 /* JitCompilerUsage.Decorator */, kind: 'directive', type });
  34178. const facade = directiveMetadata(type, metadata);
  34179. facade.typeSourceSpan = compiler.createParseSourceSpan('Directive', name, sourceMapUrl);
  34180. if (facade.usesInheritance) {
  34181. addDirectiveDefToUndecoratedParents(type);
  34182. }
  34183. return { metadata: facade, sourceMapUrl };
  34184. }
  34185. function addDirectiveFactoryDef(type, metadata) {
  34186. let ngFactoryDef = null;
  34187. Object.defineProperty(type, NG_FACTORY_DEF, {
  34188. get: () => {
  34189. if (ngFactoryDef === null) {
  34190. const meta = getDirectiveMetadata(type, metadata);
  34191. const compiler = getCompilerFacade({
  34192. usage: 0 /* JitCompilerUsage.Decorator */,
  34193. kind: 'directive',
  34194. type,
  34195. });
  34196. ngFactoryDef = compiler.compileFactory(angularCoreEnv, `ng:///${type.name}/ɵfac.js`, {
  34197. name: meta.metadata.name,
  34198. type: meta.metadata.type,
  34199. typeArgumentCount: 0,
  34200. deps: reflectDependencies(type),
  34201. target: compiler.FactoryTarget.Directive,
  34202. });
  34203. }
  34204. return ngFactoryDef;
  34205. },
  34206. // Make the property configurable in dev mode to allow overriding in tests
  34207. configurable: !!ngDevMode,
  34208. });
  34209. }
  34210. function extendsDirectlyFromObject(type) {
  34211. return Object.getPrototypeOf(type.prototype) === Object.prototype;
  34212. }
  34213. /**
  34214. * Extract the `R3DirectiveMetadata` for a particular directive (either a `Directive` or a
  34215. * `Component`).
  34216. */
  34217. function directiveMetadata(type, metadata) {
  34218. // Reflect inputs and outputs.
  34219. const reflect = getReflect();
  34220. const propMetadata = reflect.ownPropMetadata(type);
  34221. return {
  34222. name: type.name,
  34223. type: type,
  34224. selector: metadata.selector !== undefined ? metadata.selector : null,
  34225. host: metadata.host || EMPTY_OBJ,
  34226. propMetadata: propMetadata,
  34227. inputs: metadata.inputs || EMPTY_ARRAY,
  34228. outputs: metadata.outputs || EMPTY_ARRAY,
  34229. queries: extractQueriesMetadata(type, propMetadata, isContentQuery),
  34230. lifecycle: { usesOnChanges: reflect.hasLifecycleHook(type, 'ngOnChanges') },
  34231. typeSourceSpan: null,
  34232. usesInheritance: !extendsDirectlyFromObject(type),
  34233. exportAs: extractExportAs(metadata.exportAs),
  34234. providers: metadata.providers || null,
  34235. viewQueries: extractQueriesMetadata(type, propMetadata, isViewQuery),
  34236. isStandalone: metadata.standalone === undefined ? true : !!metadata.standalone,
  34237. isSignal: !!metadata.signals,
  34238. hostDirectives: metadata.hostDirectives?.map((directive) => typeof directive === 'function' ? { directive } : directive) || null,
  34239. };
  34240. }
  34241. /**
  34242. * Adds a directive definition to all parent classes of a type that don't have an Angular decorator.
  34243. */
  34244. function addDirectiveDefToUndecoratedParents(type) {
  34245. const objPrototype = Object.prototype;
  34246. let parent = Object.getPrototypeOf(type.prototype).constructor;
  34247. // Go up the prototype until we hit `Object`.
  34248. while (parent && parent !== objPrototype) {
  34249. // Since inheritance works if the class was annotated already, we only need to add
  34250. // the def if there are no annotations and the def hasn't been created already.
  34251. if (!getDirectiveDef(parent) &&
  34252. !getComponentDef(parent) &&
  34253. shouldAddAbstractDirective(parent)) {
  34254. compileDirective(parent, null);
  34255. }
  34256. parent = Object.getPrototypeOf(parent);
  34257. }
  34258. }
  34259. function convertToR3QueryPredicate(selector) {
  34260. return typeof selector === 'string' ? splitByComma(selector) : resolveForwardRef(selector);
  34261. }
  34262. function convertToR3QueryMetadata(propertyName, ann) {
  34263. return {
  34264. propertyName: propertyName,
  34265. predicate: convertToR3QueryPredicate(ann.selector),
  34266. descendants: ann.descendants,
  34267. first: ann.first,
  34268. read: ann.read ? ann.read : null,
  34269. static: !!ann.static,
  34270. emitDistinctChangesOnly: !!ann.emitDistinctChangesOnly,
  34271. isSignal: !!ann.isSignal,
  34272. };
  34273. }
  34274. function extractQueriesMetadata(type, propMetadata, isQueryAnn) {
  34275. const queriesMeta = [];
  34276. for (const field in propMetadata) {
  34277. if (propMetadata.hasOwnProperty(field)) {
  34278. const annotations = propMetadata[field];
  34279. annotations.forEach((ann) => {
  34280. if (isQueryAnn(ann)) {
  34281. if (!ann.selector) {
  34282. throw new Error(`Can't construct a query for the property "${field}" of ` +
  34283. `"${stringifyForError(type)}" since the query selector wasn't defined.`);
  34284. }
  34285. if (annotations.some(isInputAnnotation)) {
  34286. throw new Error(`Cannot combine @Input decorators with query decorators`);
  34287. }
  34288. queriesMeta.push(convertToR3QueryMetadata(field, ann));
  34289. }
  34290. });
  34291. }
  34292. }
  34293. return queriesMeta;
  34294. }
  34295. function extractExportAs(exportAs) {
  34296. return exportAs === undefined ? null : splitByComma(exportAs);
  34297. }
  34298. function isContentQuery(value) {
  34299. const name = value.ngMetadataName;
  34300. return name === 'ContentChild' || name === 'ContentChildren';
  34301. }
  34302. function isViewQuery(value) {
  34303. const name = value.ngMetadataName;
  34304. return name === 'ViewChild' || name === 'ViewChildren';
  34305. }
  34306. function isInputAnnotation(value) {
  34307. return value.ngMetadataName === 'Input';
  34308. }
  34309. function splitByComma(value) {
  34310. return value.split(',').map((piece) => piece.trim());
  34311. }
  34312. const LIFECYCLE_HOOKS = [
  34313. 'ngOnChanges',
  34314. 'ngOnInit',
  34315. 'ngOnDestroy',
  34316. 'ngDoCheck',
  34317. 'ngAfterViewInit',
  34318. 'ngAfterViewChecked',
  34319. 'ngAfterContentInit',
  34320. 'ngAfterContentChecked',
  34321. ];
  34322. function shouldAddAbstractDirective(type) {
  34323. const reflect = getReflect();
  34324. if (LIFECYCLE_HOOKS.some((hookName) => reflect.hasLifecycleHook(type, hookName))) {
  34325. return true;
  34326. }
  34327. const propMetadata = reflect.propMetadata(type);
  34328. for (const field in propMetadata) {
  34329. const annotations = propMetadata[field];
  34330. for (let i = 0; i < annotations.length; i++) {
  34331. const current = annotations[i];
  34332. const metadataName = current.ngMetadataName;
  34333. if (isInputAnnotation(current) ||
  34334. isContentQuery(current) ||
  34335. isViewQuery(current) ||
  34336. metadataName === 'Output' ||
  34337. metadataName === 'HostBinding' ||
  34338. metadataName === 'HostListener') {
  34339. return true;
  34340. }
  34341. }
  34342. }
  34343. return false;
  34344. }
  34345. function compilePipe(type, meta) {
  34346. let ngPipeDef = null;
  34347. let ngFactoryDef = null;
  34348. Object.defineProperty(type, NG_FACTORY_DEF, {
  34349. get: () => {
  34350. if (ngFactoryDef === null) {
  34351. const metadata = getPipeMetadata(type, meta);
  34352. const compiler = getCompilerFacade({
  34353. usage: 0 /* JitCompilerUsage.Decorator */,
  34354. kind: 'pipe',
  34355. type: metadata.type,
  34356. });
  34357. ngFactoryDef = compiler.compileFactory(angularCoreEnv, `ng:///${metadata.name}/ɵfac.js`, {
  34358. name: metadata.name,
  34359. type: metadata.type,
  34360. typeArgumentCount: 0,
  34361. deps: reflectDependencies(type),
  34362. target: compiler.FactoryTarget.Pipe,
  34363. });
  34364. }
  34365. return ngFactoryDef;
  34366. },
  34367. // Make the property configurable in dev mode to allow overriding in tests
  34368. configurable: !!ngDevMode,
  34369. });
  34370. Object.defineProperty(type, NG_PIPE_DEF, {
  34371. get: () => {
  34372. if (ngPipeDef === null) {
  34373. const metadata = getPipeMetadata(type, meta);
  34374. const compiler = getCompilerFacade({
  34375. usage: 0 /* JitCompilerUsage.Decorator */,
  34376. kind: 'pipe',
  34377. type: metadata.type,
  34378. });
  34379. ngPipeDef = compiler.compilePipe(angularCoreEnv, `ng:///${metadata.name}/ɵpipe.js`, metadata);
  34380. }
  34381. return ngPipeDef;
  34382. },
  34383. // Make the property configurable in dev mode to allow overriding in tests
  34384. configurable: !!ngDevMode,
  34385. });
  34386. }
  34387. function getPipeMetadata(type, meta) {
  34388. return {
  34389. type: type,
  34390. name: type.name,
  34391. pipeName: meta.name,
  34392. pure: meta.pure !== undefined ? meta.pure : true,
  34393. isStandalone: meta.standalone === undefined ? true : !!meta.standalone,
  34394. };
  34395. }
  34396. /**
  34397. * Type of the Directive metadata.
  34398. *
  34399. * @publicApi
  34400. */
  34401. const Directive = makeDecorator('Directive', (dir = {}) => dir, undefined, undefined, (type, meta) => compileDirective(type, meta));
  34402. /**
  34403. * Component decorator and metadata.
  34404. *
  34405. * @Annotation
  34406. * @publicApi
  34407. */
  34408. const Component = makeDecorator('Component', (c = {}) => ({ changeDetection: ChangeDetectionStrategy.Default, ...c }), Directive, undefined, (type, meta) => compileComponent(type, meta));
  34409. /**
  34410. * @Annotation
  34411. * @publicApi
  34412. */
  34413. const Pipe = makeDecorator('Pipe', (p) => ({ pure: true, ...p }), undefined, undefined, (type, meta) => compilePipe(type, meta));
  34414. /**
  34415. * @Annotation
  34416. * @publicApi
  34417. */
  34418. const Input = makePropDecorator('Input', (arg) => {
  34419. if (!arg) {
  34420. return {};
  34421. }
  34422. return typeof arg === 'string' ? { alias: arg } : arg;
  34423. });
  34424. /**
  34425. * @Annotation
  34426. * @publicApi
  34427. */
  34428. const Output = makePropDecorator('Output', (alias) => ({ alias }));
  34429. /**
  34430. * @Annotation
  34431. * @publicApi
  34432. */
  34433. const HostBinding = makePropDecorator('HostBinding', (hostPropertyName) => ({ hostPropertyName }));
  34434. /**
  34435. * @Annotation
  34436. * @publicApi
  34437. */
  34438. const HostListener = makePropDecorator('HostListener', (eventName, args) => ({ eventName, args }));
  34439. /**
  34440. * @Annotation
  34441. */
  34442. const NgModule = makeDecorator('NgModule', (ngModule) => ngModule, undefined, undefined,
  34443. /**
  34444. * Decorator that marks the following class as an NgModule, and supplies
  34445. * configuration metadata for it.
  34446. *
  34447. * * The `declarations` option configures the compiler
  34448. * with information about what belongs to the NgModule.
  34449. * * The `providers` options configures the NgModule's injector to provide
  34450. * dependencies the NgModule members.
  34451. * * The `imports` and `exports` options bring in members from other modules, and make
  34452. * this module's members available to others.
  34453. */
  34454. (type, meta) => compileNgModule(type, meta));
  34455. /**
  34456. * @description Represents the version of Angular
  34457. *
  34458. * @publicApi
  34459. */
  34460. class Version {
  34461. full;
  34462. major;
  34463. minor;
  34464. patch;
  34465. constructor(full) {
  34466. this.full = full;
  34467. const parts = full.split('.');
  34468. this.major = parts[0];
  34469. this.minor = parts[1];
  34470. this.patch = parts.slice(2).join('.');
  34471. }
  34472. }
  34473. /**
  34474. * @publicApi
  34475. */
  34476. const VERSION = new Version('19.2.13');
  34477. /**
  34478. * Combination of NgModuleFactory and ComponentFactories.
  34479. *
  34480. * @publicApi
  34481. *
  34482. * @deprecated
  34483. * Ivy JIT mode doesn't require accessing this symbol.
  34484. */
  34485. class ModuleWithComponentFactories {
  34486. ngModuleFactory;
  34487. componentFactories;
  34488. constructor(ngModuleFactory, componentFactories) {
  34489. this.ngModuleFactory = ngModuleFactory;
  34490. this.componentFactories = componentFactories;
  34491. }
  34492. }
  34493. /**
  34494. * Low-level service for running the angular compiler during runtime
  34495. * to create {@link ComponentFactory}s, which
  34496. * can later be used to create and render a Component instance.
  34497. *
  34498. * Each `@NgModule` provides an own `Compiler` to its injector,
  34499. * that will use the directives/pipes of the ng module for compilation
  34500. * of components.
  34501. *
  34502. * @publicApi
  34503. *
  34504. * @deprecated
  34505. * Ivy JIT mode doesn't require accessing this symbol.
  34506. */
  34507. class Compiler {
  34508. /**
  34509. * Compiles the given NgModule and all of its components. All templates of the components
  34510. * have to be inlined.
  34511. */
  34512. compileModuleSync(moduleType) {
  34513. return new NgModuleFactory(moduleType);
  34514. }
  34515. /**
  34516. * Compiles the given NgModule and all of its components
  34517. */
  34518. compileModuleAsync(moduleType) {
  34519. return Promise.resolve(this.compileModuleSync(moduleType));
  34520. }
  34521. /**
  34522. * Same as {@link Compiler#compileModuleSync compileModuleSync} but also creates ComponentFactories for all components.
  34523. */
  34524. compileModuleAndAllComponentsSync(moduleType) {
  34525. const ngModuleFactory = this.compileModuleSync(moduleType);
  34526. const moduleDef = getNgModuleDef(moduleType);
  34527. const componentFactories = maybeUnwrapFn(moduleDef.declarations).reduce((factories, declaration) => {
  34528. const componentDef = getComponentDef(declaration);
  34529. componentDef && factories.push(new ComponentFactory(componentDef));
  34530. return factories;
  34531. }, []);
  34532. return new ModuleWithComponentFactories(ngModuleFactory, componentFactories);
  34533. }
  34534. /**
  34535. * Same as {@link Compiler#compileModuleAsync compileModuleAsync} but also creates ComponentFactories for all components.
  34536. */
  34537. compileModuleAndAllComponentsAsync(moduleType) {
  34538. return Promise.resolve(this.compileModuleAndAllComponentsSync(moduleType));
  34539. }
  34540. /**
  34541. * Clears all caches.
  34542. */
  34543. clearCache() { }
  34544. /**
  34545. * Clears the cache for the given component/ngModule.
  34546. */
  34547. clearCacheFor(type) { }
  34548. /**
  34549. * Returns the id for a given NgModule, if one is defined and known to the compiler.
  34550. */
  34551. getModuleId(moduleType) {
  34552. return undefined;
  34553. }
  34554. static ɵfac = function Compiler_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || Compiler)(); };
  34555. static ɵprov = /*@__PURE__*/ ɵɵdefineInjectable({ token: Compiler, factory: Compiler.ɵfac, providedIn: 'root' });
  34556. }
  34557. (() => { (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(Compiler, [{
  34558. type: Injectable,
  34559. args: [{ providedIn: 'root' }]
  34560. }], null, null); })();
  34561. /**
  34562. * Token to provide CompilerOptions in the platform injector.
  34563. *
  34564. * @publicApi
  34565. */
  34566. const COMPILER_OPTIONS = new InjectionToken(ngDevMode ? 'compilerOptions' : '');
  34567. /**
  34568. * A factory for creating a Compiler
  34569. *
  34570. * @publicApi
  34571. *
  34572. * @deprecated
  34573. * Ivy JIT mode doesn't require accessing this symbol.
  34574. */
  34575. class CompilerFactory {
  34576. }
  34577. function compileNgModuleFactory(injector, options, moduleType) {
  34578. ngDevMode && assertNgModuleType(moduleType);
  34579. const moduleFactory = new NgModuleFactory(moduleType);
  34580. // All of the logic below is irrelevant for AOT-compiled code.
  34581. if (typeof ngJitMode !== 'undefined' && !ngJitMode) {
  34582. return Promise.resolve(moduleFactory);
  34583. }
  34584. const compilerOptions = injector.get(COMPILER_OPTIONS, []).concat(options);
  34585. // Configure the compiler to use the provided options. This call may fail when multiple modules
  34586. // are bootstrapped with incompatible options, as a component can only be compiled according to
  34587. // a single set of options.
  34588. setJitOptions({
  34589. defaultEncapsulation: _lastDefined(compilerOptions.map((opts) => opts.defaultEncapsulation)),
  34590. preserveWhitespaces: _lastDefined(compilerOptions.map((opts) => opts.preserveWhitespaces)),
  34591. });
  34592. if (isComponentResourceResolutionQueueEmpty()) {
  34593. return Promise.resolve(moduleFactory);
  34594. }
  34595. const compilerProviders = compilerOptions.flatMap((option) => option.providers ?? []);
  34596. // In case there are no compiler providers, we just return the module factory as
  34597. // there won't be any resource loader. This can happen with Ivy, because AOT compiled
  34598. // modules can be still passed through "bootstrapModule". In that case we shouldn't
  34599. // unnecessarily require the JIT compiler.
  34600. if (compilerProviders.length === 0) {
  34601. return Promise.resolve(moduleFactory);
  34602. }
  34603. const compiler = getCompilerFacade({
  34604. usage: 0 /* JitCompilerUsage.Decorator */,
  34605. kind: 'NgModule',
  34606. type: moduleType,
  34607. });
  34608. const compilerInjector = Injector.create({ providers: compilerProviders });
  34609. const resourceLoader = compilerInjector.get(compiler.ResourceLoader);
  34610. // The resource loader can also return a string while the "resolveComponentResources"
  34611. // always expects a promise. Therefore we need to wrap the returned value in a promise.
  34612. return resolveComponentResources((url) => Promise.resolve(resourceLoader.get(url))).then(() => moduleFactory);
  34613. }
  34614. function _lastDefined(args) {
  34615. for (let i = args.length - 1; i >= 0; i--) {
  34616. if (args[i] !== undefined) {
  34617. return args[i];
  34618. }
  34619. }
  34620. return undefined;
  34621. }
  34622. class NgZoneChangeDetectionScheduler {
  34623. zone = inject(NgZone);
  34624. changeDetectionScheduler = inject(ChangeDetectionScheduler);
  34625. applicationRef = inject(ApplicationRef);
  34626. _onMicrotaskEmptySubscription;
  34627. initialize() {
  34628. if (this._onMicrotaskEmptySubscription) {
  34629. return;
  34630. }
  34631. this._onMicrotaskEmptySubscription = this.zone.onMicrotaskEmpty.subscribe({
  34632. next: () => {
  34633. // `onMicroTaskEmpty` can happen _during_ the zoneless scheduler change detection because
  34634. // zone.run(() => {}) will result in `checkStable` at the end of the `zone.run` closure
  34635. // and emit `onMicrotaskEmpty` synchronously if run coalsecing is false.
  34636. if (this.changeDetectionScheduler.runningTick) {
  34637. return;
  34638. }
  34639. this.zone.run(() => {
  34640. this.applicationRef.tick();
  34641. });
  34642. },
  34643. });
  34644. }
  34645. ngOnDestroy() {
  34646. this._onMicrotaskEmptySubscription?.unsubscribe();
  34647. }
  34648. static ɵfac = function NgZoneChangeDetectionScheduler_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || NgZoneChangeDetectionScheduler)(); };
  34649. static ɵprov = /*@__PURE__*/ ɵɵdefineInjectable({ token: NgZoneChangeDetectionScheduler, factory: NgZoneChangeDetectionScheduler.ɵfac, providedIn: 'root' });
  34650. }
  34651. (() => { (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(NgZoneChangeDetectionScheduler, [{
  34652. type: Injectable,
  34653. args: [{ providedIn: 'root' }]
  34654. }], null, null); })();
  34655. /**
  34656. * Internal token used to verify that `provideZoneChangeDetection` is not used
  34657. * with the bootstrapModule API.
  34658. */
  34659. const PROVIDED_NG_ZONE = new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'provideZoneChangeDetection token' : '', { factory: () => false });
  34660. function internalProvideZoneChangeDetection({ ngZoneFactory, ignoreChangesOutsideZone, scheduleInRootZone, }) {
  34661. ngZoneFactory ??= () => new NgZone({ ...getNgZoneOptions(), scheduleInRootZone });
  34662. return [
  34663. { provide: NgZone, useFactory: ngZoneFactory },
  34664. {
  34665. provide: ENVIRONMENT_INITIALIZER,
  34666. multi: true,
  34667. useFactory: () => {
  34668. const ngZoneChangeDetectionScheduler = inject(NgZoneChangeDetectionScheduler, {
  34669. optional: true,
  34670. });
  34671. if ((typeof ngDevMode === 'undefined' || ngDevMode) &&
  34672. ngZoneChangeDetectionScheduler === null) {
  34673. throw new RuntimeError(402 /* RuntimeErrorCode.MISSING_REQUIRED_INJECTABLE_IN_BOOTSTRAP */, `A required Injectable was not found in the dependency injection tree. ` +
  34674. 'If you are bootstrapping an NgModule, make sure that the `BrowserModule` is imported.');
  34675. }
  34676. return () => ngZoneChangeDetectionScheduler.initialize();
  34677. },
  34678. },
  34679. {
  34680. provide: ENVIRONMENT_INITIALIZER,
  34681. multi: true,
  34682. useFactory: () => {
  34683. const service = inject(ZoneStablePendingTask);
  34684. return () => {
  34685. service.initialize();
  34686. };
  34687. },
  34688. },
  34689. // Always disable scheduler whenever explicitly disabled, even if another place called
  34690. // `provideZoneChangeDetection` without the 'ignore' option.
  34691. ignoreChangesOutsideZone === true ? { provide: ZONELESS_SCHEDULER_DISABLED, useValue: true } : [],
  34692. {
  34693. provide: SCHEDULE_IN_ROOT_ZONE,
  34694. useValue: scheduleInRootZone ?? SCHEDULE_IN_ROOT_ZONE_DEFAULT,
  34695. },
  34696. ];
  34697. }
  34698. /**
  34699. * Provides `NgZone`-based change detection for the application bootstrapped using
  34700. * `bootstrapApplication`.
  34701. *
  34702. * `NgZone` is already provided in applications by default. This provider allows you to configure
  34703. * options like `eventCoalescing` in the `NgZone`.
  34704. * This provider is not available for `platformBrowser().bootstrapModule`, which uses
  34705. * `BootstrapOptions` instead.
  34706. *
  34707. * @usageNotes
  34708. * ```ts
  34709. * bootstrapApplication(MyApp, {providers: [
  34710. * provideZoneChangeDetection({eventCoalescing: true}),
  34711. * ]});
  34712. * ```
  34713. *
  34714. * @publicApi
  34715. * @see {@link /api/platform-browser/bootstrapApplication bootstrapApplication}
  34716. * @see {@link NgZoneOptions}
  34717. */
  34718. function provideZoneChangeDetection(options) {
  34719. const ignoreChangesOutsideZone = options?.ignoreChangesOutsideZone;
  34720. const scheduleInRootZone = options?.scheduleInRootZone;
  34721. const zoneProviders = internalProvideZoneChangeDetection({
  34722. ngZoneFactory: () => {
  34723. const ngZoneOptions = getNgZoneOptions(options);
  34724. ngZoneOptions.scheduleInRootZone = scheduleInRootZone;
  34725. if (ngZoneOptions.shouldCoalesceEventChangeDetection) {
  34726. performanceMarkFeature('NgZone_CoalesceEvent');
  34727. }
  34728. return new NgZone(ngZoneOptions);
  34729. },
  34730. ignoreChangesOutsideZone,
  34731. scheduleInRootZone,
  34732. });
  34733. return makeEnvironmentProviders([
  34734. { provide: PROVIDED_NG_ZONE, useValue: true },
  34735. { provide: ZONELESS_ENABLED, useValue: false },
  34736. zoneProviders,
  34737. ]);
  34738. }
  34739. // Transforms a set of `BootstrapOptions` (supported by the NgModule-based bootstrap APIs) ->
  34740. // `NgZoneOptions` that are recognized by the NgZone constructor. Passing no options will result in
  34741. // a set of default options returned.
  34742. function getNgZoneOptions(options) {
  34743. return {
  34744. enableLongStackTrace: typeof ngDevMode === 'undefined' ? false : !!ngDevMode,
  34745. shouldCoalesceEventChangeDetection: options?.eventCoalescing ?? false,
  34746. shouldCoalesceRunChangeDetection: options?.runCoalescing ?? false,
  34747. };
  34748. }
  34749. class ZoneStablePendingTask {
  34750. subscription = new Subscription();
  34751. initialized = false;
  34752. zone = inject(NgZone);
  34753. pendingTasks = inject(PendingTasksInternal);
  34754. initialize() {
  34755. if (this.initialized) {
  34756. return;
  34757. }
  34758. this.initialized = true;
  34759. let task = null;
  34760. if (!this.zone.isStable && !this.zone.hasPendingMacrotasks && !this.zone.hasPendingMicrotasks) {
  34761. task = this.pendingTasks.add();
  34762. }
  34763. this.zone.runOutsideAngular(() => {
  34764. this.subscription.add(this.zone.onStable.subscribe(() => {
  34765. NgZone.assertNotInAngularZone();
  34766. // Check whether there are no pending macro/micro tasks in the next tick
  34767. // to allow for NgZone to update the state.
  34768. queueMicrotask(() => {
  34769. if (task !== null &&
  34770. !this.zone.hasPendingMacrotasks &&
  34771. !this.zone.hasPendingMicrotasks) {
  34772. this.pendingTasks.remove(task);
  34773. task = null;
  34774. }
  34775. });
  34776. }));
  34777. });
  34778. this.subscription.add(this.zone.onUnstable.subscribe(() => {
  34779. NgZone.assertInAngularZone();
  34780. task ??= this.pendingTasks.add();
  34781. }));
  34782. }
  34783. ngOnDestroy() {
  34784. this.subscription.unsubscribe();
  34785. }
  34786. static ɵfac = function ZoneStablePendingTask_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || ZoneStablePendingTask)(); };
  34787. static ɵprov = /*@__PURE__*/ ɵɵdefineInjectable({ token: ZoneStablePendingTask, factory: ZoneStablePendingTask.ɵfac, providedIn: 'root' });
  34788. }
  34789. (() => { (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(ZoneStablePendingTask, [{
  34790. type: Injectable,
  34791. args: [{ providedIn: 'root' }]
  34792. }], null, null); })();
  34793. const CONSECUTIVE_MICROTASK_NOTIFICATION_LIMIT = 100;
  34794. let consecutiveMicrotaskNotifications = 0;
  34795. let stackFromLastFewNotifications = [];
  34796. function trackMicrotaskNotificationForDebugging() {
  34797. consecutiveMicrotaskNotifications++;
  34798. if (CONSECUTIVE_MICROTASK_NOTIFICATION_LIMIT - consecutiveMicrotaskNotifications < 5) {
  34799. const stack = new Error().stack;
  34800. if (stack) {
  34801. stackFromLastFewNotifications.push(stack);
  34802. }
  34803. }
  34804. if (consecutiveMicrotaskNotifications === CONSECUTIVE_MICROTASK_NOTIFICATION_LIMIT) {
  34805. throw new RuntimeError(103 /* RuntimeErrorCode.INFINITE_CHANGE_DETECTION */, 'Angular could not stabilize because there were endless change notifications within the browser event loop. ' +
  34806. 'The stack from the last several notifications: \n' +
  34807. stackFromLastFewNotifications.join('\n'));
  34808. }
  34809. }
  34810. class ChangeDetectionSchedulerImpl {
  34811. appRef = inject(ApplicationRef);
  34812. taskService = inject(PendingTasksInternal);
  34813. ngZone = inject(NgZone);
  34814. zonelessEnabled = inject(ZONELESS_ENABLED);
  34815. tracing = inject(TracingService, { optional: true });
  34816. disableScheduling = inject(ZONELESS_SCHEDULER_DISABLED, { optional: true }) ?? false;
  34817. zoneIsDefined = typeof Zone !== 'undefined' && !!Zone.root.run;
  34818. schedulerTickApplyArgs = [{ data: { '__scheduler_tick__': true } }];
  34819. subscriptions = new Subscription();
  34820. angularZoneId = this.zoneIsDefined
  34821. ? this.ngZone._inner?.get(angularZoneInstanceIdProperty)
  34822. : null;
  34823. scheduleInRootZone = !this.zonelessEnabled &&
  34824. this.zoneIsDefined &&
  34825. (inject(SCHEDULE_IN_ROOT_ZONE, { optional: true }) ?? false);
  34826. cancelScheduledCallback = null;
  34827. useMicrotaskScheduler = false;
  34828. runningTick = false;
  34829. pendingRenderTaskId = null;
  34830. constructor() {
  34831. this.subscriptions.add(this.appRef.afterTick.subscribe(() => {
  34832. // If the scheduler isn't running a tick but the application ticked, that means
  34833. // someone called ApplicationRef.tick manually. In this case, we should cancel
  34834. // any change detections that had been scheduled so we don't run an extra one.
  34835. if (!this.runningTick) {
  34836. this.cleanup();
  34837. }
  34838. }));
  34839. this.subscriptions.add(this.ngZone.onUnstable.subscribe(() => {
  34840. // If the zone becomes unstable when we're not running tick (this happens from the zone.run),
  34841. // we should cancel any scheduled change detection here because at this point we
  34842. // know that the zone will stabilize at some point and run change detection itself.
  34843. if (!this.runningTick) {
  34844. this.cleanup();
  34845. }
  34846. }));
  34847. // TODO(atscott): These conditions will need to change when zoneless is the default
  34848. // Instead, they should flip to checking if ZoneJS scheduling is provided
  34849. this.disableScheduling ||=
  34850. !this.zonelessEnabled &&
  34851. // NoopNgZone without enabling zoneless means no scheduling whatsoever
  34852. (this.ngZone instanceof NoopNgZone ||
  34853. // The same goes for the lack of Zone without enabling zoneless scheduling
  34854. !this.zoneIsDefined);
  34855. }
  34856. notify(source) {
  34857. if (!this.zonelessEnabled && source === 5 /* NotificationSource.Listener */) {
  34858. // When the notification comes from a listener, we skip the notification unless the
  34859. // application has enabled zoneless. Ideally, listeners wouldn't notify the scheduler at all
  34860. // automatically. We do not know that a developer made a change in the listener callback that
  34861. // requires an `ApplicationRef.tick` (synchronize templates / run render hooks). We do this
  34862. // only for an easier migration from OnPush components to zoneless. Because listeners are
  34863. // usually executed inside the Angular zone and listeners automatically call `markViewDirty`,
  34864. // developers never needed to manually use `ChangeDetectorRef.markForCheck` or some other API
  34865. // to make listener callbacks work correctly with `OnPush` components.
  34866. return;
  34867. }
  34868. let force = false;
  34869. switch (source) {
  34870. case 0 /* NotificationSource.MarkAncestorsForTraversal */: {
  34871. this.appRef.dirtyFlags |= 2 /* ApplicationRefDirtyFlags.ViewTreeTraversal */;
  34872. break;
  34873. }
  34874. case 3 /* NotificationSource.DebugApplyChanges */:
  34875. case 2 /* NotificationSource.DeferBlockStateUpdate */:
  34876. case 4 /* NotificationSource.MarkForCheck */:
  34877. case 5 /* NotificationSource.Listener */:
  34878. case 1 /* NotificationSource.SetInput */: {
  34879. this.appRef.dirtyFlags |= 4 /* ApplicationRefDirtyFlags.ViewTreeCheck */;
  34880. break;
  34881. }
  34882. case 6 /* NotificationSource.CustomElement */: {
  34883. // We use `ViewTreeTraversal` to ensure we refresh the element even if this is triggered
  34884. // during CD. In practice this is a no-op since the elements code also calls via a
  34885. // `markForRefresh()` API which sends `NotificationSource.MarkAncestorsForTraversal` anyway.
  34886. this.appRef.dirtyFlags |= 2 /* ApplicationRefDirtyFlags.ViewTreeTraversal */;
  34887. force = true;
  34888. break;
  34889. }
  34890. case 12 /* NotificationSource.RootEffect */: {
  34891. this.appRef.dirtyFlags |= 16 /* ApplicationRefDirtyFlags.RootEffects */;
  34892. // Root effects still force a CD, even if the scheduler is disabled. This ensures that
  34893. // effects always run, even when triggered from outside the zone when the scheduler is
  34894. // otherwise disabled.
  34895. force = true;
  34896. break;
  34897. }
  34898. case 13 /* NotificationSource.ViewEffect */: {
  34899. // This is technically a no-op, since view effects will also send a
  34900. // `MarkAncestorsForTraversal` notification. Still, we set this for logical consistency.
  34901. this.appRef.dirtyFlags |= 2 /* ApplicationRefDirtyFlags.ViewTreeTraversal */;
  34902. // View effects still force a CD, even if the scheduler is disabled. This ensures that
  34903. // effects always run, even when triggered from outside the zone when the scheduler is
  34904. // otherwise disabled.
  34905. force = true;
  34906. break;
  34907. }
  34908. case 11 /* NotificationSource.PendingTaskRemoved */: {
  34909. // Removing a pending task via the public API forces a scheduled tick, ensuring that
  34910. // stability is async and delayed until there was at least an opportunity to run
  34911. // application synchronization. This prevents some footguns when working with the
  34912. // public API for pending tasks where developers attempt to update application state
  34913. // immediately after removing the last task.
  34914. force = true;
  34915. break;
  34916. }
  34917. case 9 /* NotificationSource.ViewDetachedFromDOM */:
  34918. case 8 /* NotificationSource.ViewAttached */:
  34919. case 7 /* NotificationSource.RenderHook */:
  34920. case 10 /* NotificationSource.AsyncAnimationsLoaded */:
  34921. default: {
  34922. // These notifications only schedule a tick but do not change whether we should refresh
  34923. // views. Instead, we only need to run render hooks unless another notification from the
  34924. // other set is also received before `tick` happens.
  34925. this.appRef.dirtyFlags |= 8 /* ApplicationRefDirtyFlags.AfterRender */;
  34926. }
  34927. }
  34928. // If not already defined, attempt to capture a tracing snapshot of this
  34929. // notification so that the resulting CD run can be attributed to the
  34930. // context which produced the notification.
  34931. this.appRef.tracingSnapshot = this.tracing?.snapshot(this.appRef.tracingSnapshot) ?? null;
  34932. if (!this.shouldScheduleTick(force)) {
  34933. return;
  34934. }
  34935. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  34936. if (this.useMicrotaskScheduler) {
  34937. trackMicrotaskNotificationForDebugging();
  34938. }
  34939. else {
  34940. consecutiveMicrotaskNotifications = 0;
  34941. stackFromLastFewNotifications.length = 0;
  34942. }
  34943. }
  34944. const scheduleCallback = this.useMicrotaskScheduler
  34945. ? scheduleCallbackWithMicrotask
  34946. : scheduleCallbackWithRafRace;
  34947. this.pendingRenderTaskId = this.taskService.add();
  34948. if (this.scheduleInRootZone) {
  34949. this.cancelScheduledCallback = Zone.root.run(() => scheduleCallback(() => this.tick()));
  34950. }
  34951. else {
  34952. this.cancelScheduledCallback = this.ngZone.runOutsideAngular(() => scheduleCallback(() => this.tick()));
  34953. }
  34954. }
  34955. shouldScheduleTick(force) {
  34956. if ((this.disableScheduling && !force) || this.appRef.destroyed) {
  34957. return false;
  34958. }
  34959. // already scheduled or running
  34960. if (this.pendingRenderTaskId !== null || this.runningTick || this.appRef._runningTick) {
  34961. return false;
  34962. }
  34963. // If we're inside the zone don't bother with scheduler. Zone will stabilize
  34964. // eventually and run change detection.
  34965. if (!this.zonelessEnabled &&
  34966. this.zoneIsDefined &&
  34967. Zone.current.get(angularZoneInstanceIdProperty + this.angularZoneId)) {
  34968. return false;
  34969. }
  34970. return true;
  34971. }
  34972. /**
  34973. * Calls ApplicationRef._tick inside the `NgZone`.
  34974. *
  34975. * Calling `tick` directly runs change detection and cancels any change detection that had been
  34976. * scheduled previously.
  34977. *
  34978. * @param shouldRefreshViews Passed directly to `ApplicationRef._tick` and skips straight to
  34979. * render hooks when `false`.
  34980. */
  34981. tick() {
  34982. // When ngZone.run below exits, onMicrotaskEmpty may emit if the zone is
  34983. // stable. We want to prevent double ticking so we track whether the tick is
  34984. // already running and skip it if so.
  34985. if (this.runningTick || this.appRef.destroyed) {
  34986. return;
  34987. }
  34988. // If we reach the tick and there is no work to be done in ApplicationRef.tick,
  34989. // skip it altogether and clean up. There may be no work if, for example, the only
  34990. // event that notified the scheduler was the removal of a pending task.
  34991. if (this.appRef.dirtyFlags === 0 /* ApplicationRefDirtyFlags.None */) {
  34992. this.cleanup();
  34993. return;
  34994. }
  34995. // The scheduler used to pass "whether to check views" as a boolean flag instead of setting
  34996. // fine-grained dirtiness flags, and global checking was always used on the first pass. This
  34997. // created an interesting edge case: if a notification made a view dirty and then ticked via the
  34998. // scheduler (and not the zone) a global check was still performed.
  34999. //
  35000. // Ideally, this would not be the case, and only zone-based ticks would do global passes.
  35001. // However this is a breaking change and requires fixes in g3. Until this cleanup can be done,
  35002. // we add the `ViewTreeGlobal` flag to request a global check if any views are dirty in a
  35003. // scheduled tick (unless zoneless is enabled, in which case global checks aren't really a
  35004. // thing).
  35005. //
  35006. // TODO(alxhub): clean up and remove this workaround as a breaking change.
  35007. if (!this.zonelessEnabled && this.appRef.dirtyFlags & 7 /* ApplicationRefDirtyFlags.ViewTreeAny */) {
  35008. this.appRef.dirtyFlags |= 1 /* ApplicationRefDirtyFlags.ViewTreeGlobal */;
  35009. }
  35010. const task = this.taskService.add();
  35011. try {
  35012. this.ngZone.run(() => {
  35013. this.runningTick = true;
  35014. this.appRef._tick();
  35015. }, undefined, this.schedulerTickApplyArgs);
  35016. }
  35017. catch (e) {
  35018. this.taskService.remove(task);
  35019. throw e;
  35020. }
  35021. finally {
  35022. this.cleanup();
  35023. }
  35024. // If we're notified of a change within 1 microtask of running change
  35025. // detection, run another round in the same event loop. This allows code
  35026. // which uses Promise.resolve (see NgModel) to avoid
  35027. // ExpressionChanged...Error to still be reflected in a single browser
  35028. // paint, even if that spans multiple rounds of change detection.
  35029. this.useMicrotaskScheduler = true;
  35030. scheduleCallbackWithMicrotask(() => {
  35031. this.useMicrotaskScheduler = false;
  35032. this.taskService.remove(task);
  35033. });
  35034. }
  35035. ngOnDestroy() {
  35036. this.subscriptions.unsubscribe();
  35037. this.cleanup();
  35038. }
  35039. cleanup() {
  35040. this.runningTick = false;
  35041. this.cancelScheduledCallback?.();
  35042. this.cancelScheduledCallback = null;
  35043. // If this is the last task, the service will synchronously emit a stable
  35044. // notification. If there is a subscriber that then acts in a way that
  35045. // tries to notify the scheduler again, we need to be able to respond to
  35046. // schedule a new change detection. Therefore, we should clear the task ID
  35047. // before removing it from the pending tasks (or the tasks service should
  35048. // not synchronously emit stable, similar to how Zone stableness only
  35049. // happens if it's still stable after a microtask).
  35050. if (this.pendingRenderTaskId !== null) {
  35051. const taskId = this.pendingRenderTaskId;
  35052. this.pendingRenderTaskId = null;
  35053. this.taskService.remove(taskId);
  35054. }
  35055. }
  35056. static ɵfac = function ChangeDetectionSchedulerImpl_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || ChangeDetectionSchedulerImpl)(); };
  35057. static ɵprov = /*@__PURE__*/ ɵɵdefineInjectable({ token: ChangeDetectionSchedulerImpl, factory: ChangeDetectionSchedulerImpl.ɵfac, providedIn: 'root' });
  35058. }
  35059. (() => { (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(ChangeDetectionSchedulerImpl, [{
  35060. type: Injectable,
  35061. args: [{ providedIn: 'root' }]
  35062. }], () => [], null); })();
  35063. /**
  35064. * Provides change detection without ZoneJS for the application bootstrapped using
  35065. * `bootstrapApplication`.
  35066. *
  35067. * This function allows you to configure the application to not use the state/state changes of
  35068. * ZoneJS to schedule change detection in the application. This will work when ZoneJS is not present
  35069. * on the page at all or if it exists because something else is using it (either another Angular
  35070. * application which uses ZoneJS for scheduling or some other library that relies on ZoneJS).
  35071. *
  35072. * This can also be added to the `TestBed` providers to configure the test environment to more
  35073. * closely match production behavior. This will help give higher confidence that components are
  35074. * compatible with zoneless change detection.
  35075. *
  35076. * ZoneJS uses browser events to trigger change detection. When using this provider, Angular will
  35077. * instead use Angular APIs to schedule change detection. These APIs include:
  35078. *
  35079. * - `ChangeDetectorRef.markForCheck`
  35080. * - `ComponentRef.setInput`
  35081. * - updating a signal that is read in a template
  35082. * - when bound host or template listeners are triggered
  35083. * - attaching a view that was marked dirty by one of the above
  35084. * - removing a view
  35085. * - registering a render hook (templates are only refreshed if render hooks do one of the above)
  35086. *
  35087. * @usageNotes
  35088. * ```ts
  35089. * bootstrapApplication(MyApp, {providers: [
  35090. * provideExperimentalZonelessChangeDetection(),
  35091. * ]});
  35092. * ```
  35093. *
  35094. * This API is experimental. Neither the shape, nor the underlying behavior is stable and can change
  35095. * in patch versions. There are known feature gaps and API ergonomic considerations. We will iterate
  35096. * on the exact API based on the feedback and our understanding of the problem and solution space.
  35097. *
  35098. * @publicApi
  35099. * @experimental
  35100. * @see {@link /api/platform-browser/bootstrapApplication bootstrapApplication}
  35101. */
  35102. function provideExperimentalZonelessChangeDetection() {
  35103. performanceMarkFeature('NgZoneless');
  35104. if ((typeof ngDevMode === 'undefined' || ngDevMode) && typeof Zone !== 'undefined' && Zone) {
  35105. const message = formatRuntimeError(914 /* RuntimeErrorCode.UNEXPECTED_ZONEJS_PRESENT_IN_ZONELESS_MODE */, `The application is using zoneless change detection, but is still loading Zone.js. ` +
  35106. `Consider removing Zone.js to get the full benefits of zoneless. ` +
  35107. `In applications using the Angular CLI, Zone.js is typically included in the "polyfills" section of the angular.json file.`);
  35108. console.warn(message);
  35109. }
  35110. return makeEnvironmentProviders([
  35111. { provide: ChangeDetectionScheduler, useExisting: ChangeDetectionSchedulerImpl },
  35112. { provide: NgZone, useClass: NoopNgZone },
  35113. { provide: ZONELESS_ENABLED, useValue: true },
  35114. { provide: SCHEDULE_IN_ROOT_ZONE, useValue: false },
  35115. typeof ngDevMode === 'undefined' || ngDevMode
  35116. ? [{ provide: PROVIDED_ZONELESS, useValue: true }]
  35117. : [],
  35118. ]);
  35119. }
  35120. /// <reference path="../../../goog.d.ts" />
  35121. /**
  35122. * Work out the locale from the potential global properties.
  35123. *
  35124. * * Closure Compiler: use `goog.LOCALE`.
  35125. * * Ivy enabled: use `$localize.locale`
  35126. */
  35127. function getGlobalLocale() {
  35128. if (typeof ngI18nClosureMode !== 'undefined' &&
  35129. ngI18nClosureMode &&
  35130. typeof goog !== 'undefined' &&
  35131. goog.LOCALE !== 'en') {
  35132. // * The default `goog.LOCALE` value is `en`, while Angular used `en-US`.
  35133. // * In order to preserve backwards compatibility, we use Angular default value over
  35134. // Closure Compiler's one.
  35135. return goog.LOCALE;
  35136. }
  35137. else {
  35138. // KEEP `typeof $localize !== 'undefined' && $localize.locale` IN SYNC WITH THE LOCALIZE
  35139. // COMPILE-TIME INLINER.
  35140. //
  35141. // * During compile time inlining of translations the expression will be replaced
  35142. // with a string literal that is the current locale. Other forms of this expression are not
  35143. // guaranteed to be replaced.
  35144. //
  35145. // * During runtime translation evaluation, the developer is required to set `$localize.locale`
  35146. // if required, or just to provide their own `LOCALE_ID` provider.
  35147. return (typeof $localize !== 'undefined' && $localize.locale) || DEFAULT_LOCALE_ID;
  35148. }
  35149. }
  35150. /**
  35151. * Provide this token to set the locale of your application.
  35152. * It is used for i18n extraction, by i18n pipes (DatePipe, I18nPluralPipe, CurrencyPipe,
  35153. * DecimalPipe and PercentPipe) and by ICU expressions.
  35154. *
  35155. * See the [i18n guide](guide/i18n/locale-id) for more information.
  35156. *
  35157. * @usageNotes
  35158. * ### Example
  35159. *
  35160. * ```ts
  35161. * import { LOCALE_ID } from '@angular/core';
  35162. * import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
  35163. * import { AppModule } from './app/app.module';
  35164. *
  35165. * platformBrowserDynamic().bootstrapModule(AppModule, {
  35166. * providers: [{provide: LOCALE_ID, useValue: 'en-US' }]
  35167. * });
  35168. * ```
  35169. *
  35170. * @publicApi
  35171. */
  35172. const LOCALE_ID = new InjectionToken(ngDevMode ? 'LocaleId' : '', {
  35173. providedIn: 'root',
  35174. factory: () => inject(LOCALE_ID, InjectFlags.Optional | InjectFlags.SkipSelf) || getGlobalLocale(),
  35175. });
  35176. /**
  35177. * Provide this token to set the default currency code your application uses for
  35178. * CurrencyPipe when there is no currency code passed into it. This is only used by
  35179. * CurrencyPipe and has no relation to locale currency. Defaults to USD if not configured.
  35180. *
  35181. * See the [i18n guide](guide/i18n/locale-id) for more information.
  35182. *
  35183. * <div class="docs-alert docs-alert-helpful">
  35184. *
  35185. * The default currency code is currently always `USD`.
  35186. *
  35187. * If you need the previous behavior then set it by creating a `DEFAULT_CURRENCY_CODE` provider in
  35188. * your application `NgModule`:
  35189. *
  35190. * ```ts
  35191. * {provide: DEFAULT_CURRENCY_CODE, useValue: 'USD'}
  35192. * ```
  35193. *
  35194. * </div>
  35195. *
  35196. * @usageNotes
  35197. * ### Example
  35198. *
  35199. * ```ts
  35200. * import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
  35201. * import { AppModule } from './app/app.module';
  35202. *
  35203. * platformBrowserDynamic().bootstrapModule(AppModule, {
  35204. * providers: [{provide: DEFAULT_CURRENCY_CODE, useValue: 'EUR' }]
  35205. * });
  35206. * ```
  35207. *
  35208. * @publicApi
  35209. */
  35210. const DEFAULT_CURRENCY_CODE = new InjectionToken(ngDevMode ? 'DefaultCurrencyCode' : '', {
  35211. providedIn: 'root',
  35212. factory: () => USD_CURRENCY_CODE,
  35213. });
  35214. /**
  35215. * Use this token at bootstrap to provide the content of your translation file (`xtb`,
  35216. * `xlf` or `xlf2`) when you want to translate your application in another language.
  35217. *
  35218. * See the [i18n guide](guide/i18n/merge) for more information.
  35219. *
  35220. * @usageNotes
  35221. * ### Example
  35222. *
  35223. * ```ts
  35224. * import { TRANSLATIONS } from '@angular/core';
  35225. * import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
  35226. * import { AppModule } from './app/app.module';
  35227. *
  35228. * // content of your translation file
  35229. * const translations = '....';
  35230. *
  35231. * platformBrowserDynamic().bootstrapModule(AppModule, {
  35232. * providers: [{provide: TRANSLATIONS, useValue: translations }]
  35233. * });
  35234. * ```
  35235. *
  35236. * @publicApi
  35237. */
  35238. const TRANSLATIONS = new InjectionToken(ngDevMode ? 'Translations' : '');
  35239. /**
  35240. * Provide this token at bootstrap to set the format of your {@link TRANSLATIONS}: `xtb`,
  35241. * `xlf` or `xlf2`.
  35242. *
  35243. * See the [i18n guide](guide/i18n/merge) for more information.
  35244. *
  35245. * @usageNotes
  35246. * ### Example
  35247. *
  35248. * ```ts
  35249. * import { TRANSLATIONS_FORMAT } from '@angular/core';
  35250. * import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
  35251. * import { AppModule } from './app/app.module';
  35252. *
  35253. * platformBrowserDynamic().bootstrapModule(AppModule, {
  35254. * providers: [{provide: TRANSLATIONS_FORMAT, useValue: 'xlf' }]
  35255. * });
  35256. * ```
  35257. *
  35258. * @publicApi
  35259. */
  35260. const TRANSLATIONS_FORMAT = new InjectionToken(ngDevMode ? 'TranslationsFormat' : '');
  35261. /**
  35262. * Use this enum at bootstrap as an option of `bootstrapModule` to define the strategy
  35263. * that the compiler should use in case of missing translations:
  35264. * - Error: throw if you have missing translations.
  35265. * - Warning (default): show a warning in the console and/or shell.
  35266. * - Ignore: do nothing.
  35267. *
  35268. * See the [i18n guide](guide/i18n/merge#report-missing-translations) for more information.
  35269. *
  35270. * @usageNotes
  35271. * ### Example
  35272. * ```ts
  35273. * import { MissingTranslationStrategy } from '@angular/core';
  35274. * import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
  35275. * import { AppModule } from './app/app.module';
  35276. *
  35277. * platformBrowserDynamic().bootstrapModule(AppModule, {
  35278. * missingTranslation: MissingTranslationStrategy.Error
  35279. * });
  35280. * ```
  35281. *
  35282. * @publicApi
  35283. */
  35284. var MissingTranslationStrategy;
  35285. (function (MissingTranslationStrategy) {
  35286. MissingTranslationStrategy[MissingTranslationStrategy["Error"] = 0] = "Error";
  35287. MissingTranslationStrategy[MissingTranslationStrategy["Warning"] = 1] = "Warning";
  35288. MissingTranslationStrategy[MissingTranslationStrategy["Ignore"] = 2] = "Ignore";
  35289. })(MissingTranslationStrategy || (MissingTranslationStrategy = {}));
  35290. // A delay in milliseconds before the scan is run after onLoad, to avoid any
  35291. // potential race conditions with other LCP-related functions. This delay
  35292. // happens outside of the main JavaScript execution and will only effect the timing
  35293. // on when the warning becomes visible in the console.
  35294. const SCAN_DELAY = 200;
  35295. const OVERSIZED_IMAGE_TOLERANCE = 1200;
  35296. class ImagePerformanceWarning {
  35297. // Map of full image URLs -> original `ngSrc` values.
  35298. window = null;
  35299. observer = null;
  35300. options = inject(IMAGE_CONFIG);
  35301. lcpImageUrl;
  35302. start() {
  35303. if ((typeof ngServerMode !== 'undefined' && ngServerMode) ||
  35304. typeof PerformanceObserver === 'undefined' ||
  35305. (this.options?.disableImageSizeWarning && this.options?.disableImageLazyLoadWarning)) {
  35306. return;
  35307. }
  35308. this.observer = this.initPerformanceObserver();
  35309. const doc = getDocument();
  35310. const win = doc.defaultView;
  35311. if (win) {
  35312. this.window = win;
  35313. // Wait to avoid race conditions where LCP image triggers
  35314. // load event before it's recorded by the performance observer
  35315. const waitToScan = () => {
  35316. setTimeout(this.scanImages.bind(this), SCAN_DELAY);
  35317. };
  35318. const setup = () => {
  35319. // Consider the case when the application is created and destroyed multiple times.
  35320. // Typically, applications are created instantly once the page is loaded, and the
  35321. // `window.load` listener is always triggered. However, the `window.load` event will never
  35322. // be fired if the page is loaded, and the application is created later. Checking for
  35323. // `readyState` is the easiest way to determine whether the page has been loaded or not.
  35324. if (doc.readyState === 'complete') {
  35325. waitToScan();
  35326. }
  35327. else {
  35328. this.window?.addEventListener('load', waitToScan, { once: true });
  35329. }
  35330. };
  35331. // Angular doesn't have to run change detection whenever any asynchronous tasks are invoked in
  35332. // the scope of this functionality.
  35333. if (typeof Zone !== 'undefined') {
  35334. Zone.root.run(() => setup());
  35335. }
  35336. else {
  35337. setup();
  35338. }
  35339. }
  35340. }
  35341. ngOnDestroy() {
  35342. this.observer?.disconnect();
  35343. }
  35344. initPerformanceObserver() {
  35345. if (typeof PerformanceObserver === 'undefined') {
  35346. return null;
  35347. }
  35348. const observer = new PerformanceObserver((entryList) => {
  35349. const entries = entryList.getEntries();
  35350. if (entries.length === 0)
  35351. return;
  35352. // We use the latest entry produced by the `PerformanceObserver` as the best
  35353. // signal on which element is actually an LCP one. As an example, the first image to load on
  35354. // a page, by virtue of being the only thing on the page so far, is often a LCP candidate
  35355. // and gets reported by PerformanceObserver, but isn't necessarily the LCP element.
  35356. const lcpElement = entries[entries.length - 1];
  35357. // Cast to `any` due to missing `element` on the `LargestContentfulPaint` type of entry.
  35358. // See https://developer.mozilla.org/en-US/docs/Web/API/LargestContentfulPaint
  35359. const imgSrc = lcpElement.element?.src ?? '';
  35360. // Exclude `data:` and `blob:` URLs, since they are fetched resources.
  35361. if (imgSrc.startsWith('data:') || imgSrc.startsWith('blob:'))
  35362. return;
  35363. this.lcpImageUrl = imgSrc;
  35364. });
  35365. observer.observe({ type: 'largest-contentful-paint', buffered: true });
  35366. return observer;
  35367. }
  35368. scanImages() {
  35369. const images = getDocument().querySelectorAll('img');
  35370. let lcpElementFound, lcpElementLoadedCorrectly = false;
  35371. images.forEach((image) => {
  35372. if (!this.options?.disableImageSizeWarning) {
  35373. // Image elements using the NgOptimizedImage directive are excluded,
  35374. // as that directive has its own version of this check.
  35375. if (!image.getAttribute('ng-img') && this.isOversized(image)) {
  35376. logOversizedImageWarning(image.src);
  35377. }
  35378. }
  35379. if (!this.options?.disableImageLazyLoadWarning && this.lcpImageUrl) {
  35380. if (image.src === this.lcpImageUrl) {
  35381. lcpElementFound = true;
  35382. if (image.loading !== 'lazy' || image.getAttribute('ng-img')) {
  35383. // This variable is set to true and never goes back to false to account
  35384. // for the case where multiple images have the same src url, and some
  35385. // have lazy loading while others don't.
  35386. // Also ignore NgOptimizedImage because there's a different warning for that.
  35387. lcpElementLoadedCorrectly = true;
  35388. }
  35389. }
  35390. }
  35391. });
  35392. if (lcpElementFound &&
  35393. !lcpElementLoadedCorrectly &&
  35394. this.lcpImageUrl &&
  35395. !this.options?.disableImageLazyLoadWarning) {
  35396. logLazyLCPWarning(this.lcpImageUrl);
  35397. }
  35398. }
  35399. isOversized(image) {
  35400. if (!this.window) {
  35401. return false;
  35402. }
  35403. // The `isOversized` check may not be applicable or may require adjustments
  35404. // for several types of image formats or scenarios. Currently, we specify only
  35405. // `svg`, but this may also include `gif` since their quality isn’t tied to
  35406. // dimensions in the same way as raster images.
  35407. const nonOversizedImageExtentions = [
  35408. // SVG images are vector-based, which means they can scale
  35409. // to any size without losing quality.
  35410. '.svg',
  35411. ];
  35412. // Convert it to lowercase because this may have uppercase
  35413. // extensions, such as `IMAGE.SVG`.
  35414. // We fallback to an empty string because `src` may be `undefined`
  35415. // if it is explicitly set to `null` by some third-party code
  35416. // (e.g., `image.src = null`).
  35417. const imageSource = (image.src || '').toLowerCase();
  35418. if (nonOversizedImageExtentions.some((extension) => imageSource.endsWith(extension))) {
  35419. return false;
  35420. }
  35421. const computedStyle = this.window.getComputedStyle(image);
  35422. let renderedWidth = parseFloat(computedStyle.getPropertyValue('width'));
  35423. let renderedHeight = parseFloat(computedStyle.getPropertyValue('height'));
  35424. const boxSizing = computedStyle.getPropertyValue('box-sizing');
  35425. const objectFit = computedStyle.getPropertyValue('object-fit');
  35426. if (objectFit === `cover`) {
  35427. // Object fit cover may indicate a use case such as a sprite sheet where
  35428. // this warning does not apply.
  35429. return false;
  35430. }
  35431. if (boxSizing === 'border-box') {
  35432. // If the image `box-sizing` is set to `border-box`, we adjust the rendered
  35433. // dimensions by subtracting padding values.
  35434. const paddingTop = computedStyle.getPropertyValue('padding-top');
  35435. const paddingRight = computedStyle.getPropertyValue('padding-right');
  35436. const paddingBottom = computedStyle.getPropertyValue('padding-bottom');
  35437. const paddingLeft = computedStyle.getPropertyValue('padding-left');
  35438. renderedWidth -= parseFloat(paddingRight) + parseFloat(paddingLeft);
  35439. renderedHeight -= parseFloat(paddingTop) + parseFloat(paddingBottom);
  35440. }
  35441. const intrinsicWidth = image.naturalWidth;
  35442. const intrinsicHeight = image.naturalHeight;
  35443. const recommendedWidth = this.window.devicePixelRatio * renderedWidth;
  35444. const recommendedHeight = this.window.devicePixelRatio * renderedHeight;
  35445. const oversizedWidth = intrinsicWidth - recommendedWidth >= OVERSIZED_IMAGE_TOLERANCE;
  35446. const oversizedHeight = intrinsicHeight - recommendedHeight >= OVERSIZED_IMAGE_TOLERANCE;
  35447. return oversizedWidth || oversizedHeight;
  35448. }
  35449. static ɵfac = function ImagePerformanceWarning_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || ImagePerformanceWarning)(); };
  35450. static ɵprov = /*@__PURE__*/ ɵɵdefineInjectable({ token: ImagePerformanceWarning, factory: ImagePerformanceWarning.ɵfac, providedIn: 'root' });
  35451. }
  35452. (() => { (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(ImagePerformanceWarning, [{
  35453. type: Injectable,
  35454. args: [{ providedIn: 'root' }]
  35455. }], null, null); })();
  35456. function logLazyLCPWarning(src) {
  35457. console.warn(formatRuntimeError(-913 /* RuntimeErrorCode.IMAGE_PERFORMANCE_WARNING */, `An image with src ${src} is the Largest Contentful Paint (LCP) element ` +
  35458. `but was given a "loading" value of "lazy", which can negatively impact ` +
  35459. `application loading performance. This warning can be addressed by ` +
  35460. `changing the loading value of the LCP image to "eager", or by using the ` +
  35461. `NgOptimizedImage directive's prioritization utilities. For more ` +
  35462. `information about addressing or disabling this warning, see ` +
  35463. `https://angular.dev/errors/NG0913`));
  35464. }
  35465. function logOversizedImageWarning(src) {
  35466. console.warn(formatRuntimeError(-913 /* RuntimeErrorCode.IMAGE_PERFORMANCE_WARNING */, `An image with src ${src} has intrinsic file dimensions much larger than its ` +
  35467. `rendered size. This can negatively impact application loading performance. ` +
  35468. `For more information about addressing or disabling this warning, see ` +
  35469. `https://angular.dev/errors/NG0913`));
  35470. }
  35471. /**
  35472. * Internal token that allows to register extra callbacks that should be invoked during the
  35473. * `PlatformRef.destroy` operation. This token is needed to avoid a direct reference to the
  35474. * `PlatformRef` class (i.e. register the callback via `PlatformRef.onDestroy`), thus making the
  35475. * entire class tree-shakeable.
  35476. */
  35477. const PLATFORM_DESTROY_LISTENERS = new InjectionToken(ngDevMode ? 'PlatformDestroyListeners' : '');
  35478. /**
  35479. * InjectionToken to control root component bootstrap behavior.
  35480. *
  35481. * This token is primarily used in Angular's server-side rendering (SSR) scenarios,
  35482. * particularly by the `@angular/ssr` package, to manage whether the root component
  35483. * should be bootstrapped during the application initialization process.
  35484. *
  35485. * ## Purpose:
  35486. * During SSR route extraction, setting this token to `false` prevents Angular from
  35487. * bootstrapping the root component. This avoids unnecessary component rendering,
  35488. * enabling route extraction without requiring additional APIs or triggering
  35489. * component logic.
  35490. *
  35491. * ## Behavior:
  35492. * - **`false`**: Prevents the root component from being bootstrapped.
  35493. * - **`true`** (default): Proceeds with the normal root component bootstrap process.
  35494. *
  35495. * This mechanism ensures SSR can efficiently separate route extraction logic
  35496. * from component rendering.
  35497. */
  35498. const ENABLE_ROOT_COMPONENT_BOOTSTRAP = new InjectionToken(ngDevMode ? 'ENABLE_ROOT_COMPONENT_BOOTSTRAP' : '');
  35499. function isApplicationBootstrapConfig(config) {
  35500. return !config.moduleRef;
  35501. }
  35502. function bootstrap(config) {
  35503. const envInjector = isApplicationBootstrapConfig(config)
  35504. ? config.r3Injector
  35505. : config.moduleRef.injector;
  35506. const ngZone = envInjector.get(NgZone);
  35507. return ngZone.run(() => {
  35508. if (isApplicationBootstrapConfig(config)) {
  35509. config.r3Injector.resolveInjectorInitializers();
  35510. }
  35511. else {
  35512. config.moduleRef.resolveInjectorInitializers();
  35513. }
  35514. const exceptionHandler = envInjector.get(ErrorHandler, null);
  35515. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  35516. if (exceptionHandler === null) {
  35517. const errorMessage = isApplicationBootstrapConfig(config)
  35518. ? 'No `ErrorHandler` found in the Dependency Injection tree.'
  35519. : 'No ErrorHandler. Is platform module (BrowserModule) included';
  35520. throw new RuntimeError(402 /* RuntimeErrorCode.MISSING_REQUIRED_INJECTABLE_IN_BOOTSTRAP */, errorMessage);
  35521. }
  35522. if (envInjector.get(PROVIDED_ZONELESS) && envInjector.get(PROVIDED_NG_ZONE)) {
  35523. throw new RuntimeError(408 /* RuntimeErrorCode.PROVIDED_BOTH_ZONE_AND_ZONELESS */, 'Invalid change detection configuration: ' +
  35524. 'provideZoneChangeDetection and provideExperimentalZonelessChangeDetection cannot be used together.');
  35525. }
  35526. }
  35527. let onErrorSubscription;
  35528. ngZone.runOutsideAngular(() => {
  35529. onErrorSubscription = ngZone.onError.subscribe({
  35530. next: (error) => {
  35531. exceptionHandler.handleError(error);
  35532. },
  35533. });
  35534. });
  35535. // If the whole platform is destroyed, invoke the `destroy` method
  35536. // for all bootstrapped applications as well.
  35537. if (isApplicationBootstrapConfig(config)) {
  35538. const destroyListener = () => envInjector.destroy();
  35539. const onPlatformDestroyListeners = config.platformInjector.get(PLATFORM_DESTROY_LISTENERS);
  35540. onPlatformDestroyListeners.add(destroyListener);
  35541. envInjector.onDestroy(() => {
  35542. onErrorSubscription.unsubscribe();
  35543. onPlatformDestroyListeners.delete(destroyListener);
  35544. });
  35545. }
  35546. else {
  35547. const destroyListener = () => config.moduleRef.destroy();
  35548. const onPlatformDestroyListeners = config.platformInjector.get(PLATFORM_DESTROY_LISTENERS);
  35549. onPlatformDestroyListeners.add(destroyListener);
  35550. config.moduleRef.onDestroy(() => {
  35551. remove(config.allPlatformModules, config.moduleRef);
  35552. onErrorSubscription.unsubscribe();
  35553. onPlatformDestroyListeners.delete(destroyListener);
  35554. });
  35555. }
  35556. return _callAndReportToErrorHandler(exceptionHandler, ngZone, () => {
  35557. const initStatus = envInjector.get(ApplicationInitStatus);
  35558. initStatus.runInitializers();
  35559. return initStatus.donePromise.then(() => {
  35560. // If the `LOCALE_ID` provider is defined at bootstrap then we set the value for ivy
  35561. const localeId = envInjector.get(LOCALE_ID, DEFAULT_LOCALE_ID);
  35562. setLocaleId(localeId || DEFAULT_LOCALE_ID);
  35563. const enableRootComponentBoostrap = envInjector.get(ENABLE_ROOT_COMPONENT_BOOTSTRAP, true);
  35564. if (!enableRootComponentBoostrap) {
  35565. if (isApplicationBootstrapConfig(config)) {
  35566. return envInjector.get(ApplicationRef);
  35567. }
  35568. config.allPlatformModules.push(config.moduleRef);
  35569. return config.moduleRef;
  35570. }
  35571. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  35572. const imagePerformanceService = envInjector.get(ImagePerformanceWarning);
  35573. imagePerformanceService.start();
  35574. }
  35575. if (isApplicationBootstrapConfig(config)) {
  35576. const appRef = envInjector.get(ApplicationRef);
  35577. if (config.rootComponent !== undefined) {
  35578. appRef.bootstrap(config.rootComponent);
  35579. }
  35580. return appRef;
  35581. }
  35582. else {
  35583. moduleDoBootstrap(config.moduleRef, config.allPlatformModules);
  35584. return config.moduleRef;
  35585. }
  35586. });
  35587. });
  35588. });
  35589. }
  35590. function moduleDoBootstrap(moduleRef, allPlatformModules) {
  35591. const appRef = moduleRef.injector.get(ApplicationRef);
  35592. if (moduleRef._bootstrapComponents.length > 0) {
  35593. moduleRef._bootstrapComponents.forEach((f) => appRef.bootstrap(f));
  35594. }
  35595. else if (moduleRef.instance.ngDoBootstrap) {
  35596. moduleRef.instance.ngDoBootstrap(appRef);
  35597. }
  35598. else {
  35599. throw new RuntimeError(-403 /* RuntimeErrorCode.BOOTSTRAP_COMPONENTS_NOT_FOUND */, ngDevMode &&
  35600. `The module ${stringify(moduleRef.instance.constructor)} was bootstrapped, ` +
  35601. `but it does not declare "@NgModule.bootstrap" components nor a "ngDoBootstrap" method. ` +
  35602. `Please define one of these.`);
  35603. }
  35604. allPlatformModules.push(moduleRef);
  35605. }
  35606. function _callAndReportToErrorHandler(errorHandler, ngZone, callback) {
  35607. try {
  35608. const result = callback();
  35609. if (isPromise(result)) {
  35610. return result.catch((e) => {
  35611. ngZone.runOutsideAngular(() => errorHandler.handleError(e));
  35612. // rethrow as the exception handler might not do it
  35613. throw e;
  35614. });
  35615. }
  35616. return result;
  35617. }
  35618. catch (e) {
  35619. ngZone.runOutsideAngular(() => errorHandler.handleError(e));
  35620. // rethrow as the exception handler might not do it
  35621. throw e;
  35622. }
  35623. }
  35624. /**
  35625. * The Angular platform is the entry point for Angular on a web page.
  35626. * Each page has exactly one platform. Services (such as reflection) which are common
  35627. * to every Angular application running on the page are bound in its scope.
  35628. * A page's platform is initialized implicitly when a platform is created using a platform
  35629. * factory such as `PlatformBrowser`, or explicitly by calling the `createPlatform()` function.
  35630. *
  35631. * @publicApi
  35632. */
  35633. class PlatformRef {
  35634. _injector;
  35635. _modules = [];
  35636. _destroyListeners = [];
  35637. _destroyed = false;
  35638. /** @internal */
  35639. constructor(_injector) {
  35640. this._injector = _injector;
  35641. }
  35642. /**
  35643. * Creates an instance of an `@NgModule` for the given platform.
  35644. *
  35645. * @deprecated Passing NgModule factories as the `PlatformRef.bootstrapModuleFactory` function
  35646. * argument is deprecated. Use the `PlatformRef.bootstrapModule` API instead.
  35647. */
  35648. bootstrapModuleFactory(moduleFactory, options) {
  35649. const scheduleInRootZone = options?.scheduleInRootZone;
  35650. const ngZoneFactory = () => getNgZone(options?.ngZone, {
  35651. ...getNgZoneOptions({
  35652. eventCoalescing: options?.ngZoneEventCoalescing,
  35653. runCoalescing: options?.ngZoneRunCoalescing,
  35654. }),
  35655. scheduleInRootZone,
  35656. });
  35657. const ignoreChangesOutsideZone = options?.ignoreChangesOutsideZone;
  35658. const allAppProviders = [
  35659. internalProvideZoneChangeDetection({
  35660. ngZoneFactory,
  35661. ignoreChangesOutsideZone,
  35662. }),
  35663. { provide: ChangeDetectionScheduler, useExisting: ChangeDetectionSchedulerImpl },
  35664. ];
  35665. const moduleRef = createNgModuleRefWithProviders(moduleFactory.moduleType, this.injector, allAppProviders);
  35666. return bootstrap({
  35667. moduleRef,
  35668. allPlatformModules: this._modules,
  35669. platformInjector: this.injector,
  35670. });
  35671. }
  35672. /**
  35673. * Creates an instance of an `@NgModule` for a given platform.
  35674. *
  35675. * @usageNotes
  35676. * ### Simple Example
  35677. *
  35678. * ```ts
  35679. * @NgModule({
  35680. * imports: [BrowserModule]
  35681. * })
  35682. * class MyModule {}
  35683. *
  35684. * let moduleRef = platformBrowser().bootstrapModule(MyModule);
  35685. * ```
  35686. *
  35687. */
  35688. bootstrapModule(moduleType, compilerOptions = []) {
  35689. const options = optionsReducer({}, compilerOptions);
  35690. return compileNgModuleFactory(this.injector, options, moduleType).then((moduleFactory) => this.bootstrapModuleFactory(moduleFactory, options));
  35691. }
  35692. /**
  35693. * Registers a listener to be called when the platform is destroyed.
  35694. */
  35695. onDestroy(callback) {
  35696. this._destroyListeners.push(callback);
  35697. }
  35698. /**
  35699. * Retrieves the platform {@link Injector}, which is the parent injector for
  35700. * every Angular application on the page and provides singleton providers.
  35701. */
  35702. get injector() {
  35703. return this._injector;
  35704. }
  35705. /**
  35706. * Destroys the current Angular platform and all Angular applications on the page.
  35707. * Destroys all modules and listeners registered with the platform.
  35708. */
  35709. destroy() {
  35710. if (this._destroyed) {
  35711. throw new RuntimeError(404 /* RuntimeErrorCode.PLATFORM_ALREADY_DESTROYED */, ngDevMode && 'The platform has already been destroyed!');
  35712. }
  35713. this._modules.slice().forEach((module) => module.destroy());
  35714. this._destroyListeners.forEach((listener) => listener());
  35715. const destroyListeners = this._injector.get(PLATFORM_DESTROY_LISTENERS, null);
  35716. if (destroyListeners) {
  35717. destroyListeners.forEach((listener) => listener());
  35718. destroyListeners.clear();
  35719. }
  35720. this._destroyed = true;
  35721. }
  35722. /**
  35723. * Indicates whether this instance was destroyed.
  35724. */
  35725. get destroyed() {
  35726. return this._destroyed;
  35727. }
  35728. static ɵfac = function PlatformRef_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || PlatformRef)(ɵɵinject(Injector)); };
  35729. static ɵprov = /*@__PURE__*/ ɵɵdefineInjectable({ token: PlatformRef, factory: PlatformRef.ɵfac, providedIn: 'platform' });
  35730. }
  35731. (() => { (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(PlatformRef, [{
  35732. type: Injectable,
  35733. args: [{ providedIn: 'platform' }]
  35734. }], () => [{ type: Injector }], null); })();
  35735. let _platformInjector = null;
  35736. /**
  35737. * Internal token to indicate whether having multiple bootstrapped platform should be allowed (only
  35738. * one bootstrapped platform is allowed by default). This token helps to support SSR scenarios.
  35739. */
  35740. const ALLOW_MULTIPLE_PLATFORMS = new InjectionToken(ngDevMode ? 'AllowMultipleToken' : '');
  35741. /**
  35742. * Creates a platform.
  35743. * Platforms must be created on launch using this function.
  35744. *
  35745. * @publicApi
  35746. */
  35747. function createPlatform(injector) {
  35748. if (_platformInjector && !_platformInjector.get(ALLOW_MULTIPLE_PLATFORMS, false)) {
  35749. throw new RuntimeError(400 /* RuntimeErrorCode.MULTIPLE_PLATFORMS */, ngDevMode && 'There can be only one platform. Destroy the previous one to create a new one.');
  35750. }
  35751. publishDefaultGlobalUtils();
  35752. publishSignalConfiguration();
  35753. _platformInjector = injector;
  35754. const platform = injector.get(PlatformRef);
  35755. runPlatformInitializers(injector);
  35756. return platform;
  35757. }
  35758. /**
  35759. * Creates a factory for a platform. Can be used to provide or override `Providers` specific to
  35760. * your application's runtime needs, such as `PLATFORM_INITIALIZER` and `PLATFORM_ID`.
  35761. * @param parentPlatformFactory Another platform factory to modify. Allows you to compose factories
  35762. * to build up configurations that might be required by different libraries or parts of the
  35763. * application.
  35764. * @param name Identifies the new platform factory.
  35765. * @param providers A set of dependency providers for platforms created with the new factory.
  35766. *
  35767. * @publicApi
  35768. */
  35769. function createPlatformFactory(parentPlatformFactory, name, providers = []) {
  35770. const desc = `Platform: ${name}`;
  35771. const marker = new InjectionToken(desc);
  35772. return (extraProviders = []) => {
  35773. let platform = getPlatform();
  35774. if (!platform || platform.injector.get(ALLOW_MULTIPLE_PLATFORMS, false)) {
  35775. const platformProviders = [
  35776. ...providers,
  35777. ...extraProviders,
  35778. { provide: marker, useValue: true },
  35779. ];
  35780. if (parentPlatformFactory) {
  35781. parentPlatformFactory(platformProviders);
  35782. }
  35783. else {
  35784. createPlatform(createPlatformInjector(platformProviders, desc));
  35785. }
  35786. }
  35787. return assertPlatform(marker);
  35788. };
  35789. }
  35790. /**
  35791. * Helper function to create an instance of a platform injector (that maintains the 'platform'
  35792. * scope).
  35793. */
  35794. function createPlatformInjector(providers = [], name) {
  35795. return Injector.create({
  35796. name,
  35797. providers: [
  35798. { provide: INJECTOR_SCOPE, useValue: 'platform' },
  35799. { provide: PLATFORM_DESTROY_LISTENERS, useValue: new Set([() => (_platformInjector = null)]) },
  35800. ...providers,
  35801. ],
  35802. });
  35803. }
  35804. /**
  35805. * Checks that there is currently a platform that contains the given token as a provider.
  35806. *
  35807. * @publicApi
  35808. */
  35809. function assertPlatform(requiredToken) {
  35810. const platform = getPlatform();
  35811. if (!platform) {
  35812. throw new RuntimeError(401 /* RuntimeErrorCode.PLATFORM_NOT_FOUND */, ngDevMode && 'No platform exists!');
  35813. }
  35814. if ((typeof ngDevMode === 'undefined' || ngDevMode) &&
  35815. !platform.injector.get(requiredToken, null)) {
  35816. throw new RuntimeError(400 /* RuntimeErrorCode.MULTIPLE_PLATFORMS */, 'A platform with a different configuration has been created. Please destroy it first.');
  35817. }
  35818. return platform;
  35819. }
  35820. /**
  35821. * Returns the current platform.
  35822. *
  35823. * @publicApi
  35824. */
  35825. function getPlatform() {
  35826. return _platformInjector?.get(PlatformRef) ?? null;
  35827. }
  35828. /**
  35829. * Destroys the current Angular platform and all Angular applications on the page.
  35830. * Destroys all modules and listeners registered with the platform.
  35831. *
  35832. * @publicApi
  35833. */
  35834. function destroyPlatform() {
  35835. getPlatform()?.destroy();
  35836. }
  35837. /**
  35838. * The goal of this function is to bootstrap a platform injector,
  35839. * but avoid referencing `PlatformRef` class.
  35840. * This function is needed for bootstrapping a Standalone Component.
  35841. */
  35842. function createOrReusePlatformInjector(providers = []) {
  35843. // If a platform injector already exists, it means that the platform
  35844. // is already bootstrapped and no additional actions are required.
  35845. if (_platformInjector)
  35846. return _platformInjector;
  35847. publishDefaultGlobalUtils();
  35848. // Otherwise, setup a new platform injector and run platform initializers.
  35849. const injector = createPlatformInjector(providers);
  35850. _platformInjector = injector;
  35851. publishSignalConfiguration();
  35852. runPlatformInitializers(injector);
  35853. return injector;
  35854. }
  35855. /**
  35856. * @description
  35857. * This function is used to provide initialization functions that will be executed upon
  35858. * initialization of the platform injector.
  35859. *
  35860. * Note that the provided initializer is run in the injection context.
  35861. *
  35862. * Previously, this was achieved using the `PLATFORM_INITIALIZER` token which is now deprecated.
  35863. *
  35864. * @see {@link PLATFORM_INITIALIZER}
  35865. *
  35866. * @publicApi
  35867. */
  35868. function providePlatformInitializer(initializerFn) {
  35869. return makeEnvironmentProviders([
  35870. {
  35871. provide: PLATFORM_INITIALIZER,
  35872. useValue: initializerFn,
  35873. multi: true,
  35874. },
  35875. ]);
  35876. }
  35877. function runPlatformInitializers(injector) {
  35878. const inits = injector.get(PLATFORM_INITIALIZER, null);
  35879. runInInjectionContext(injector, () => {
  35880. inits?.forEach((init) => init());
  35881. });
  35882. }
  35883. /**
  35884. * Used to periodically verify no expressions have changed after they were checked.
  35885. *
  35886. * @param options Used to configure when the check will execute.
  35887. * - `interval` will periodically run exhaustive `checkNoChanges` on application views
  35888. * - `useNgZoneOnStable` will use ZoneJS to determine when change detection might have run
  35889. * in an application using ZoneJS to drive change detection. When the `NgZone.onStable` would
  35890. * have emitted, all views attached to the `ApplicationRef` are checked for changes.
  35891. * - 'exhaustive' means that all views attached to `ApplicationRef` and all the descendants of those views will be
  35892. * checked for changes (excluding those subtrees which are detached via `ChangeDetectorRef.detach()`).
  35893. * This is useful because the check that runs after regular change detection does not work for components using `ChangeDetectionStrategy.OnPush`.
  35894. * This check is will surface any existing errors hidden by `OnPush` components. By default, this check is exhaustive
  35895. * and will always check all views, regardless of their "dirty" state and `ChangeDetectionStrategy`.
  35896. *
  35897. * When the `useNgZoneOnStable` option is `true`, this function will provide its own `NgZone` implementation and needs
  35898. * to come after any other `NgZone` provider, including `provideZoneChangeDetection()` and `provideExperimentalZonelessChangeDetection()`.
  35899. *
  35900. * @experimental
  35901. * @publicApi
  35902. */
  35903. function provideExperimentalCheckNoChangesForDebug(options) {
  35904. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  35905. if (options.interval === undefined && !options.useNgZoneOnStable) {
  35906. throw new Error('Must provide one of `useNgZoneOnStable` or `interval`');
  35907. }
  35908. const checkNoChangesMode = options?.exhaustive === false
  35909. ? CheckNoChangesMode.OnlyDirtyViews
  35910. : CheckNoChangesMode.Exhaustive;
  35911. return makeEnvironmentProviders([
  35912. options?.useNgZoneOnStable
  35913. ? { provide: NgZone, useFactory: () => new DebugNgZoneForCheckNoChanges(checkNoChangesMode) }
  35914. : [],
  35915. options?.interval !== undefined
  35916. ? exhaustiveCheckNoChangesInterval(options.interval, checkNoChangesMode)
  35917. : [],
  35918. {
  35919. provide: ENVIRONMENT_INITIALIZER,
  35920. multi: true,
  35921. useValue: () => {
  35922. if (options?.useNgZoneOnStable &&
  35923. !(inject(NgZone) instanceof DebugNgZoneForCheckNoChanges)) {
  35924. throw new Error('`provideExperimentalCheckNoChangesForDebug` with `useNgZoneOnStable` must be after any other provider for `NgZone`.');
  35925. }
  35926. },
  35927. },
  35928. ]);
  35929. }
  35930. else {
  35931. return makeEnvironmentProviders([]);
  35932. }
  35933. }
  35934. class DebugNgZoneForCheckNoChanges extends NgZone {
  35935. checkNoChangesMode;
  35936. applicationRef;
  35937. scheduler;
  35938. errorHandler;
  35939. injector = inject(EnvironmentInjector);
  35940. constructor(checkNoChangesMode) {
  35941. const zonelessEnabled = inject(ZONELESS_ENABLED);
  35942. // Use coalescing to ensure we aren't ever running this check synchronously
  35943. super({
  35944. shouldCoalesceEventChangeDetection: true,
  35945. shouldCoalesceRunChangeDetection: zonelessEnabled,
  35946. });
  35947. this.checkNoChangesMode = checkNoChangesMode;
  35948. if (zonelessEnabled) {
  35949. // prevent emits to ensure code doesn't rely on these
  35950. this.onMicrotaskEmpty.emit = () => { };
  35951. this.onStable.emit = () => {
  35952. this.scheduler ||= this.injector.get(ChangeDetectionSchedulerImpl);
  35953. if (this.scheduler.pendingRenderTaskId || this.scheduler.runningTick) {
  35954. return;
  35955. }
  35956. this.checkApplicationViews();
  35957. };
  35958. this.onUnstable.emit = () => { };
  35959. }
  35960. else {
  35961. this.runOutsideAngular(() => {
  35962. this.onStable.subscribe(() => {
  35963. this.checkApplicationViews();
  35964. });
  35965. });
  35966. }
  35967. }
  35968. checkApplicationViews() {
  35969. this.applicationRef ||= this.injector.get(ApplicationRef);
  35970. for (const view of this.applicationRef.allViews) {
  35971. try {
  35972. checkNoChangesInternal(view._lView, this.checkNoChangesMode, view.notifyErrorHandler);
  35973. }
  35974. catch (e) {
  35975. this.errorHandler ||= this.injector.get(ErrorHandler);
  35976. this.errorHandler.handleError(e);
  35977. }
  35978. }
  35979. }
  35980. }
  35981. function exhaustiveCheckNoChangesInterval(interval, checkNoChangesMode) {
  35982. return {
  35983. provide: ENVIRONMENT_INITIALIZER,
  35984. multi: true,
  35985. useFactory: () => {
  35986. const applicationRef = inject(ApplicationRef);
  35987. const errorHandler = inject(ErrorHandler);
  35988. const scheduler = inject(ChangeDetectionSchedulerImpl);
  35989. const ngZone = inject(NgZone);
  35990. return () => {
  35991. function scheduleCheckNoChanges() {
  35992. ngZone.runOutsideAngular(() => {
  35993. setTimeout(() => {
  35994. if (applicationRef.destroyed) {
  35995. return;
  35996. }
  35997. if (scheduler.pendingRenderTaskId || scheduler.runningTick) {
  35998. scheduleCheckNoChanges();
  35999. return;
  36000. }
  36001. for (const view of applicationRef.allViews) {
  36002. try {
  36003. checkNoChangesInternal(view._lView, checkNoChangesMode, view.notifyErrorHandler);
  36004. }
  36005. catch (e) {
  36006. errorHandler.handleError(e);
  36007. }
  36008. }
  36009. scheduleCheckNoChanges();
  36010. }, interval);
  36011. });
  36012. }
  36013. scheduleCheckNoChanges();
  36014. };
  36015. },
  36016. };
  36017. }
  36018. /**
  36019. * Returns whether Angular is in development mode.
  36020. *
  36021. * By default, this is true, unless `enableProdMode` is invoked prior to calling this method or the
  36022. * application is built using the Angular CLI with the `optimization` option.
  36023. * @see {@link /cli/build ng build}
  36024. *
  36025. * @publicApi
  36026. */
  36027. function isDevMode() {
  36028. return typeof ngDevMode === 'undefined' || !!ngDevMode;
  36029. }
  36030. /**
  36031. * Disable Angular's development mode, which turns off assertions and other
  36032. * checks within the framework.
  36033. *
  36034. * One important assertion this disables verifies that a change detection pass
  36035. * does not result in additional changes to any bindings (also known as
  36036. * unidirectional data flow).
  36037. *
  36038. * Using this method is discouraged as the Angular CLI will set production mode when using the
  36039. * `optimization` option.
  36040. * @see {@link /cli/build ng build}
  36041. *
  36042. * @publicApi
  36043. */
  36044. function enableProdMode() {
  36045. // The below check is there so when ngDevMode is set via terser
  36046. // `global['ngDevMode'] = false;` is also dropped.
  36047. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  36048. _global['ngDevMode'] = false;
  36049. }
  36050. }
  36051. /**
  36052. * Returns the NgModuleFactory with the given id (specified using [@NgModule.id
  36053. * field](api/core/NgModule#id)), if it exists and has been loaded. Factories for NgModules that do
  36054. * not specify an `id` cannot be retrieved. Throws if an NgModule cannot be found.
  36055. * @publicApi
  36056. * @deprecated Use `getNgModuleById` instead.
  36057. */
  36058. function getModuleFactory(id) {
  36059. const type = getRegisteredNgModuleType(id);
  36060. if (!type)
  36061. throw noModuleError(id);
  36062. return new NgModuleFactory(type);
  36063. }
  36064. /**
  36065. * Returns the NgModule class with the given id (specified using [@NgModule.id
  36066. * field](api/core/NgModule#id)), if it exists and has been loaded. Classes for NgModules that do
  36067. * not specify an `id` cannot be retrieved. Throws if an NgModule cannot be found.
  36068. * @publicApi
  36069. */
  36070. function getNgModuleById(id) {
  36071. const type = getRegisteredNgModuleType(id);
  36072. if (!type)
  36073. throw noModuleError(id);
  36074. return type;
  36075. }
  36076. function noModuleError(id) {
  36077. return new Error(`No module with ID ${id} loaded`);
  36078. }
  36079. /**
  36080. * Base class that provides change detection functionality.
  36081. * A change-detection tree collects all views that are to be checked for changes.
  36082. * Use the methods to add and remove views from the tree, initiate change-detection,
  36083. * and explicitly mark views as _dirty_, meaning that they have changed and need to be re-rendered.
  36084. *
  36085. * @see [Using change detection hooks](guide/components/lifecycle#using-change-detection-hooks)
  36086. * @see [Defining custom change detection](guide/components/lifecycle#defining-custom-change-detection)
  36087. *
  36088. * @usageNotes
  36089. *
  36090. * The following examples demonstrate how to modify default change-detection behavior
  36091. * to perform explicit detection when needed.
  36092. *
  36093. * ### Use `markForCheck()` with `CheckOnce` strategy
  36094. *
  36095. * The following example sets the `OnPush` change-detection strategy for a component
  36096. * (`CheckOnce`, rather than the default `CheckAlways`), then forces a second check
  36097. * after an interval.
  36098. *
  36099. * {@example core/ts/change_detect/change-detection.ts region='mark-for-check'}
  36100. *
  36101. * ### Detach change detector to limit how often check occurs
  36102. *
  36103. * The following example defines a component with a large list of read-only data
  36104. * that is expected to change constantly, many times per second.
  36105. * To improve performance, we want to check and update the list
  36106. * less often than the changes actually occur. To do that, we detach
  36107. * the component's change detector and perform an explicit local check every five seconds.
  36108. *
  36109. * {@example core/ts/change_detect/change-detection.ts region='detach'}
  36110. *
  36111. *
  36112. * ### Reattaching a detached component
  36113. *
  36114. * The following example creates a component displaying live data.
  36115. * The component detaches its change detector from the main change detector tree
  36116. * when the `live` property is set to false, and reattaches it when the property
  36117. * becomes true.
  36118. *
  36119. * {@example core/ts/change_detect/change-detection.ts region='reattach'}
  36120. *
  36121. * @publicApi
  36122. */
  36123. class ChangeDetectorRef {
  36124. /**
  36125. * @internal
  36126. * @nocollapse
  36127. */
  36128. static __NG_ELEMENT_ID__ = injectChangeDetectorRef;
  36129. }
  36130. /** Returns a ChangeDetectorRef (a.k.a. a ViewRef) */
  36131. function injectChangeDetectorRef(flags) {
  36132. return createViewRef(getCurrentTNode(), getLView(), (flags & 16 /* InternalInjectFlags.ForPipe */) === 16 /* InternalInjectFlags.ForPipe */);
  36133. }
  36134. /**
  36135. * Creates a ViewRef and stores it on the injector as ChangeDetectorRef (public alias).
  36136. *
  36137. * @param tNode The node that is requesting a ChangeDetectorRef
  36138. * @param lView The view to which the node belongs
  36139. * @param isPipe Whether the view is being injected into a pipe.
  36140. * @returns The ChangeDetectorRef to use
  36141. */
  36142. function createViewRef(tNode, lView, isPipe) {
  36143. if (isComponentHost(tNode) && !isPipe) {
  36144. // The LView represents the location where the component is declared.
  36145. // Instead we want the LView for the component View and so we need to look it up.
  36146. const componentView = getComponentLViewByIndex(tNode.index, lView); // look down
  36147. return new ViewRef$1(componentView, componentView);
  36148. }
  36149. else if (tNode.type &
  36150. (3 /* TNodeType.AnyRNode */ | 12 /* TNodeType.AnyContainer */ | 32 /* TNodeType.Icu */ | 128 /* TNodeType.LetDeclaration */)) {
  36151. // The LView represents the location where the injection is requested from.
  36152. // We need to locate the containing LView (in case where the `lView` is an embedded view)
  36153. const hostComponentView = lView[DECLARATION_COMPONENT_VIEW]; // look up
  36154. return new ViewRef$1(hostComponentView, lView);
  36155. }
  36156. return null;
  36157. }
  36158. /**
  36159. * Represents an Angular view.
  36160. *
  36161. * @see {@link /api/core/ChangeDetectorRef?tab=usage-notes Change detection usage}
  36162. *
  36163. * @publicApi
  36164. */
  36165. class ViewRef extends ChangeDetectorRef {
  36166. }
  36167. /**
  36168. * Represents an Angular view in a view container.
  36169. * An embedded view can be referenced from a component
  36170. * other than the hosting component whose template defines it, or it can be defined
  36171. * independently by a `TemplateRef`.
  36172. *
  36173. * Properties of elements in a view can change, but the structure (number and order) of elements in
  36174. * a view cannot. Change the structure of elements by inserting, moving, or
  36175. * removing nested views in a view container.
  36176. *
  36177. * @see {@link ViewContainerRef}
  36178. *
  36179. * @usageNotes
  36180. *
  36181. * The following template breaks down into two separate `TemplateRef` instances,
  36182. * an outer one and an inner one.
  36183. *
  36184. * ```html
  36185. * Count: {{items.length}}
  36186. * <ul>
  36187. * <li *ngFor="let item of items">{{item}}</li>
  36188. * </ul>
  36189. * ```
  36190. *
  36191. * This is the outer `TemplateRef`:
  36192. *
  36193. * ```html
  36194. * Count: {{items.length}}
  36195. * <ul>
  36196. * <ng-template ngFor let-item [ngForOf]="items"></ng-template>
  36197. * </ul>
  36198. * ```
  36199. *
  36200. * This is the inner `TemplateRef`:
  36201. *
  36202. * ```html
  36203. * <li>{{item}}</li>
  36204. * ```
  36205. *
  36206. * The outer and inner `TemplateRef` instances are assembled into views as follows:
  36207. *
  36208. * ```html
  36209. * <!-- ViewRef: outer-0 -->
  36210. * Count: 2
  36211. * <ul>
  36212. * <ng-template view-container-ref></ng-template>
  36213. * <!-- ViewRef: inner-1 --><li>first</li><!-- /ViewRef: inner-1 -->
  36214. * <!-- ViewRef: inner-2 --><li>second</li><!-- /ViewRef: inner-2 -->
  36215. * </ul>
  36216. * <!-- /ViewRef: outer-0 -->
  36217. * ```
  36218. * @publicApi
  36219. */
  36220. class EmbeddedViewRef extends ViewRef {
  36221. }
  36222. /**
  36223. * @publicApi
  36224. */
  36225. class DebugEventListener {
  36226. name;
  36227. callback;
  36228. constructor(name, callback) {
  36229. this.name = name;
  36230. this.callback = callback;
  36231. }
  36232. }
  36233. /**
  36234. * @publicApi
  36235. */
  36236. function asNativeElements(debugEls) {
  36237. return debugEls.map((el) => el.nativeElement);
  36238. }
  36239. /**
  36240. * @publicApi
  36241. */
  36242. class DebugNode {
  36243. /**
  36244. * The underlying DOM node.
  36245. */
  36246. nativeNode;
  36247. constructor(nativeNode) {
  36248. this.nativeNode = nativeNode;
  36249. }
  36250. /**
  36251. * The `DebugElement` parent. Will be `null` if this is the root element.
  36252. */
  36253. get parent() {
  36254. const parent = this.nativeNode.parentNode;
  36255. return parent ? new DebugElement(parent) : null;
  36256. }
  36257. /**
  36258. * The host dependency injector. For example, the root element's component instance injector.
  36259. */
  36260. get injector() {
  36261. return getInjector(this.nativeNode);
  36262. }
  36263. /**
  36264. * The element's own component instance, if it has one.
  36265. */
  36266. get componentInstance() {
  36267. const nativeElement = this.nativeNode;
  36268. return (nativeElement && (getComponent(nativeElement) || getOwningComponent(nativeElement)));
  36269. }
  36270. /**
  36271. * An object that provides parent context for this element. Often an ancestor component instance
  36272. * that governs this element.
  36273. *
  36274. * When an element is repeated within *ngFor, the context is an `NgForOf` whose `$implicit`
  36275. * property is the value of the row instance value. For example, the `hero` in `*ngFor="let hero
  36276. * of heroes"`.
  36277. */
  36278. get context() {
  36279. return getComponent(this.nativeNode) || getContext(this.nativeNode);
  36280. }
  36281. /**
  36282. * The callbacks attached to the component's @Output properties and/or the element's event
  36283. * properties.
  36284. */
  36285. get listeners() {
  36286. return getListeners(this.nativeNode).filter((listener) => listener.type === 'dom');
  36287. }
  36288. /**
  36289. * Dictionary of objects associated with template local variables (e.g. #foo), keyed by the local
  36290. * variable name.
  36291. */
  36292. get references() {
  36293. return getLocalRefs(this.nativeNode);
  36294. }
  36295. /**
  36296. * This component's injector lookup tokens. Includes the component itself plus the tokens that the
  36297. * component lists in its providers metadata.
  36298. */
  36299. get providerTokens() {
  36300. return getInjectionTokens(this.nativeNode);
  36301. }
  36302. }
  36303. /**
  36304. * @publicApi
  36305. *
  36306. * @see [Component testing scenarios](guide/testing/components-scenarios)
  36307. * @see [Basics of testing components](guide/testing/components-basics)
  36308. * @see [Testing utility APIs](guide/testing/utility-apis)
  36309. */
  36310. class DebugElement extends DebugNode {
  36311. constructor(nativeNode) {
  36312. ngDevMode && assertDomNode(nativeNode);
  36313. super(nativeNode);
  36314. }
  36315. /**
  36316. * The underlying DOM element at the root of the component.
  36317. */
  36318. get nativeElement() {
  36319. return this.nativeNode.nodeType == Node.ELEMENT_NODE ? this.nativeNode : null;
  36320. }
  36321. /**
  36322. * The element tag name, if it is an element.
  36323. */
  36324. get name() {
  36325. const context = getLContext(this.nativeNode);
  36326. const lView = context ? context.lView : null;
  36327. if (lView !== null) {
  36328. const tData = lView[TVIEW].data;
  36329. const tNode = tData[context.nodeIndex];
  36330. return tNode.value;
  36331. }
  36332. else {
  36333. return this.nativeNode.nodeName;
  36334. }
  36335. }
  36336. /**
  36337. * Gets a map of property names to property values for an element.
  36338. *
  36339. * This map includes:
  36340. * - Regular property bindings (e.g. `[id]="id"`)
  36341. * - Host property bindings (e.g. `host: { '[id]': "id" }`)
  36342. * - Interpolated property bindings (e.g. `id="{{ value }}")
  36343. *
  36344. * It does not include:
  36345. * - input property bindings (e.g. `[myCustomInput]="value"`)
  36346. * - attribute bindings (e.g. `[attr.role]="menu"`)
  36347. */
  36348. get properties() {
  36349. const context = getLContext(this.nativeNode);
  36350. const lView = context ? context.lView : null;
  36351. if (lView === null) {
  36352. return {};
  36353. }
  36354. const tData = lView[TVIEW].data;
  36355. const tNode = tData[context.nodeIndex];
  36356. const properties = {};
  36357. // Collect properties from the DOM.
  36358. copyDomProperties(this.nativeElement, properties);
  36359. // Collect properties from the bindings. This is needed for animation renderer which has
  36360. // synthetic properties which don't get reflected into the DOM.
  36361. collectPropertyBindings(properties, tNode, lView, tData);
  36362. return properties;
  36363. }
  36364. /**
  36365. * A map of attribute names to attribute values for an element.
  36366. */
  36367. // TODO: replace null by undefined in the return type
  36368. get attributes() {
  36369. const attributes = {};
  36370. const element = this.nativeElement;
  36371. if (!element) {
  36372. return attributes;
  36373. }
  36374. const context = getLContext(element);
  36375. const lView = context ? context.lView : null;
  36376. if (lView === null) {
  36377. return {};
  36378. }
  36379. const tNodeAttrs = lView[TVIEW].data[context.nodeIndex].attrs;
  36380. const lowercaseTNodeAttrs = [];
  36381. // For debug nodes we take the element's attribute directly from the DOM since it allows us
  36382. // to account for ones that weren't set via bindings (e.g. ViewEngine keeps track of the ones
  36383. // that are set through `Renderer2`). The problem is that the browser will lowercase all names,
  36384. // however since we have the attributes already on the TNode, we can preserve the case by going
  36385. // through them once, adding them to the `attributes` map and putting their lower-cased name
  36386. // into an array. Afterwards when we're going through the native DOM attributes, we can check
  36387. // whether we haven't run into an attribute already through the TNode.
  36388. if (tNodeAttrs) {
  36389. let i = 0;
  36390. while (i < tNodeAttrs.length) {
  36391. const attrName = tNodeAttrs[i];
  36392. // Stop as soon as we hit a marker. We only care about the regular attributes. Everything
  36393. // else will be handled below when we read the final attributes off the DOM.
  36394. if (typeof attrName !== 'string')
  36395. break;
  36396. const attrValue = tNodeAttrs[i + 1];
  36397. attributes[attrName] = attrValue;
  36398. lowercaseTNodeAttrs.push(attrName.toLowerCase());
  36399. i += 2;
  36400. }
  36401. }
  36402. for (const attr of element.attributes) {
  36403. // Make sure that we don't assign the same attribute both in its
  36404. // case-sensitive form and the lower-cased one from the browser.
  36405. if (!lowercaseTNodeAttrs.includes(attr.name)) {
  36406. attributes[attr.name] = attr.value;
  36407. }
  36408. }
  36409. return attributes;
  36410. }
  36411. /**
  36412. * The inline styles of the DOM element.
  36413. */
  36414. // TODO: replace null by undefined in the return type
  36415. get styles() {
  36416. const element = this.nativeElement;
  36417. return (element?.style ?? {});
  36418. }
  36419. /**
  36420. * A map containing the class names on the element as keys.
  36421. *
  36422. * This map is derived from the `className` property of the DOM element.
  36423. *
  36424. * Note: The values of this object will always be `true`. The class key will not appear in the KV
  36425. * object if it does not exist on the element.
  36426. *
  36427. * @see [Element.className](https://developer.mozilla.org/en-US/docs/Web/API/Element/className)
  36428. */
  36429. get classes() {
  36430. const result = {};
  36431. const element = this.nativeElement;
  36432. // SVG elements return an `SVGAnimatedString` instead of a plain string for the `className`.
  36433. const className = element.className;
  36434. const classes = typeof className !== 'string' ? className.baseVal.split(' ') : className.split(' ');
  36435. classes.forEach((value) => (result[value] = true));
  36436. return result;
  36437. }
  36438. /**
  36439. * The `childNodes` of the DOM element as a `DebugNode` array.
  36440. *
  36441. * @see [Node.childNodes](https://developer.mozilla.org/en-US/docs/Web/API/Node/childNodes)
  36442. */
  36443. get childNodes() {
  36444. const childNodes = this.nativeNode.childNodes;
  36445. const children = [];
  36446. for (let i = 0; i < childNodes.length; i++) {
  36447. const element = childNodes[i];
  36448. children.push(getDebugNode(element));
  36449. }
  36450. return children;
  36451. }
  36452. /**
  36453. * The immediate `DebugElement` children. Walk the tree by descending through `children`.
  36454. */
  36455. get children() {
  36456. const nativeElement = this.nativeElement;
  36457. if (!nativeElement)
  36458. return [];
  36459. const childNodes = nativeElement.children;
  36460. const children = [];
  36461. for (let i = 0; i < childNodes.length; i++) {
  36462. const element = childNodes[i];
  36463. children.push(getDebugNode(element));
  36464. }
  36465. return children;
  36466. }
  36467. /**
  36468. * @returns the first `DebugElement` that matches the predicate at any depth in the subtree.
  36469. */
  36470. query(predicate) {
  36471. const results = this.queryAll(predicate);
  36472. return results[0] || null;
  36473. }
  36474. /**
  36475. * @returns All `DebugElement` matches for the predicate at any depth in the subtree.
  36476. */
  36477. queryAll(predicate) {
  36478. const matches = [];
  36479. _queryAll(this, predicate, matches, true);
  36480. return matches;
  36481. }
  36482. /**
  36483. * @returns All `DebugNode` matches for the predicate at any depth in the subtree.
  36484. */
  36485. queryAllNodes(predicate) {
  36486. const matches = [];
  36487. _queryAll(this, predicate, matches, false);
  36488. return matches;
  36489. }
  36490. /**
  36491. * Triggers the event by its name if there is a corresponding listener in the element's
  36492. * `listeners` collection.
  36493. *
  36494. * If the event lacks a listener or there's some other problem, consider
  36495. * calling `nativeElement.dispatchEvent(eventObject)`.
  36496. *
  36497. * @param eventName The name of the event to trigger
  36498. * @param eventObj The _event object_ expected by the handler
  36499. *
  36500. * @see [Testing components scenarios](guide/testing/components-scenarios#trigger-event-handler)
  36501. */
  36502. triggerEventHandler(eventName, eventObj) {
  36503. const node = this.nativeNode;
  36504. const invokedListeners = [];
  36505. this.listeners.forEach((listener) => {
  36506. if (listener.name === eventName) {
  36507. const callback = listener.callback;
  36508. callback.call(node, eventObj);
  36509. invokedListeners.push(callback);
  36510. }
  36511. });
  36512. // We need to check whether `eventListeners` exists, because it's something
  36513. // that Zone.js only adds to `EventTarget` in browser environments.
  36514. if (typeof node.eventListeners === 'function') {
  36515. // Note that in Ivy we wrap event listeners with a call to `event.preventDefault` in some
  36516. // cases. We use '__ngUnwrap__' as a special token that gives us access to the actual event
  36517. // listener.
  36518. node.eventListeners(eventName).forEach((listener) => {
  36519. // In order to ensure that we can detect the special __ngUnwrap__ token described above, we
  36520. // use `toString` on the listener and see if it contains the token. We use this approach to
  36521. // ensure that it still worked with compiled code since it cannot remove or rename string
  36522. // literals. We also considered using a special function name (i.e. if(listener.name ===
  36523. // special)) but that was more cumbersome and we were also concerned the compiled code could
  36524. // strip the name, turning the condition in to ("" === "") and always returning true.
  36525. if (listener.toString().indexOf('__ngUnwrap__') !== -1) {
  36526. const unwrappedListener = listener('__ngUnwrap__');
  36527. return (invokedListeners.indexOf(unwrappedListener) === -1 &&
  36528. unwrappedListener.call(node, eventObj));
  36529. }
  36530. });
  36531. }
  36532. }
  36533. }
  36534. function copyDomProperties(element, properties) {
  36535. if (element) {
  36536. // Skip own properties (as those are patched)
  36537. let obj = Object.getPrototypeOf(element);
  36538. const NodePrototype = Node.prototype;
  36539. while (obj !== null && obj !== NodePrototype) {
  36540. const descriptors = Object.getOwnPropertyDescriptors(obj);
  36541. for (let key in descriptors) {
  36542. if (!key.startsWith('__') && !key.startsWith('on')) {
  36543. // don't include properties starting with `__` and `on`.
  36544. // `__` are patched values which should not be included.
  36545. // `on` are listeners which also should not be included.
  36546. const value = element[key];
  36547. if (isPrimitiveValue(value)) {
  36548. properties[key] = value;
  36549. }
  36550. }
  36551. }
  36552. obj = Object.getPrototypeOf(obj);
  36553. }
  36554. }
  36555. }
  36556. function isPrimitiveValue(value) {
  36557. return (typeof value === 'string' ||
  36558. typeof value === 'boolean' ||
  36559. typeof value === 'number' ||
  36560. value === null);
  36561. }
  36562. function _queryAll(parentElement, predicate, matches, elementsOnly) {
  36563. const context = getLContext(parentElement.nativeNode);
  36564. const lView = context ? context.lView : null;
  36565. if (lView !== null) {
  36566. const parentTNode = lView[TVIEW].data[context.nodeIndex];
  36567. _queryNodeChildren(parentTNode, lView, predicate, matches, elementsOnly, parentElement.nativeNode);
  36568. }
  36569. else {
  36570. // If the context is null, then `parentElement` was either created with Renderer2 or native DOM
  36571. // APIs.
  36572. _queryNativeNodeDescendants(parentElement.nativeNode, predicate, matches, elementsOnly);
  36573. }
  36574. }
  36575. /**
  36576. * Recursively match the current TNode against the predicate, and goes on with the next ones.
  36577. *
  36578. * @param tNode the current TNode
  36579. * @param lView the LView of this TNode
  36580. * @param predicate the predicate to match
  36581. * @param matches the list of positive matches
  36582. * @param elementsOnly whether only elements should be searched
  36583. * @param rootNativeNode the root native node on which predicate should not be matched
  36584. */
  36585. function _queryNodeChildren(tNode, lView, predicate, matches, elementsOnly, rootNativeNode) {
  36586. ngDevMode && assertTNodeForLView(tNode, lView);
  36587. const nativeNode = getNativeByTNodeOrNull(tNode, lView);
  36588. // For each type of TNode, specific logic is executed.
  36589. if (tNode.type & (3 /* TNodeType.AnyRNode */ | 8 /* TNodeType.ElementContainer */)) {
  36590. // Case 1: the TNode is an element
  36591. // The native node has to be checked.
  36592. _addQueryMatch(nativeNode, predicate, matches, elementsOnly, rootNativeNode);
  36593. if (isComponentHost(tNode)) {
  36594. // If the element is the host of a component, then all nodes in its view have to be processed.
  36595. // Note: the component's content (tNode.child) will be processed from the insertion points.
  36596. const componentView = getComponentLViewByIndex(tNode.index, lView);
  36597. if (componentView && componentView[TVIEW].firstChild) {
  36598. _queryNodeChildren(componentView[TVIEW].firstChild, componentView, predicate, matches, elementsOnly, rootNativeNode);
  36599. }
  36600. }
  36601. else {
  36602. if (tNode.child) {
  36603. // Otherwise, its children have to be processed.
  36604. _queryNodeChildren(tNode.child, lView, predicate, matches, elementsOnly, rootNativeNode);
  36605. }
  36606. // We also have to query the DOM directly in order to catch elements inserted through
  36607. // Renderer2. Note that this is __not__ optimal, because we're walking similar trees multiple
  36608. // times. ViewEngine could do it more efficiently, because all the insertions go through
  36609. // Renderer2, however that's not the case in Ivy. This approach is being used because:
  36610. // 1. Matching the ViewEngine behavior would mean potentially introducing a dependency
  36611. // from `Renderer2` to Ivy which could bring Ivy code into ViewEngine.
  36612. // 2. It allows us to capture nodes that were inserted directly via the DOM.
  36613. nativeNode && _queryNativeNodeDescendants(nativeNode, predicate, matches, elementsOnly);
  36614. }
  36615. // In all cases, if a dynamic container exists for this node, each view inside it has to be
  36616. // processed.
  36617. const nodeOrContainer = lView[tNode.index];
  36618. if (isLContainer(nodeOrContainer)) {
  36619. _queryNodeChildrenInContainer(nodeOrContainer, predicate, matches, elementsOnly, rootNativeNode);
  36620. }
  36621. }
  36622. else if (tNode.type & 4 /* TNodeType.Container */) {
  36623. // Case 2: the TNode is a container
  36624. // The native node has to be checked.
  36625. const lContainer = lView[tNode.index];
  36626. _addQueryMatch(lContainer[NATIVE], predicate, matches, elementsOnly, rootNativeNode);
  36627. // Each view inside the container has to be processed.
  36628. _queryNodeChildrenInContainer(lContainer, predicate, matches, elementsOnly, rootNativeNode);
  36629. }
  36630. else if (tNode.type & 16 /* TNodeType.Projection */) {
  36631. // Case 3: the TNode is a projection insertion point (i.e. a <ng-content>).
  36632. // The nodes projected at this location all need to be processed.
  36633. const componentView = lView[DECLARATION_COMPONENT_VIEW];
  36634. const componentHost = componentView[T_HOST];
  36635. const head = componentHost.projection[tNode.projection];
  36636. if (Array.isArray(head)) {
  36637. for (let nativeNode of head) {
  36638. _addQueryMatch(nativeNode, predicate, matches, elementsOnly, rootNativeNode);
  36639. }
  36640. }
  36641. else if (head) {
  36642. const nextLView = componentView[PARENT];
  36643. const nextTNode = nextLView[TVIEW].data[head.index];
  36644. _queryNodeChildren(nextTNode, nextLView, predicate, matches, elementsOnly, rootNativeNode);
  36645. }
  36646. }
  36647. else if (tNode.child) {
  36648. // Case 4: the TNode is a view.
  36649. _queryNodeChildren(tNode.child, lView, predicate, matches, elementsOnly, rootNativeNode);
  36650. }
  36651. // We don't want to go to the next sibling of the root node.
  36652. if (rootNativeNode !== nativeNode) {
  36653. // To determine the next node to be processed, we need to use the next or the projectionNext
  36654. // link, depending on whether the current node has been projected.
  36655. const nextTNode = tNode.flags & 2 /* TNodeFlags.isProjected */ ? tNode.projectionNext : tNode.next;
  36656. if (nextTNode) {
  36657. _queryNodeChildren(nextTNode, lView, predicate, matches, elementsOnly, rootNativeNode);
  36658. }
  36659. }
  36660. }
  36661. /**
  36662. * Process all TNodes in a given container.
  36663. *
  36664. * @param lContainer the container to be processed
  36665. * @param predicate the predicate to match
  36666. * @param matches the list of positive matches
  36667. * @param elementsOnly whether only elements should be searched
  36668. * @param rootNativeNode the root native node on which predicate should not be matched
  36669. */
  36670. function _queryNodeChildrenInContainer(lContainer, predicate, matches, elementsOnly, rootNativeNode) {
  36671. for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
  36672. const childView = lContainer[i];
  36673. const firstChild = childView[TVIEW].firstChild;
  36674. if (firstChild) {
  36675. _queryNodeChildren(firstChild, childView, predicate, matches, elementsOnly, rootNativeNode);
  36676. }
  36677. }
  36678. }
  36679. /**
  36680. * Match the current native node against the predicate.
  36681. *
  36682. * @param nativeNode the current native node
  36683. * @param predicate the predicate to match
  36684. * @param matches the list of positive matches
  36685. * @param elementsOnly whether only elements should be searched
  36686. * @param rootNativeNode the root native node on which predicate should not be matched
  36687. */
  36688. function _addQueryMatch(nativeNode, predicate, matches, elementsOnly, rootNativeNode) {
  36689. if (rootNativeNode !== nativeNode) {
  36690. const debugNode = getDebugNode(nativeNode);
  36691. if (!debugNode) {
  36692. return;
  36693. }
  36694. // Type of the "predicate and "matches" array are set based on the value of
  36695. // the "elementsOnly" parameter. TypeScript is not able to properly infer these
  36696. // types with generics, so we manually cast the parameters accordingly.
  36697. if (elementsOnly &&
  36698. debugNode instanceof DebugElement &&
  36699. predicate(debugNode) &&
  36700. matches.indexOf(debugNode) === -1) {
  36701. matches.push(debugNode);
  36702. }
  36703. else if (!elementsOnly &&
  36704. predicate(debugNode) &&
  36705. matches.indexOf(debugNode) === -1) {
  36706. matches.push(debugNode);
  36707. }
  36708. }
  36709. }
  36710. /**
  36711. * Match all the descendants of a DOM node against a predicate.
  36712. *
  36713. * @param nativeNode the current native node
  36714. * @param predicate the predicate to match
  36715. * @param matches the list where matches are stored
  36716. * @param elementsOnly whether only elements should be searched
  36717. */
  36718. function _queryNativeNodeDescendants(parentNode, predicate, matches, elementsOnly) {
  36719. const nodes = parentNode.childNodes;
  36720. const length = nodes.length;
  36721. for (let i = 0; i < length; i++) {
  36722. const node = nodes[i];
  36723. const debugNode = getDebugNode(node);
  36724. if (debugNode) {
  36725. if (elementsOnly &&
  36726. debugNode instanceof DebugElement &&
  36727. predicate(debugNode) &&
  36728. matches.indexOf(debugNode) === -1) {
  36729. matches.push(debugNode);
  36730. }
  36731. else if (!elementsOnly &&
  36732. predicate(debugNode) &&
  36733. matches.indexOf(debugNode) === -1) {
  36734. matches.push(debugNode);
  36735. }
  36736. _queryNativeNodeDescendants(node, predicate, matches, elementsOnly);
  36737. }
  36738. }
  36739. }
  36740. /**
  36741. * Iterates through the property bindings for a given node and generates
  36742. * a map of property names to values. This map only contains property bindings
  36743. * defined in templates, not in host bindings.
  36744. */
  36745. function collectPropertyBindings(properties, tNode, lView, tData) {
  36746. let bindingIndexes = tNode.propertyBindings;
  36747. if (bindingIndexes !== null) {
  36748. for (let i = 0; i < bindingIndexes.length; i++) {
  36749. const bindingIndex = bindingIndexes[i];
  36750. const propMetadata = tData[bindingIndex];
  36751. const metadataParts = propMetadata.split(INTERPOLATION_DELIMITER);
  36752. const propertyName = metadataParts[0];
  36753. if (metadataParts.length > 1) {
  36754. let value = metadataParts[1];
  36755. for (let j = 1; j < metadataParts.length - 1; j++) {
  36756. value += renderStringify(lView[bindingIndex + j - 1]) + metadataParts[j + 1];
  36757. }
  36758. properties[propertyName] = value;
  36759. }
  36760. else {
  36761. properties[propertyName] = lView[bindingIndex];
  36762. }
  36763. }
  36764. }
  36765. }
  36766. const NG_DEBUG_PROPERTY = '__ng_debug__';
  36767. /**
  36768. * @publicApi
  36769. */
  36770. function getDebugNode(nativeNode) {
  36771. if (nativeNode instanceof Node) {
  36772. if (!nativeNode.hasOwnProperty(NG_DEBUG_PROPERTY)) {
  36773. nativeNode[NG_DEBUG_PROPERTY] =
  36774. nativeNode.nodeType == Node.ELEMENT_NODE
  36775. ? new DebugElement(nativeNode)
  36776. : new DebugNode(nativeNode);
  36777. }
  36778. return nativeNode[NG_DEBUG_PROPERTY];
  36779. }
  36780. return null;
  36781. }
  36782. class DefaultIterableDifferFactory {
  36783. constructor() { }
  36784. supports(obj) {
  36785. return isListLikeIterable(obj);
  36786. }
  36787. create(trackByFn) {
  36788. return new DefaultIterableDiffer(trackByFn);
  36789. }
  36790. }
  36791. const trackByIdentity = (index, item) => item;
  36792. /**
  36793. * @deprecated v4.0.0 - Should not be part of public API.
  36794. * @publicApi
  36795. */
  36796. class DefaultIterableDiffer {
  36797. length = 0;
  36798. // TODO: confirm the usage of `collection` as it's unused, readonly and on a non public API.
  36799. collection;
  36800. // Keeps track of the used records at any point in time (during & across `_check()` calls)
  36801. _linkedRecords = null;
  36802. // Keeps track of the removed records at any point in time during `_check()` calls.
  36803. _unlinkedRecords = null;
  36804. _previousItHead = null;
  36805. _itHead = null;
  36806. _itTail = null;
  36807. _additionsHead = null;
  36808. _additionsTail = null;
  36809. _movesHead = null;
  36810. _movesTail = null;
  36811. _removalsHead = null;
  36812. _removalsTail = null;
  36813. // Keeps track of records where custom track by is the same, but item identity has changed
  36814. _identityChangesHead = null;
  36815. _identityChangesTail = null;
  36816. _trackByFn;
  36817. constructor(trackByFn) {
  36818. this._trackByFn = trackByFn || trackByIdentity;
  36819. }
  36820. forEachItem(fn) {
  36821. let record;
  36822. for (record = this._itHead; record !== null; record = record._next) {
  36823. fn(record);
  36824. }
  36825. }
  36826. forEachOperation(fn) {
  36827. let nextIt = this._itHead;
  36828. let nextRemove = this._removalsHead;
  36829. let addRemoveOffset = 0;
  36830. let moveOffsets = null;
  36831. while (nextIt || nextRemove) {
  36832. // Figure out which is the next record to process
  36833. // Order: remove, add, move
  36834. const record = !nextRemove ||
  36835. (nextIt &&
  36836. nextIt.currentIndex < getPreviousIndex(nextRemove, addRemoveOffset, moveOffsets))
  36837. ? nextIt
  36838. : nextRemove;
  36839. const adjPreviousIndex = getPreviousIndex(record, addRemoveOffset, moveOffsets);
  36840. const currentIndex = record.currentIndex;
  36841. // consume the item, and adjust the addRemoveOffset and update moveDistance if necessary
  36842. if (record === nextRemove) {
  36843. addRemoveOffset--;
  36844. nextRemove = nextRemove._nextRemoved;
  36845. }
  36846. else {
  36847. nextIt = nextIt._next;
  36848. if (record.previousIndex == null) {
  36849. addRemoveOffset++;
  36850. }
  36851. else {
  36852. // INVARIANT: currentIndex < previousIndex
  36853. if (!moveOffsets)
  36854. moveOffsets = [];
  36855. const localMovePreviousIndex = adjPreviousIndex - addRemoveOffset;
  36856. const localCurrentIndex = currentIndex - addRemoveOffset;
  36857. if (localMovePreviousIndex != localCurrentIndex) {
  36858. for (let i = 0; i < localMovePreviousIndex; i++) {
  36859. const offset = i < moveOffsets.length ? moveOffsets[i] : (moveOffsets[i] = 0);
  36860. const index = offset + i;
  36861. if (localCurrentIndex <= index && index < localMovePreviousIndex) {
  36862. moveOffsets[i] = offset + 1;
  36863. }
  36864. }
  36865. const previousIndex = record.previousIndex;
  36866. moveOffsets[previousIndex] = localCurrentIndex - localMovePreviousIndex;
  36867. }
  36868. }
  36869. }
  36870. if (adjPreviousIndex !== currentIndex) {
  36871. fn(record, adjPreviousIndex, currentIndex);
  36872. }
  36873. }
  36874. }
  36875. forEachPreviousItem(fn) {
  36876. let record;
  36877. for (record = this._previousItHead; record !== null; record = record._nextPrevious) {
  36878. fn(record);
  36879. }
  36880. }
  36881. forEachAddedItem(fn) {
  36882. let record;
  36883. for (record = this._additionsHead; record !== null; record = record._nextAdded) {
  36884. fn(record);
  36885. }
  36886. }
  36887. forEachMovedItem(fn) {
  36888. let record;
  36889. for (record = this._movesHead; record !== null; record = record._nextMoved) {
  36890. fn(record);
  36891. }
  36892. }
  36893. forEachRemovedItem(fn) {
  36894. let record;
  36895. for (record = this._removalsHead; record !== null; record = record._nextRemoved) {
  36896. fn(record);
  36897. }
  36898. }
  36899. forEachIdentityChange(fn) {
  36900. let record;
  36901. for (record = this._identityChangesHead; record !== null; record = record._nextIdentityChange) {
  36902. fn(record);
  36903. }
  36904. }
  36905. diff(collection) {
  36906. if (collection == null)
  36907. collection = [];
  36908. if (!isListLikeIterable(collection)) {
  36909. throw new RuntimeError(900 /* RuntimeErrorCode.INVALID_DIFFER_INPUT */, ngDevMode &&
  36910. `Error trying to diff '${stringify(collection)}'. Only arrays and iterables are allowed`);
  36911. }
  36912. if (this.check(collection)) {
  36913. return this;
  36914. }
  36915. else {
  36916. return null;
  36917. }
  36918. }
  36919. onDestroy() { }
  36920. check(collection) {
  36921. this._reset();
  36922. let record = this._itHead;
  36923. let mayBeDirty = false;
  36924. let index;
  36925. let item;
  36926. let itemTrackBy;
  36927. if (Array.isArray(collection)) {
  36928. this.length = collection.length;
  36929. for (let index = 0; index < this.length; index++) {
  36930. item = collection[index];
  36931. itemTrackBy = this._trackByFn(index, item);
  36932. if (record === null || !Object.is(record.trackById, itemTrackBy)) {
  36933. record = this._mismatch(record, item, itemTrackBy, index);
  36934. mayBeDirty = true;
  36935. }
  36936. else {
  36937. if (mayBeDirty) {
  36938. // TODO(misko): can we limit this to duplicates only?
  36939. record = this._verifyReinsertion(record, item, itemTrackBy, index);
  36940. }
  36941. if (!Object.is(record.item, item))
  36942. this._addIdentityChange(record, item);
  36943. }
  36944. record = record._next;
  36945. }
  36946. }
  36947. else {
  36948. index = 0;
  36949. iterateListLike(collection, (item) => {
  36950. itemTrackBy = this._trackByFn(index, item);
  36951. if (record === null || !Object.is(record.trackById, itemTrackBy)) {
  36952. record = this._mismatch(record, item, itemTrackBy, index);
  36953. mayBeDirty = true;
  36954. }
  36955. else {
  36956. if (mayBeDirty) {
  36957. // TODO(misko): can we limit this to duplicates only?
  36958. record = this._verifyReinsertion(record, item, itemTrackBy, index);
  36959. }
  36960. if (!Object.is(record.item, item))
  36961. this._addIdentityChange(record, item);
  36962. }
  36963. record = record._next;
  36964. index++;
  36965. });
  36966. this.length = index;
  36967. }
  36968. this._truncate(record);
  36969. this.collection = collection;
  36970. return this.isDirty;
  36971. }
  36972. /* CollectionChanges is considered dirty if it has any additions, moves, removals, or identity
  36973. * changes.
  36974. */
  36975. get isDirty() {
  36976. return (this._additionsHead !== null ||
  36977. this._movesHead !== null ||
  36978. this._removalsHead !== null ||
  36979. this._identityChangesHead !== null);
  36980. }
  36981. /**
  36982. * Reset the state of the change objects to show no changes. This means set previousKey to
  36983. * currentKey, and clear all of the queues (additions, moves, removals).
  36984. * Set the previousIndexes of moved and added items to their currentIndexes
  36985. * Reset the list of additions, moves and removals
  36986. *
  36987. * @internal
  36988. */
  36989. _reset() {
  36990. if (this.isDirty) {
  36991. let record;
  36992. for (record = this._previousItHead = this._itHead; record !== null; record = record._next) {
  36993. record._nextPrevious = record._next;
  36994. }
  36995. for (record = this._additionsHead; record !== null; record = record._nextAdded) {
  36996. record.previousIndex = record.currentIndex;
  36997. }
  36998. this._additionsHead = this._additionsTail = null;
  36999. for (record = this._movesHead; record !== null; record = record._nextMoved) {
  37000. record.previousIndex = record.currentIndex;
  37001. }
  37002. this._movesHead = this._movesTail = null;
  37003. this._removalsHead = this._removalsTail = null;
  37004. this._identityChangesHead = this._identityChangesTail = null;
  37005. // TODO(vicb): when assert gets supported
  37006. // assert(!this.isDirty);
  37007. }
  37008. }
  37009. /**
  37010. * This is the core function which handles differences between collections.
  37011. *
  37012. * - `record` is the record which we saw at this position last time. If null then it is a new
  37013. * item.
  37014. * - `item` is the current item in the collection
  37015. * - `index` is the position of the item in the collection
  37016. *
  37017. * @internal
  37018. */
  37019. _mismatch(record, item, itemTrackBy, index) {
  37020. // The previous record after which we will append the current one.
  37021. let previousRecord;
  37022. if (record === null) {
  37023. previousRecord = this._itTail;
  37024. }
  37025. else {
  37026. previousRecord = record._prev;
  37027. // Remove the record from the collection since we know it does not match the item.
  37028. this._remove(record);
  37029. }
  37030. // See if we have evicted the item, which used to be at some anterior position of _itHead list.
  37031. record = this._unlinkedRecords === null ? null : this._unlinkedRecords.get(itemTrackBy, null);
  37032. if (record !== null) {
  37033. // It is an item which we have evicted earlier: reinsert it back into the list.
  37034. // But first we need to check if identity changed, so we can update in view if necessary.
  37035. if (!Object.is(record.item, item))
  37036. this._addIdentityChange(record, item);
  37037. this._reinsertAfter(record, previousRecord, index);
  37038. }
  37039. else {
  37040. // Attempt to see if the item is at some posterior position of _itHead list.
  37041. record = this._linkedRecords === null ? null : this._linkedRecords.get(itemTrackBy, index);
  37042. if (record !== null) {
  37043. // We have the item in _itHead at/after `index` position. We need to move it forward in the
  37044. // collection.
  37045. // But first we need to check if identity changed, so we can update in view if necessary.
  37046. if (!Object.is(record.item, item))
  37047. this._addIdentityChange(record, item);
  37048. this._moveAfter(record, previousRecord, index);
  37049. }
  37050. else {
  37051. // It is a new item: add it.
  37052. record = this._addAfter(new IterableChangeRecord_(item, itemTrackBy), previousRecord, index);
  37053. }
  37054. }
  37055. return record;
  37056. }
  37057. /**
  37058. * This check is only needed if an array contains duplicates. (Short circuit of nothing dirty)
  37059. *
  37060. * Use case: `[a, a]` => `[b, a, a]`
  37061. *
  37062. * If we did not have this check then the insertion of `b` would:
  37063. * 1) evict first `a`
  37064. * 2) insert `b` at `0` index.
  37065. * 3) leave `a` at index `1` as is. <-- this is wrong!
  37066. * 3) reinsert `a` at index 2. <-- this is wrong!
  37067. *
  37068. * The correct behavior is:
  37069. * 1) evict first `a`
  37070. * 2) insert `b` at `0` index.
  37071. * 3) reinsert `a` at index 1.
  37072. * 3) move `a` at from `1` to `2`.
  37073. *
  37074. *
  37075. * Double check that we have not evicted a duplicate item. We need to check if the item type may
  37076. * have already been removed:
  37077. * The insertion of b will evict the first 'a'. If we don't reinsert it now it will be reinserted
  37078. * at the end. Which will show up as the two 'a's switching position. This is incorrect, since a
  37079. * better way to think of it is as insert of 'b' rather then switch 'a' with 'b' and then add 'a'
  37080. * at the end.
  37081. *
  37082. * @internal
  37083. */
  37084. _verifyReinsertion(record, item, itemTrackBy, index) {
  37085. let reinsertRecord = this._unlinkedRecords === null ? null : this._unlinkedRecords.get(itemTrackBy, null);
  37086. if (reinsertRecord !== null) {
  37087. record = this._reinsertAfter(reinsertRecord, record._prev, index);
  37088. }
  37089. else if (record.currentIndex != index) {
  37090. record.currentIndex = index;
  37091. this._addToMoves(record, index);
  37092. }
  37093. return record;
  37094. }
  37095. /**
  37096. * Get rid of any excess {@link IterableChangeRecord_}s from the previous collection
  37097. *
  37098. * - `record` The first excess {@link IterableChangeRecord_}.
  37099. *
  37100. * @internal
  37101. */
  37102. _truncate(record) {
  37103. // Anything after that needs to be removed;
  37104. while (record !== null) {
  37105. const nextRecord = record._next;
  37106. this._addToRemovals(this._unlink(record));
  37107. record = nextRecord;
  37108. }
  37109. if (this._unlinkedRecords !== null) {
  37110. this._unlinkedRecords.clear();
  37111. }
  37112. if (this._additionsTail !== null) {
  37113. this._additionsTail._nextAdded = null;
  37114. }
  37115. if (this._movesTail !== null) {
  37116. this._movesTail._nextMoved = null;
  37117. }
  37118. if (this._itTail !== null) {
  37119. this._itTail._next = null;
  37120. }
  37121. if (this._removalsTail !== null) {
  37122. this._removalsTail._nextRemoved = null;
  37123. }
  37124. if (this._identityChangesTail !== null) {
  37125. this._identityChangesTail._nextIdentityChange = null;
  37126. }
  37127. }
  37128. /** @internal */
  37129. _reinsertAfter(record, prevRecord, index) {
  37130. if (this._unlinkedRecords !== null) {
  37131. this._unlinkedRecords.remove(record);
  37132. }
  37133. const prev = record._prevRemoved;
  37134. const next = record._nextRemoved;
  37135. if (prev === null) {
  37136. this._removalsHead = next;
  37137. }
  37138. else {
  37139. prev._nextRemoved = next;
  37140. }
  37141. if (next === null) {
  37142. this._removalsTail = prev;
  37143. }
  37144. else {
  37145. next._prevRemoved = prev;
  37146. }
  37147. this._insertAfter(record, prevRecord, index);
  37148. this._addToMoves(record, index);
  37149. return record;
  37150. }
  37151. /** @internal */
  37152. _moveAfter(record, prevRecord, index) {
  37153. this._unlink(record);
  37154. this._insertAfter(record, prevRecord, index);
  37155. this._addToMoves(record, index);
  37156. return record;
  37157. }
  37158. /** @internal */
  37159. _addAfter(record, prevRecord, index) {
  37160. this._insertAfter(record, prevRecord, index);
  37161. if (this._additionsTail === null) {
  37162. // TODO(vicb):
  37163. // assert(this._additionsHead === null);
  37164. this._additionsTail = this._additionsHead = record;
  37165. }
  37166. else {
  37167. // TODO(vicb):
  37168. // assert(_additionsTail._nextAdded === null);
  37169. // assert(record._nextAdded === null);
  37170. this._additionsTail = this._additionsTail._nextAdded = record;
  37171. }
  37172. return record;
  37173. }
  37174. /** @internal */
  37175. _insertAfter(record, prevRecord, index) {
  37176. // TODO(vicb):
  37177. // assert(record != prevRecord);
  37178. // assert(record._next === null);
  37179. // assert(record._prev === null);
  37180. const next = prevRecord === null ? this._itHead : prevRecord._next;
  37181. // TODO(vicb):
  37182. // assert(next != record);
  37183. // assert(prevRecord != record);
  37184. record._next = next;
  37185. record._prev = prevRecord;
  37186. if (next === null) {
  37187. this._itTail = record;
  37188. }
  37189. else {
  37190. next._prev = record;
  37191. }
  37192. if (prevRecord === null) {
  37193. this._itHead = record;
  37194. }
  37195. else {
  37196. prevRecord._next = record;
  37197. }
  37198. if (this._linkedRecords === null) {
  37199. this._linkedRecords = new _DuplicateMap();
  37200. }
  37201. this._linkedRecords.put(record);
  37202. record.currentIndex = index;
  37203. return record;
  37204. }
  37205. /** @internal */
  37206. _remove(record) {
  37207. return this._addToRemovals(this._unlink(record));
  37208. }
  37209. /** @internal */
  37210. _unlink(record) {
  37211. if (this._linkedRecords !== null) {
  37212. this._linkedRecords.remove(record);
  37213. }
  37214. const prev = record._prev;
  37215. const next = record._next;
  37216. // TODO(vicb):
  37217. // assert((record._prev = null) === null);
  37218. // assert((record._next = null) === null);
  37219. if (prev === null) {
  37220. this._itHead = next;
  37221. }
  37222. else {
  37223. prev._next = next;
  37224. }
  37225. if (next === null) {
  37226. this._itTail = prev;
  37227. }
  37228. else {
  37229. next._prev = prev;
  37230. }
  37231. return record;
  37232. }
  37233. /** @internal */
  37234. _addToMoves(record, toIndex) {
  37235. // TODO(vicb):
  37236. // assert(record._nextMoved === null);
  37237. if (record.previousIndex === toIndex) {
  37238. return record;
  37239. }
  37240. if (this._movesTail === null) {
  37241. // TODO(vicb):
  37242. // assert(_movesHead === null);
  37243. this._movesTail = this._movesHead = record;
  37244. }
  37245. else {
  37246. // TODO(vicb):
  37247. // assert(_movesTail._nextMoved === null);
  37248. this._movesTail = this._movesTail._nextMoved = record;
  37249. }
  37250. return record;
  37251. }
  37252. _addToRemovals(record) {
  37253. if (this._unlinkedRecords === null) {
  37254. this._unlinkedRecords = new _DuplicateMap();
  37255. }
  37256. this._unlinkedRecords.put(record);
  37257. record.currentIndex = null;
  37258. record._nextRemoved = null;
  37259. if (this._removalsTail === null) {
  37260. // TODO(vicb):
  37261. // assert(_removalsHead === null);
  37262. this._removalsTail = this._removalsHead = record;
  37263. record._prevRemoved = null;
  37264. }
  37265. else {
  37266. // TODO(vicb):
  37267. // assert(_removalsTail._nextRemoved === null);
  37268. // assert(record._nextRemoved === null);
  37269. record._prevRemoved = this._removalsTail;
  37270. this._removalsTail = this._removalsTail._nextRemoved = record;
  37271. }
  37272. return record;
  37273. }
  37274. /** @internal */
  37275. _addIdentityChange(record, item) {
  37276. record.item = item;
  37277. if (this._identityChangesTail === null) {
  37278. this._identityChangesTail = this._identityChangesHead = record;
  37279. }
  37280. else {
  37281. this._identityChangesTail = this._identityChangesTail._nextIdentityChange = record;
  37282. }
  37283. return record;
  37284. }
  37285. }
  37286. class IterableChangeRecord_ {
  37287. item;
  37288. trackById;
  37289. currentIndex = null;
  37290. previousIndex = null;
  37291. /** @internal */
  37292. _nextPrevious = null;
  37293. /** @internal */
  37294. _prev = null;
  37295. /** @internal */
  37296. _next = null;
  37297. /** @internal */
  37298. _prevDup = null;
  37299. /** @internal */
  37300. _nextDup = null;
  37301. /** @internal */
  37302. _prevRemoved = null;
  37303. /** @internal */
  37304. _nextRemoved = null;
  37305. /** @internal */
  37306. _nextAdded = null;
  37307. /** @internal */
  37308. _nextMoved = null;
  37309. /** @internal */
  37310. _nextIdentityChange = null;
  37311. constructor(item, trackById) {
  37312. this.item = item;
  37313. this.trackById = trackById;
  37314. }
  37315. }
  37316. // A linked list of IterableChangeRecords with the same IterableChangeRecord_.item
  37317. class _DuplicateItemRecordList {
  37318. /** @internal */
  37319. _head = null;
  37320. /** @internal */
  37321. _tail = null;
  37322. /**
  37323. * Append the record to the list of duplicates.
  37324. *
  37325. * Note: by design all records in the list of duplicates hold the same value in record.item.
  37326. */
  37327. add(record) {
  37328. if (this._head === null) {
  37329. this._head = this._tail = record;
  37330. record._nextDup = null;
  37331. record._prevDup = null;
  37332. }
  37333. else {
  37334. // TODO(vicb):
  37335. // assert(record.item == _head.item ||
  37336. // record.item is num && record.item.isNaN && _head.item is num && _head.item.isNaN);
  37337. this._tail._nextDup = record;
  37338. record._prevDup = this._tail;
  37339. record._nextDup = null;
  37340. this._tail = record;
  37341. }
  37342. }
  37343. // Returns a IterableChangeRecord_ having IterableChangeRecord_.trackById == trackById and
  37344. // IterableChangeRecord_.currentIndex >= atOrAfterIndex
  37345. get(trackById, atOrAfterIndex) {
  37346. let record;
  37347. for (record = this._head; record !== null; record = record._nextDup) {
  37348. if ((atOrAfterIndex === null || atOrAfterIndex <= record.currentIndex) &&
  37349. Object.is(record.trackById, trackById)) {
  37350. return record;
  37351. }
  37352. }
  37353. return null;
  37354. }
  37355. /**
  37356. * Remove one {@link IterableChangeRecord_} from the list of duplicates.
  37357. *
  37358. * Returns whether the list of duplicates is empty.
  37359. */
  37360. remove(record) {
  37361. // TODO(vicb):
  37362. // assert(() {
  37363. // // verify that the record being removed is in the list.
  37364. // for (IterableChangeRecord_ cursor = _head; cursor != null; cursor = cursor._nextDup) {
  37365. // if (identical(cursor, record)) return true;
  37366. // }
  37367. // return false;
  37368. //});
  37369. const prev = record._prevDup;
  37370. const next = record._nextDup;
  37371. if (prev === null) {
  37372. this._head = next;
  37373. }
  37374. else {
  37375. prev._nextDup = next;
  37376. }
  37377. if (next === null) {
  37378. this._tail = prev;
  37379. }
  37380. else {
  37381. next._prevDup = prev;
  37382. }
  37383. return this._head === null;
  37384. }
  37385. }
  37386. class _DuplicateMap {
  37387. map = new Map();
  37388. put(record) {
  37389. const key = record.trackById;
  37390. let duplicates = this.map.get(key);
  37391. if (!duplicates) {
  37392. duplicates = new _DuplicateItemRecordList();
  37393. this.map.set(key, duplicates);
  37394. }
  37395. duplicates.add(record);
  37396. }
  37397. /**
  37398. * Retrieve the `value` using key. Because the IterableChangeRecord_ value may be one which we
  37399. * have already iterated over, we use the `atOrAfterIndex` to pretend it is not there.
  37400. *
  37401. * Use case: `[a, b, c, a, a]` if we are at index `3` which is the second `a` then asking if we
  37402. * have any more `a`s needs to return the second `a`.
  37403. */
  37404. get(trackById, atOrAfterIndex) {
  37405. const key = trackById;
  37406. const recordList = this.map.get(key);
  37407. return recordList ? recordList.get(trackById, atOrAfterIndex) : null;
  37408. }
  37409. /**
  37410. * Removes a {@link IterableChangeRecord_} from the list of duplicates.
  37411. *
  37412. * The list of duplicates also is removed from the map if it gets empty.
  37413. */
  37414. remove(record) {
  37415. const key = record.trackById;
  37416. const recordList = this.map.get(key);
  37417. // Remove the list of duplicates when it gets empty
  37418. if (recordList.remove(record)) {
  37419. this.map.delete(key);
  37420. }
  37421. return record;
  37422. }
  37423. get isEmpty() {
  37424. return this.map.size === 0;
  37425. }
  37426. clear() {
  37427. this.map.clear();
  37428. }
  37429. }
  37430. function getPreviousIndex(item, addRemoveOffset, moveOffsets) {
  37431. const previousIndex = item.previousIndex;
  37432. if (previousIndex === null)
  37433. return previousIndex;
  37434. let moveOffset = 0;
  37435. if (moveOffsets && previousIndex < moveOffsets.length) {
  37436. moveOffset = moveOffsets[previousIndex];
  37437. }
  37438. return previousIndex + addRemoveOffset + moveOffset;
  37439. }
  37440. class DefaultKeyValueDifferFactory {
  37441. constructor() { }
  37442. supports(obj) {
  37443. return obj instanceof Map || isJsObject(obj);
  37444. }
  37445. create() {
  37446. return new DefaultKeyValueDiffer();
  37447. }
  37448. }
  37449. class DefaultKeyValueDiffer {
  37450. _records = new Map();
  37451. _mapHead = null;
  37452. // _appendAfter is used in the check loop
  37453. _appendAfter = null;
  37454. _previousMapHead = null;
  37455. _changesHead = null;
  37456. _changesTail = null;
  37457. _additionsHead = null;
  37458. _additionsTail = null;
  37459. _removalsHead = null;
  37460. _removalsTail = null;
  37461. get isDirty() {
  37462. return (this._additionsHead !== null || this._changesHead !== null || this._removalsHead !== null);
  37463. }
  37464. forEachItem(fn) {
  37465. let record;
  37466. for (record = this._mapHead; record !== null; record = record._next) {
  37467. fn(record);
  37468. }
  37469. }
  37470. forEachPreviousItem(fn) {
  37471. let record;
  37472. for (record = this._previousMapHead; record !== null; record = record._nextPrevious) {
  37473. fn(record);
  37474. }
  37475. }
  37476. forEachChangedItem(fn) {
  37477. let record;
  37478. for (record = this._changesHead; record !== null; record = record._nextChanged) {
  37479. fn(record);
  37480. }
  37481. }
  37482. forEachAddedItem(fn) {
  37483. let record;
  37484. for (record = this._additionsHead; record !== null; record = record._nextAdded) {
  37485. fn(record);
  37486. }
  37487. }
  37488. forEachRemovedItem(fn) {
  37489. let record;
  37490. for (record = this._removalsHead; record !== null; record = record._nextRemoved) {
  37491. fn(record);
  37492. }
  37493. }
  37494. diff(map) {
  37495. if (!map) {
  37496. map = new Map();
  37497. }
  37498. else if (!(map instanceof Map || isJsObject(map))) {
  37499. throw new RuntimeError(900 /* RuntimeErrorCode.INVALID_DIFFER_INPUT */, ngDevMode && `Error trying to diff '${stringify(map)}'. Only maps and objects are allowed`);
  37500. }
  37501. return this.check(map) ? this : null;
  37502. }
  37503. onDestroy() { }
  37504. /**
  37505. * Check the current state of the map vs the previous.
  37506. * The algorithm is optimised for when the keys do no change.
  37507. */
  37508. check(map) {
  37509. this._reset();
  37510. let insertBefore = this._mapHead;
  37511. this._appendAfter = null;
  37512. this._forEach(map, (value, key) => {
  37513. if (insertBefore && insertBefore.key === key) {
  37514. this._maybeAddToChanges(insertBefore, value);
  37515. this._appendAfter = insertBefore;
  37516. insertBefore = insertBefore._next;
  37517. }
  37518. else {
  37519. const record = this._getOrCreateRecordForKey(key, value);
  37520. insertBefore = this._insertBeforeOrAppend(insertBefore, record);
  37521. }
  37522. });
  37523. // Items remaining at the end of the list have been deleted
  37524. if (insertBefore) {
  37525. if (insertBefore._prev) {
  37526. insertBefore._prev._next = null;
  37527. }
  37528. this._removalsHead = insertBefore;
  37529. for (let record = insertBefore; record !== null; record = record._nextRemoved) {
  37530. if (record === this._mapHead) {
  37531. this._mapHead = null;
  37532. }
  37533. this._records.delete(record.key);
  37534. record._nextRemoved = record._next;
  37535. record.previousValue = record.currentValue;
  37536. record.currentValue = null;
  37537. record._prev = null;
  37538. record._next = null;
  37539. }
  37540. }
  37541. // Make sure tails have no next records from previous runs
  37542. if (this._changesTail)
  37543. this._changesTail._nextChanged = null;
  37544. if (this._additionsTail)
  37545. this._additionsTail._nextAdded = null;
  37546. return this.isDirty;
  37547. }
  37548. /**
  37549. * Inserts a record before `before` or append at the end of the list when `before` is null.
  37550. *
  37551. * Notes:
  37552. * - This method appends at `this._appendAfter`,
  37553. * - This method updates `this._appendAfter`,
  37554. * - The return value is the new value for the insertion pointer.
  37555. */
  37556. _insertBeforeOrAppend(before, record) {
  37557. if (before) {
  37558. const prev = before._prev;
  37559. record._next = before;
  37560. record._prev = prev;
  37561. before._prev = record;
  37562. if (prev) {
  37563. prev._next = record;
  37564. }
  37565. if (before === this._mapHead) {
  37566. this._mapHead = record;
  37567. }
  37568. this._appendAfter = before;
  37569. return before;
  37570. }
  37571. if (this._appendAfter) {
  37572. this._appendAfter._next = record;
  37573. record._prev = this._appendAfter;
  37574. }
  37575. else {
  37576. this._mapHead = record;
  37577. }
  37578. this._appendAfter = record;
  37579. return null;
  37580. }
  37581. _getOrCreateRecordForKey(key, value) {
  37582. if (this._records.has(key)) {
  37583. const record = this._records.get(key);
  37584. this._maybeAddToChanges(record, value);
  37585. const prev = record._prev;
  37586. const next = record._next;
  37587. if (prev) {
  37588. prev._next = next;
  37589. }
  37590. if (next) {
  37591. next._prev = prev;
  37592. }
  37593. record._next = null;
  37594. record._prev = null;
  37595. return record;
  37596. }
  37597. const record = new KeyValueChangeRecord_(key);
  37598. this._records.set(key, record);
  37599. record.currentValue = value;
  37600. this._addToAdditions(record);
  37601. return record;
  37602. }
  37603. /** @internal */
  37604. _reset() {
  37605. if (this.isDirty) {
  37606. let record;
  37607. // let `_previousMapHead` contain the state of the map before the changes
  37608. this._previousMapHead = this._mapHead;
  37609. for (record = this._previousMapHead; record !== null; record = record._next) {
  37610. record._nextPrevious = record._next;
  37611. }
  37612. // Update `record.previousValue` with the value of the item before the changes
  37613. // We need to update all changed items (that's those which have been added and changed)
  37614. for (record = this._changesHead; record !== null; record = record._nextChanged) {
  37615. record.previousValue = record.currentValue;
  37616. }
  37617. for (record = this._additionsHead; record != null; record = record._nextAdded) {
  37618. record.previousValue = record.currentValue;
  37619. }
  37620. this._changesHead = this._changesTail = null;
  37621. this._additionsHead = this._additionsTail = null;
  37622. this._removalsHead = null;
  37623. }
  37624. }
  37625. // Add the record or a given key to the list of changes only when the value has actually changed
  37626. _maybeAddToChanges(record, newValue) {
  37627. if (!Object.is(newValue, record.currentValue)) {
  37628. record.previousValue = record.currentValue;
  37629. record.currentValue = newValue;
  37630. this._addToChanges(record);
  37631. }
  37632. }
  37633. _addToAdditions(record) {
  37634. if (this._additionsHead === null) {
  37635. this._additionsHead = this._additionsTail = record;
  37636. }
  37637. else {
  37638. this._additionsTail._nextAdded = record;
  37639. this._additionsTail = record;
  37640. }
  37641. }
  37642. _addToChanges(record) {
  37643. if (this._changesHead === null) {
  37644. this._changesHead = this._changesTail = record;
  37645. }
  37646. else {
  37647. this._changesTail._nextChanged = record;
  37648. this._changesTail = record;
  37649. }
  37650. }
  37651. /** @internal */
  37652. _forEach(obj, fn) {
  37653. if (obj instanceof Map) {
  37654. obj.forEach(fn);
  37655. }
  37656. else {
  37657. Object.keys(obj).forEach((k) => fn(obj[k], k));
  37658. }
  37659. }
  37660. }
  37661. class KeyValueChangeRecord_ {
  37662. key;
  37663. previousValue = null;
  37664. currentValue = null;
  37665. /** @internal */
  37666. _nextPrevious = null;
  37667. /** @internal */
  37668. _next = null;
  37669. /** @internal */
  37670. _prev = null;
  37671. /** @internal */
  37672. _nextAdded = null;
  37673. /** @internal */
  37674. _nextRemoved = null;
  37675. /** @internal */
  37676. _nextChanged = null;
  37677. constructor(key) {
  37678. this.key = key;
  37679. }
  37680. }
  37681. function defaultIterableDiffersFactory() {
  37682. return new IterableDiffers([new DefaultIterableDifferFactory()]);
  37683. }
  37684. /**
  37685. * A repository of different iterable diffing strategies used by NgFor, NgClass, and others.
  37686. *
  37687. * @publicApi
  37688. */
  37689. class IterableDiffers {
  37690. factories;
  37691. /** @nocollapse */
  37692. static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
  37693. token: IterableDiffers,
  37694. providedIn: 'root',
  37695. factory: defaultIterableDiffersFactory,
  37696. });
  37697. constructor(factories) {
  37698. this.factories = factories;
  37699. }
  37700. static create(factories, parent) {
  37701. if (parent != null) {
  37702. const copied = parent.factories.slice();
  37703. factories = factories.concat(copied);
  37704. }
  37705. return new IterableDiffers(factories);
  37706. }
  37707. /**
  37708. * Takes an array of {@link IterableDifferFactory} and returns a provider used to extend the
  37709. * inherited {@link IterableDiffers} instance with the provided factories and return a new
  37710. * {@link IterableDiffers} instance.
  37711. *
  37712. * @usageNotes
  37713. * ### Example
  37714. *
  37715. * The following example shows how to extend an existing list of factories,
  37716. * which will only be applied to the injector for this component and its children.
  37717. * This step is all that's required to make a new {@link IterableDiffer} available.
  37718. *
  37719. * ```ts
  37720. * @Component({
  37721. * viewProviders: [
  37722. * IterableDiffers.extend([new ImmutableListDiffer()])
  37723. * ]
  37724. * })
  37725. * ```
  37726. */
  37727. static extend(factories) {
  37728. return {
  37729. provide: IterableDiffers,
  37730. useFactory: (parent) => {
  37731. // if parent is null, it means that we are in the root injector and we have just overridden
  37732. // the default injection mechanism for IterableDiffers, in such a case just assume
  37733. // `defaultIterableDiffersFactory`.
  37734. return IterableDiffers.create(factories, parent || defaultIterableDiffersFactory());
  37735. },
  37736. // Dependency technically isn't optional, but we can provide a better error message this way.
  37737. deps: [[IterableDiffers, new SkipSelf(), new Optional()]],
  37738. };
  37739. }
  37740. find(iterable) {
  37741. const factory = this.factories.find((f) => f.supports(iterable));
  37742. if (factory != null) {
  37743. return factory;
  37744. }
  37745. else {
  37746. throw new RuntimeError(901 /* RuntimeErrorCode.NO_SUPPORTING_DIFFER_FACTORY */, ngDevMode &&
  37747. `Cannot find a differ supporting object '${iterable}' of type '${getTypeNameForDebugging(iterable)}'`);
  37748. }
  37749. }
  37750. }
  37751. function getTypeNameForDebugging(type) {
  37752. return type['name'] || typeof type;
  37753. }
  37754. function defaultKeyValueDiffersFactory() {
  37755. return new KeyValueDiffers([new DefaultKeyValueDifferFactory()]);
  37756. }
  37757. /**
  37758. * A repository of different Map diffing strategies used by NgClass, NgStyle, and others.
  37759. *
  37760. * @publicApi
  37761. */
  37762. class KeyValueDiffers {
  37763. /** @nocollapse */
  37764. static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
  37765. token: KeyValueDiffers,
  37766. providedIn: 'root',
  37767. factory: defaultKeyValueDiffersFactory,
  37768. });
  37769. factories;
  37770. constructor(factories) {
  37771. this.factories = factories;
  37772. }
  37773. static create(factories, parent) {
  37774. if (parent) {
  37775. const copied = parent.factories.slice();
  37776. factories = factories.concat(copied);
  37777. }
  37778. return new KeyValueDiffers(factories);
  37779. }
  37780. /**
  37781. * Takes an array of {@link KeyValueDifferFactory} and returns a provider used to extend the
  37782. * inherited {@link KeyValueDiffers} instance with the provided factories and return a new
  37783. * {@link KeyValueDiffers} instance.
  37784. *
  37785. * @usageNotes
  37786. * ### Example
  37787. *
  37788. * The following example shows how to extend an existing list of factories,
  37789. * which will only be applied to the injector for this component and its children.
  37790. * This step is all that's required to make a new {@link KeyValueDiffer} available.
  37791. *
  37792. * ```ts
  37793. * @Component({
  37794. * viewProviders: [
  37795. * KeyValueDiffers.extend([new ImmutableMapDiffer()])
  37796. * ]
  37797. * })
  37798. * ```
  37799. */
  37800. static extend(factories) {
  37801. return {
  37802. provide: KeyValueDiffers,
  37803. useFactory: (parent) => {
  37804. // if parent is null, it means that we are in the root injector and we have just overridden
  37805. // the default injection mechanism for KeyValueDiffers, in such a case just assume
  37806. // `defaultKeyValueDiffersFactory`.
  37807. return KeyValueDiffers.create(factories, parent || defaultKeyValueDiffersFactory());
  37808. },
  37809. // Dependency technically isn't optional, but we can provide a better error message this way.
  37810. deps: [[KeyValueDiffers, new SkipSelf(), new Optional()]],
  37811. };
  37812. }
  37813. find(kv) {
  37814. const factory = this.factories.find((f) => f.supports(kv));
  37815. if (factory) {
  37816. return factory;
  37817. }
  37818. throw new RuntimeError(901 /* RuntimeErrorCode.NO_SUPPORTING_DIFFER_FACTORY */, ngDevMode && `Cannot find a differ supporting object '${kv}'`);
  37819. }
  37820. }
  37821. /**
  37822. * Structural diffing for `Object`s and `Map`s.
  37823. */
  37824. const keyValDiff = [new DefaultKeyValueDifferFactory()];
  37825. /**
  37826. * Structural diffing for `Iterable` types such as `Array`s.
  37827. */
  37828. const iterableDiff = [new DefaultIterableDifferFactory()];
  37829. const defaultIterableDiffers = new IterableDiffers(iterableDiff);
  37830. const defaultKeyValueDiffers = new KeyValueDiffers(keyValDiff);
  37831. /**
  37832. * This platform has to be included in any other platform
  37833. *
  37834. * @publicApi
  37835. */
  37836. const platformCore = createPlatformFactory(null, 'core', []);
  37837. /**
  37838. * Re-exported by `BrowserModule`, which is included automatically in the root
  37839. * `AppModule` when you create a new app with the CLI `new` command. Eagerly injects
  37840. * `ApplicationRef` to instantiate it.
  37841. *
  37842. * @publicApi
  37843. */
  37844. class ApplicationModule {
  37845. // Inject ApplicationRef to make it eager...
  37846. constructor(appRef) { }
  37847. static ɵfac = function ApplicationModule_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || ApplicationModule)(ɵɵinject(ApplicationRef)); };
  37848. static ɵmod = /*@__PURE__*/ ɵɵdefineNgModule({ type: ApplicationModule });
  37849. static ɵinj = /*@__PURE__*/ ɵɵdefineInjector({});
  37850. }
  37851. (() => { (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(ApplicationModule, [{
  37852. type: NgModule
  37853. }], () => [{ type: ApplicationRef }], null); })();
  37854. /**
  37855. * Internal create application API that implements the core application creation logic and optional
  37856. * bootstrap logic.
  37857. *
  37858. * Platforms (such as `platform-browser`) may require different set of application and platform
  37859. * providers for an application to function correctly. As a result, platforms may use this function
  37860. * internally and supply the necessary providers during the bootstrap, while exposing
  37861. * platform-specific APIs as a part of their public API.
  37862. *
  37863. * @returns A promise that returns an `ApplicationRef` instance once resolved.
  37864. */
  37865. function internalCreateApplication(config) {
  37866. profiler(8 /* ProfilerEvent.BootstrapApplicationStart */);
  37867. try {
  37868. const { rootComponent, appProviders, platformProviders } = config;
  37869. if ((typeof ngDevMode === 'undefined' || ngDevMode) && rootComponent !== undefined) {
  37870. assertStandaloneComponentType(rootComponent);
  37871. }
  37872. const platformInjector = createOrReusePlatformInjector(platformProviders);
  37873. // Create root application injector based on a set of providers configured at the platform
  37874. // bootstrap level as well as providers passed to the bootstrap call by a user.
  37875. const allAppProviders = [
  37876. internalProvideZoneChangeDetection({}),
  37877. { provide: ChangeDetectionScheduler, useExisting: ChangeDetectionSchedulerImpl },
  37878. ...(appProviders || []),
  37879. ];
  37880. const adapter = new EnvironmentNgModuleRefAdapter({
  37881. providers: allAppProviders,
  37882. parent: platformInjector,
  37883. debugName: typeof ngDevMode === 'undefined' || ngDevMode ? 'Environment Injector' : '',
  37884. // We skip environment initializers because we need to run them inside the NgZone, which
  37885. // happens after we get the NgZone instance from the Injector.
  37886. runEnvironmentInitializers: false,
  37887. });
  37888. return bootstrap({
  37889. r3Injector: adapter.injector,
  37890. platformInjector,
  37891. rootComponent,
  37892. });
  37893. }
  37894. catch (e) {
  37895. return Promise.reject(e);
  37896. }
  37897. finally {
  37898. profiler(9 /* ProfilerEvent.BootstrapApplicationEnd */);
  37899. }
  37900. }
  37901. /** Apps in which we've enabled event replay.
  37902. * This is to prevent initializing event replay more than once per app.
  37903. */
  37904. const appsWithEventReplay = new WeakSet();
  37905. /**
  37906. * The key that represents all replayable elements that are not in defer blocks.
  37907. */
  37908. const EAGER_CONTENT_LISTENERS_KEY = '';
  37909. /**
  37910. * A list of block events that need to be replayed
  37911. */
  37912. let blockEventQueue = [];
  37913. /**
  37914. * Determines whether Event Replay feature should be activated on the client.
  37915. */
  37916. function shouldEnableEventReplay(injector) {
  37917. return injector.get(IS_EVENT_REPLAY_ENABLED, EVENT_REPLAY_ENABLED_DEFAULT);
  37918. }
  37919. /**
  37920. * Returns a set of providers required to setup support for event replay.
  37921. * Requires hydration to be enabled separately.
  37922. */
  37923. function withEventReplay() {
  37924. const providers = [
  37925. {
  37926. provide: IS_EVENT_REPLAY_ENABLED,
  37927. useFactory: () => {
  37928. let isEnabled = true;
  37929. if (typeof ngServerMode === 'undefined' || !ngServerMode) {
  37930. // Note: globalThis[CONTRACT_PROPERTY] may be undefined in case Event Replay feature
  37931. // is enabled, but there are no events configured in this application, in which case
  37932. // we don't activate this feature, since there are no events to replay.
  37933. const appId = inject(APP_ID);
  37934. isEnabled = !!window._ejsas?.[appId];
  37935. }
  37936. if (isEnabled) {
  37937. performanceMarkFeature('NgEventReplay');
  37938. }
  37939. return isEnabled;
  37940. },
  37941. },
  37942. ];
  37943. if (typeof ngServerMode === 'undefined' || !ngServerMode) {
  37944. providers.push({
  37945. provide: ENVIRONMENT_INITIALIZER,
  37946. useValue: () => {
  37947. const appRef = inject(ApplicationRef);
  37948. const { injector } = appRef;
  37949. // We have to check for the appRef here due to the possibility of multiple apps
  37950. // being present on the same page. We only want to enable event replay for the
  37951. // apps that actually want it.
  37952. if (!appsWithEventReplay.has(appRef)) {
  37953. const jsActionMap = inject(JSACTION_BLOCK_ELEMENT_MAP);
  37954. if (shouldEnableEventReplay(injector)) {
  37955. enableStashEventListenerImpl();
  37956. const appId = injector.get(APP_ID);
  37957. const clearStashFn = setStashFn(appId, (rEl, eventName, listenerFn) => {
  37958. // If a user binds to a ng-container and uses a directive that binds using a host listener,
  37959. // this element could be a comment node. So we need to ensure we have an actual element
  37960. // node before stashing anything.
  37961. if (rEl.nodeType !== Node.ELEMENT_NODE)
  37962. return;
  37963. sharedStashFunction(rEl, eventName, listenerFn);
  37964. sharedMapFunction(rEl, jsActionMap);
  37965. });
  37966. // Clean up the reference to the function set by the environment initializer,
  37967. // as the function closure may capture injected elements and prevent them
  37968. // from being properly garbage collected.
  37969. appRef.onDestroy(clearStashFn);
  37970. }
  37971. }
  37972. },
  37973. multi: true,
  37974. }, {
  37975. provide: APP_BOOTSTRAP_LISTENER,
  37976. useFactory: () => {
  37977. const appRef = inject(ApplicationRef);
  37978. const { injector } = appRef;
  37979. return () => {
  37980. // We have to check for the appRef here due to the possibility of multiple apps
  37981. // being present on the same page. We only want to enable event replay for the
  37982. // apps that actually want it.
  37983. if (!shouldEnableEventReplay(injector) || appsWithEventReplay.has(appRef)) {
  37984. return;
  37985. }
  37986. appsWithEventReplay.add(appRef);
  37987. appRef.onDestroy(() => {
  37988. appsWithEventReplay.delete(appRef);
  37989. // Ensure that we're always safe calling this in the browser.
  37990. if (typeof ngServerMode !== 'undefined' && !ngServerMode) {
  37991. const appId = injector.get(APP_ID);
  37992. // `_ejsa` should be deleted when the app is destroyed, ensuring that
  37993. // no elements are still captured in the global list and are not prevented
  37994. // from being garbage collected.
  37995. clearAppScopedEarlyEventContract(appId);
  37996. }
  37997. });
  37998. // Kick off event replay logic once hydration for the initial part
  37999. // of the application is completed. This timing is similar to the unclaimed
  38000. // dehydrated views cleanup timing.
  38001. appRef.whenStable().then(() => {
  38002. // Note: we have to check whether the application is destroyed before
  38003. // performing other operations with the `injector`.
  38004. // The application may be destroyed **before** it becomes stable, so when
  38005. // the `whenStable` resolves, the injector might already be in
  38006. // a destroyed state. Thus, calling `injector.get` would throw an error
  38007. // indicating that the injector has already been destroyed.
  38008. if (appRef.destroyed) {
  38009. return;
  38010. }
  38011. const eventContractDetails = injector.get(JSACTION_EVENT_CONTRACT);
  38012. initEventReplay(eventContractDetails, injector);
  38013. const jsActionMap = injector.get(JSACTION_BLOCK_ELEMENT_MAP);
  38014. jsActionMap.get(EAGER_CONTENT_LISTENERS_KEY)?.forEach(removeListeners);
  38015. jsActionMap.delete(EAGER_CONTENT_LISTENERS_KEY);
  38016. const eventContract = eventContractDetails.instance;
  38017. // This removes event listeners registered through the container manager,
  38018. // as listeners registered on `document.body` might never be removed if we
  38019. // don't clean up the contract.
  38020. if (isIncrementalHydrationEnabled(injector)) {
  38021. // When incremental hydration is enabled, we cannot clean up the event
  38022. // contract immediately because we're unaware if there are any deferred
  38023. // blocks to hydrate. We can only schedule a contract cleanup when the
  38024. // app is destroyed.
  38025. appRef.onDestroy(() => eventContract.cleanUp());
  38026. }
  38027. else {
  38028. eventContract.cleanUp();
  38029. }
  38030. });
  38031. };
  38032. },
  38033. multi: true,
  38034. });
  38035. }
  38036. return providers;
  38037. }
  38038. const initEventReplay = (eventDelegation, injector) => {
  38039. const appId = injector.get(APP_ID);
  38040. // This is set in packages/platform-server/src/utils.ts
  38041. const earlyJsactionData = window._ejsas[appId];
  38042. const eventContract = (eventDelegation.instance = new EventContract(new EventContractContainer(earlyJsactionData.c)));
  38043. for (const et of earlyJsactionData.et) {
  38044. eventContract.addEvent(et);
  38045. }
  38046. for (const et of earlyJsactionData.etc) {
  38047. eventContract.addEvent(et);
  38048. }
  38049. const eventInfos = getAppScopedQueuedEventInfos(appId);
  38050. eventContract.replayEarlyEventInfos(eventInfos);
  38051. clearAppScopedEarlyEventContract(appId);
  38052. const dispatcher = new EventDispatcher((event) => {
  38053. invokeRegisteredReplayListeners(injector, event, event.currentTarget);
  38054. });
  38055. registerDispatcher(eventContract, dispatcher);
  38056. };
  38057. /**
  38058. * Extracts information about all DOM events (added in a template) registered on elements in a give
  38059. * LView. Maps collected events to a corresponding DOM element (an element is used as a key).
  38060. */
  38061. function collectDomEventsInfo(tView, lView, eventTypesToReplay) {
  38062. const domEventsInfo = new Map();
  38063. const lCleanup = lView[CLEANUP];
  38064. const tCleanup = tView.cleanup;
  38065. if (!tCleanup || !lCleanup) {
  38066. return domEventsInfo;
  38067. }
  38068. for (let i = 0; i < tCleanup.length;) {
  38069. const firstParam = tCleanup[i++];
  38070. const secondParam = tCleanup[i++];
  38071. if (typeof firstParam !== 'string') {
  38072. continue;
  38073. }
  38074. const eventType = firstParam;
  38075. if (!isEarlyEventType(eventType)) {
  38076. continue;
  38077. }
  38078. if (isCaptureEventType(eventType)) {
  38079. eventTypesToReplay.capture.add(eventType);
  38080. }
  38081. else {
  38082. eventTypesToReplay.regular.add(eventType);
  38083. }
  38084. const listenerElement = unwrapRNode(lView[secondParam]);
  38085. i++; // move the cursor to the next position (location of the listener idx)
  38086. const useCaptureOrIndx = tCleanup[i++];
  38087. // if useCaptureOrIndx is boolean then report it as is.
  38088. // if useCaptureOrIndx is positive number then it in unsubscribe method
  38089. // if useCaptureOrIndx is negative number then it is a Subscription
  38090. const isDomEvent = typeof useCaptureOrIndx === 'boolean' || useCaptureOrIndx >= 0;
  38091. if (!isDomEvent) {
  38092. continue;
  38093. }
  38094. if (!domEventsInfo.has(listenerElement)) {
  38095. domEventsInfo.set(listenerElement, [eventType]);
  38096. }
  38097. else {
  38098. domEventsInfo.get(listenerElement).push(eventType);
  38099. }
  38100. }
  38101. return domEventsInfo;
  38102. }
  38103. function invokeRegisteredReplayListeners(injector, event, currentTarget) {
  38104. const blockName = (currentTarget && currentTarget.getAttribute(DEFER_BLOCK_SSR_ID_ATTRIBUTE)) ?? '';
  38105. if (/d\d+/.test(blockName)) {
  38106. hydrateAndInvokeBlockListeners(blockName, injector, event, currentTarget);
  38107. }
  38108. else if (event.eventPhase === EventPhase.REPLAY) {
  38109. invokeListeners(event, currentTarget);
  38110. }
  38111. }
  38112. function hydrateAndInvokeBlockListeners(blockName, injector, event, currentTarget) {
  38113. blockEventQueue.push({ event, currentTarget });
  38114. triggerHydrationFromBlockName(injector, blockName, replayQueuedBlockEvents);
  38115. }
  38116. function replayQueuedBlockEvents(hydratedBlocks) {
  38117. // clone the queue
  38118. const queue = [...blockEventQueue];
  38119. const hydrated = new Set(hydratedBlocks);
  38120. // empty it
  38121. blockEventQueue = [];
  38122. for (let { event, currentTarget } of queue) {
  38123. const blockName = currentTarget.getAttribute(DEFER_BLOCK_SSR_ID_ATTRIBUTE);
  38124. if (hydrated.has(blockName)) {
  38125. invokeListeners(event, currentTarget);
  38126. }
  38127. else {
  38128. // requeue events that weren't yet hydrated
  38129. blockEventQueue.push({ event, currentTarget });
  38130. }
  38131. }
  38132. }
  38133. /**
  38134. * A collection that tracks all serialized views (`ngh` DOM annotations)
  38135. * to avoid duplication. An attempt to add a duplicate view results in the
  38136. * collection returning the index of the previously collected serialized view.
  38137. * This reduces the number of annotations needed for a given page.
  38138. */
  38139. class SerializedViewCollection {
  38140. views = [];
  38141. indexByContent = new Map();
  38142. add(serializedView) {
  38143. const viewAsString = JSON.stringify(serializedView);
  38144. if (!this.indexByContent.has(viewAsString)) {
  38145. const index = this.views.length;
  38146. this.views.push(serializedView);
  38147. this.indexByContent.set(viewAsString, index);
  38148. return index;
  38149. }
  38150. return this.indexByContent.get(viewAsString);
  38151. }
  38152. getAll() {
  38153. return this.views;
  38154. }
  38155. }
  38156. /**
  38157. * Global counter that is used to generate a unique id for TViews
  38158. * during the serialization process.
  38159. */
  38160. let tViewSsrId = 0;
  38161. /**
  38162. * Generates a unique id for a given TView and returns this id.
  38163. * The id is also stored on this instance of a TView and reused in
  38164. * subsequent calls.
  38165. *
  38166. * This id is needed to uniquely identify and pick up dehydrated views
  38167. * at runtime.
  38168. */
  38169. function getSsrId(tView) {
  38170. if (!tView.ssrId) {
  38171. tView.ssrId = `t${tViewSsrId++}`;
  38172. }
  38173. return tView.ssrId;
  38174. }
  38175. /**
  38176. * Computes the number of root nodes in a given view
  38177. * (or child nodes in a given container if a tNode is provided).
  38178. */
  38179. function calcNumRootNodes(tView, lView, tNode) {
  38180. const rootNodes = [];
  38181. collectNativeNodes(tView, lView, tNode, rootNodes);
  38182. return rootNodes.length;
  38183. }
  38184. /**
  38185. * Computes the number of root nodes in all views in a given LContainer.
  38186. */
  38187. function calcNumRootNodesInLContainer(lContainer) {
  38188. const rootNodes = [];
  38189. collectNativeNodesInLContainer(lContainer, rootNodes);
  38190. return rootNodes.length;
  38191. }
  38192. /**
  38193. * Annotates root level component's LView for hydration,
  38194. * see `annotateHostElementForHydration` for additional information.
  38195. */
  38196. function annotateComponentLViewForHydration(lView, context, injector) {
  38197. const hostElement = lView[HOST];
  38198. // Root elements might also be annotated with the `ngSkipHydration` attribute,
  38199. // check if it's present before starting the serialization process.
  38200. if (hostElement && !hostElement.hasAttribute(SKIP_HYDRATION_ATTR_NAME)) {
  38201. return annotateHostElementForHydration(hostElement, lView, null, context);
  38202. }
  38203. return null;
  38204. }
  38205. /**
  38206. * Annotates root level LContainer for hydration. This happens when a root component
  38207. * injects ViewContainerRef, thus making the component an anchor for a view container.
  38208. * This function serializes the component itself as well as all views from the view
  38209. * container.
  38210. */
  38211. function annotateLContainerForHydration(lContainer, context, injector) {
  38212. const componentLView = unwrapLView(lContainer[HOST]);
  38213. // Serialize the root component itself.
  38214. const componentLViewNghIndex = annotateComponentLViewForHydration(componentLView, context);
  38215. if (componentLViewNghIndex === null) {
  38216. // Component was not serialized (for example, if hydration was skipped by adding
  38217. // the `ngSkipHydration` attribute or this component uses i18n blocks in the template,
  38218. // but `withI18nSupport()` was not added), avoid annotating host element with the `ngh`
  38219. // attribute.
  38220. return;
  38221. }
  38222. const hostElement = unwrapRNode(componentLView[HOST]);
  38223. // Serialize all views within this view container.
  38224. const rootLView = lContainer[PARENT];
  38225. const rootLViewNghIndex = annotateHostElementForHydration(hostElement, rootLView, null, context);
  38226. const renderer = componentLView[RENDERER];
  38227. // For cases when a root component also acts as an anchor node for a ViewContainerRef
  38228. // (for example, when ViewContainerRef is injected in a root component), there is a need
  38229. // to serialize information about the component itself, as well as an LContainer that
  38230. // represents this ViewContainerRef. Effectively, we need to serialize 2 pieces of info:
  38231. // (1) hydration info for the root component itself and (2) hydration info for the
  38232. // ViewContainerRef instance (an LContainer). Each piece of information is included into
  38233. // the hydration data (in the TransferState object) separately, thus we end up with 2 ids.
  38234. // Since we only have 1 root element, we encode both bits of info into a single string:
  38235. // ids are separated by the `|` char (e.g. `10|25`, where `10` is the ngh for a component view
  38236. // and 25 is the `ngh` for a root view which holds LContainer).
  38237. const finalIndex = `${componentLViewNghIndex}|${rootLViewNghIndex}`;
  38238. renderer.setAttribute(hostElement, NGH_ATTR_NAME, finalIndex);
  38239. }
  38240. /**
  38241. * Annotates all components bootstrapped in a given ApplicationRef
  38242. * with info needed for hydration.
  38243. *
  38244. * @param appRef An instance of an ApplicationRef.
  38245. * @param doc A reference to the current Document instance.
  38246. * @return event types that need to be replayed
  38247. */
  38248. function annotateForHydration(appRef, doc) {
  38249. const injector = appRef.injector;
  38250. const isI18nHydrationEnabledVal = isI18nHydrationEnabled(injector);
  38251. const isIncrementalHydrationEnabledVal = isIncrementalHydrationEnabled(injector);
  38252. const serializedViewCollection = new SerializedViewCollection();
  38253. const corruptedTextNodes = new Map();
  38254. const viewRefs = appRef._views;
  38255. const shouldReplayEvents = injector.get(IS_EVENT_REPLAY_ENABLED, EVENT_REPLAY_ENABLED_DEFAULT);
  38256. const eventTypesToReplay = {
  38257. regular: new Set(),
  38258. capture: new Set(),
  38259. };
  38260. const deferBlocks = new Map();
  38261. appRef.injector.get(APP_ID);
  38262. for (const viewRef of viewRefs) {
  38263. const lNode = getLNodeForHydration(viewRef);
  38264. // An `lView` might be `null` if a `ViewRef` represents
  38265. // an embedded view (not a component view).
  38266. if (lNode !== null) {
  38267. const context = {
  38268. serializedViewCollection,
  38269. corruptedTextNodes,
  38270. isI18nHydrationEnabled: isI18nHydrationEnabledVal,
  38271. isIncrementalHydrationEnabled: isIncrementalHydrationEnabledVal,
  38272. i18nChildren: new Map(),
  38273. eventTypesToReplay,
  38274. shouldReplayEvents,
  38275. deferBlocks,
  38276. };
  38277. if (isLContainer(lNode)) {
  38278. annotateLContainerForHydration(lNode, context);
  38279. }
  38280. else {
  38281. annotateComponentLViewForHydration(lNode, context);
  38282. }
  38283. insertCorruptedTextNodeMarkers(corruptedTextNodes, doc);
  38284. }
  38285. }
  38286. // Note: we *always* include hydration info key and a corresponding value
  38287. // into the TransferState, even if the list of serialized views is empty.
  38288. // This is needed as a signal to the client that the server part of the
  38289. // hydration logic was setup and enabled correctly. Otherwise, if a client
  38290. // hydration doesn't find a key in the transfer state - an error is produced.
  38291. const serializedViews = serializedViewCollection.getAll();
  38292. const transferState = injector.get(TransferState);
  38293. transferState.set(NGH_DATA_KEY, serializedViews);
  38294. if (deferBlocks.size > 0) {
  38295. const blocks = {};
  38296. for (const [id, info] of deferBlocks.entries()) {
  38297. blocks[id] = info;
  38298. }
  38299. transferState.set(NGH_DEFER_BLOCKS_KEY, blocks);
  38300. }
  38301. return eventTypesToReplay;
  38302. }
  38303. /**
  38304. * Serializes the lContainer data into a list of SerializedView objects,
  38305. * that represent views within this lContainer.
  38306. *
  38307. * @param lContainer the lContainer we are serializing
  38308. * @param tNode the TNode that contains info about this LContainer
  38309. * @param lView that hosts this LContainer
  38310. * @param parentDeferBlockId the defer block id of the parent if it exists
  38311. * @param context the hydration context
  38312. * @returns an array of the `SerializedView` objects
  38313. */
  38314. function serializeLContainer(lContainer, tNode, lView, parentDeferBlockId, context) {
  38315. const views = [];
  38316. let lastViewAsString = '';
  38317. for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
  38318. let childLView = lContainer[i];
  38319. let template;
  38320. let numRootNodes;
  38321. let serializedView;
  38322. if (isRootView(childLView)) {
  38323. // If this is a root view, get an LView for the underlying component,
  38324. // because it contains information about the view to serialize.
  38325. childLView = childLView[HEADER_OFFSET];
  38326. // If we have an LContainer at this position, this indicates that the
  38327. // host element was used as a ViewContainerRef anchor (e.g. a `ViewContainerRef`
  38328. // was injected within the component class). This case requires special handling.
  38329. if (isLContainer(childLView)) {
  38330. // Calculate the number of root nodes in all views in a given container
  38331. // and increment by one to account for an anchor node itself, i.e. in this
  38332. // scenario we'll have a layout that would look like this:
  38333. // `<app-root /><#VIEW1><#VIEW2>...<!--container-->`
  38334. // The `+1` is to capture the `<app-root />` element.
  38335. numRootNodes = calcNumRootNodesInLContainer(childLView) + 1;
  38336. annotateLContainerForHydration(childLView, context);
  38337. const componentLView = unwrapLView(childLView[HOST]);
  38338. serializedView = {
  38339. [TEMPLATE_ID]: componentLView[TVIEW].ssrId,
  38340. [NUM_ROOT_NODES]: numRootNodes,
  38341. };
  38342. }
  38343. }
  38344. if (!serializedView) {
  38345. const childTView = childLView[TVIEW];
  38346. if (childTView.type === 1 /* TViewType.Component */) {
  38347. template = childTView.ssrId;
  38348. // This is a component view, thus it has only 1 root node: the component
  38349. // host node itself (other nodes would be inside that host node).
  38350. numRootNodes = 1;
  38351. }
  38352. else {
  38353. template = getSsrId(childTView);
  38354. numRootNodes = calcNumRootNodes(childTView, childLView, childTView.firstChild);
  38355. }
  38356. serializedView = {
  38357. [TEMPLATE_ID]: template,
  38358. [NUM_ROOT_NODES]: numRootNodes,
  38359. };
  38360. let isHydrateNeverBlock = false;
  38361. // If this is a defer block, serialize extra info.
  38362. if (isDeferBlock(lView[TVIEW], tNode)) {
  38363. const lDetails = getLDeferBlockDetails(lView, tNode);
  38364. const tDetails = getTDeferBlockDetails(lView[TVIEW], tNode);
  38365. if (context.isIncrementalHydrationEnabled && tDetails.hydrateTriggers !== null) {
  38366. const deferBlockId = `d${context.deferBlocks.size}`;
  38367. if (tDetails.hydrateTriggers.has(7 /* DeferBlockTrigger.Never */)) {
  38368. isHydrateNeverBlock = true;
  38369. }
  38370. let rootNodes = [];
  38371. collectNativeNodesInLContainer(lContainer, rootNodes);
  38372. // Add defer block into info context.deferBlocks
  38373. const deferBlockInfo = {
  38374. [NUM_ROOT_NODES]: rootNodes.length,
  38375. [DEFER_BLOCK_STATE$1]: lDetails[DEFER_BLOCK_STATE],
  38376. };
  38377. const serializedTriggers = serializeHydrateTriggers(tDetails.hydrateTriggers);
  38378. if (serializedTriggers.length > 0) {
  38379. deferBlockInfo[DEFER_HYDRATE_TRIGGERS] = serializedTriggers;
  38380. }
  38381. if (parentDeferBlockId !== null) {
  38382. // Serialize parent id only when it's present.
  38383. deferBlockInfo[DEFER_PARENT_BLOCK_ID] = parentDeferBlockId;
  38384. }
  38385. context.deferBlocks.set(deferBlockId, deferBlockInfo);
  38386. const node = unwrapRNode(lContainer);
  38387. if (node !== undefined) {
  38388. if (node.nodeType === Node.COMMENT_NODE) {
  38389. annotateDeferBlockAnchorForHydration(node, deferBlockId);
  38390. }
  38391. }
  38392. else {
  38393. ngDevMode && validateNodeExists(node, childLView, tNode);
  38394. ngDevMode &&
  38395. validateMatchingNode(node, Node.COMMENT_NODE, null, childLView, tNode, true);
  38396. annotateDeferBlockAnchorForHydration(node, deferBlockId);
  38397. }
  38398. if (!isHydrateNeverBlock) {
  38399. // Add JSAction attributes for root nodes that use some hydration triggers
  38400. annotateDeferBlockRootNodesWithJsAction(tDetails, rootNodes, deferBlockId, context);
  38401. }
  38402. // Use current block id as parent for nested routes.
  38403. parentDeferBlockId = deferBlockId;
  38404. // Serialize extra info into the view object.
  38405. // TODO(incremental-hydration): this should be serialized and included at a different level
  38406. // (not at the view level).
  38407. serializedView[DEFER_BLOCK_ID] = deferBlockId;
  38408. }
  38409. // DEFER_BLOCK_STATE is used for reconciliation in hydration, both regular and incremental.
  38410. // We need to know which template is rendered when hydrating. So we serialize this state
  38411. // regardless of hydration type.
  38412. serializedView[DEFER_BLOCK_STATE$1] = lDetails[DEFER_BLOCK_STATE];
  38413. }
  38414. if (!isHydrateNeverBlock) {
  38415. Object.assign(serializedView, serializeLView(lContainer[i], parentDeferBlockId, context));
  38416. }
  38417. }
  38418. // Check if the previous view has the same shape (for example, it was
  38419. // produced by the *ngFor), in which case bump the counter on the previous
  38420. // view instead of including the same information again.
  38421. const currentViewAsString = JSON.stringify(serializedView);
  38422. if (views.length > 0 && currentViewAsString === lastViewAsString) {
  38423. const previousView = views[views.length - 1];
  38424. previousView[MULTIPLIER] ??= 1;
  38425. previousView[MULTIPLIER]++;
  38426. }
  38427. else {
  38428. // Record this view as most recently added.
  38429. lastViewAsString = currentViewAsString;
  38430. views.push(serializedView);
  38431. }
  38432. }
  38433. return views;
  38434. }
  38435. function serializeHydrateTriggers(triggerMap) {
  38436. const serializableDeferBlockTrigger = new Set([
  38437. 0 /* DeferBlockTrigger.Idle */,
  38438. 1 /* DeferBlockTrigger.Immediate */,
  38439. 2 /* DeferBlockTrigger.Viewport */,
  38440. 5 /* DeferBlockTrigger.Timer */,
  38441. ]);
  38442. let triggers = [];
  38443. for (let [trigger, details] of triggerMap) {
  38444. if (serializableDeferBlockTrigger.has(trigger)) {
  38445. if (details === null) {
  38446. triggers.push(trigger);
  38447. }
  38448. else {
  38449. triggers.push({ trigger, delay: details.delay });
  38450. }
  38451. }
  38452. }
  38453. return triggers;
  38454. }
  38455. /**
  38456. * Helper function to produce a node path (which navigation steps runtime logic
  38457. * needs to take to locate a node) and stores it in the `NODES` section of the
  38458. * current serialized view.
  38459. */
  38460. function appendSerializedNodePath(ngh, tNode, lView, excludedParentNodes) {
  38461. const noOffsetIndex = tNode.index - HEADER_OFFSET;
  38462. ngh[NODES] ??= {};
  38463. // Ensure we don't calculate the path multiple times.
  38464. ngh[NODES][noOffsetIndex] ??= calcPathForNode(tNode, lView, excludedParentNodes);
  38465. }
  38466. /**
  38467. * Helper function to append information about a disconnected node.
  38468. * This info is needed at runtime to avoid DOM lookups for this element
  38469. * and instead, the element would be created from scratch.
  38470. */
  38471. function appendDisconnectedNodeIndex(ngh, tNodeOrNoOffsetIndex) {
  38472. const noOffsetIndex = typeof tNodeOrNoOffsetIndex === 'number'
  38473. ? tNodeOrNoOffsetIndex
  38474. : tNodeOrNoOffsetIndex.index - HEADER_OFFSET;
  38475. ngh[DISCONNECTED_NODES] ??= [];
  38476. if (!ngh[DISCONNECTED_NODES].includes(noOffsetIndex)) {
  38477. ngh[DISCONNECTED_NODES].push(noOffsetIndex);
  38478. }
  38479. }
  38480. /**
  38481. * Serializes the lView data into a SerializedView object that will later be added
  38482. * to the TransferState storage and referenced using the `ngh` attribute on a host
  38483. * element.
  38484. *
  38485. * @param lView the lView we are serializing
  38486. * @param context the hydration context
  38487. * @returns the `SerializedView` object containing the data to be added to the host node
  38488. */
  38489. function serializeLView(lView, parentDeferBlockId = null, context) {
  38490. const ngh = {};
  38491. const tView = lView[TVIEW];
  38492. const i18nChildren = getOrComputeI18nChildren(tView, context);
  38493. const nativeElementsToEventTypes = context.shouldReplayEvents
  38494. ? collectDomEventsInfo(tView, lView, context.eventTypesToReplay)
  38495. : null;
  38496. // Iterate over DOM element references in an LView.
  38497. for (let i = HEADER_OFFSET; i < tView.bindingStartIndex; i++) {
  38498. const tNode = tView.data[i];
  38499. const noOffsetIndex = i - HEADER_OFFSET;
  38500. // Attempt to serialize any i18n data for the given slot. We do this first, as i18n
  38501. // has its own process for serialization.
  38502. const i18nData = trySerializeI18nBlock(lView, i, context);
  38503. if (i18nData) {
  38504. ngh[I18N_DATA] ??= {};
  38505. ngh[I18N_DATA][noOffsetIndex] = i18nData.caseQueue;
  38506. for (const nodeNoOffsetIndex of i18nData.disconnectedNodes) {
  38507. appendDisconnectedNodeIndex(ngh, nodeNoOffsetIndex);
  38508. }
  38509. for (const nodeNoOffsetIndex of i18nData.disjointNodes) {
  38510. const tNode = tView.data[nodeNoOffsetIndex + HEADER_OFFSET];
  38511. ngDevMode && assertTNode(tNode);
  38512. appendSerializedNodePath(ngh, tNode, lView, i18nChildren);
  38513. }
  38514. continue;
  38515. }
  38516. // Skip processing of a given slot in the following cases:
  38517. // - Local refs (e.g. <div #localRef>) take up an extra slot in LViews
  38518. // to store the same element. In this case, there is no information in
  38519. // a corresponding slot in TNode data structure.
  38520. // - When a slot contains something other than a TNode. For example, there
  38521. // might be some metadata information about a defer block or a control flow block.
  38522. if (!isTNodeShape(tNode)) {
  38523. continue;
  38524. }
  38525. // Skip any nodes that are in an i18n block but are considered detached (i.e. not
  38526. // present in the template). These nodes are disconnected from the DOM tree, and
  38527. // so we don't want to serialize any information about them.
  38528. if (isDetachedByI18n(tNode)) {
  38529. continue;
  38530. }
  38531. // Check if a native node that represents a given TNode is disconnected from the DOM tree.
  38532. // Such nodes must be excluded from the hydration (since the hydration won't be able to
  38533. // find them), so the TNode ids are collected and used at runtime to skip the hydration.
  38534. //
  38535. // This situation may happen during the content projection, when some nodes don't make it
  38536. // into one of the content projection slots (for example, when there is no default
  38537. // <ng-content /> slot in projector component's template).
  38538. if (isDisconnectedNode(tNode, lView) && isContentProjectedNode(tNode)) {
  38539. appendDisconnectedNodeIndex(ngh, tNode);
  38540. continue;
  38541. }
  38542. if (Array.isArray(tNode.projection)) {
  38543. for (const projectionHeadTNode of tNode.projection) {
  38544. // We may have `null`s in slots with no projected content.
  38545. if (!projectionHeadTNode)
  38546. continue;
  38547. if (!Array.isArray(projectionHeadTNode)) {
  38548. // If we process re-projected content (i.e. `<ng-content>`
  38549. // appears at projection location), skip annotations for this content
  38550. // since all DOM nodes in this projection were handled while processing
  38551. // a parent lView, which contains those nodes.
  38552. if (!isProjectionTNode(projectionHeadTNode) &&
  38553. !isInSkipHydrationBlock(projectionHeadTNode)) {
  38554. if (isDisconnectedNode(projectionHeadTNode, lView)) {
  38555. // Check whether this node is connected, since we may have a TNode
  38556. // in the data structure as a projection segment head, but the
  38557. // content projection slot might be disabled (e.g.
  38558. // <ng-content *ngIf="false" />).
  38559. appendDisconnectedNodeIndex(ngh, projectionHeadTNode);
  38560. }
  38561. else {
  38562. appendSerializedNodePath(ngh, projectionHeadTNode, lView, i18nChildren);
  38563. }
  38564. }
  38565. }
  38566. else {
  38567. // If a value is an array, it means that we are processing a projection
  38568. // where projectable nodes were passed in as DOM nodes (for example, when
  38569. // calling `ViewContainerRef.createComponent(CmpA, {projectableNodes: [...]})`).
  38570. //
  38571. // In this scenario, nodes can come from anywhere (either created manually,
  38572. // accessed via `document.querySelector`, etc) and may be in any state
  38573. // (attached or detached from the DOM tree). As a result, we can not reliably
  38574. // restore the state for such cases during hydration.
  38575. throw unsupportedProjectionOfDomNodes(unwrapRNode(lView[i]));
  38576. }
  38577. }
  38578. }
  38579. conditionallyAnnotateNodePath(ngh, tNode, lView, i18nChildren);
  38580. if (isLContainer(lView[i])) {
  38581. // Serialize information about a template.
  38582. const embeddedTView = tNode.tView;
  38583. if (embeddedTView !== null) {
  38584. ngh[TEMPLATES] ??= {};
  38585. ngh[TEMPLATES][noOffsetIndex] = getSsrId(embeddedTView);
  38586. }
  38587. // Serialize views within this LContainer.
  38588. const hostNode = lView[i][HOST]; // host node of this container
  38589. // LView[i][HOST] can be of 2 different types:
  38590. // - either a DOM node
  38591. // - or an array that represents an LView of a component
  38592. if (Array.isArray(hostNode)) {
  38593. // This is a component, serialize info about it.
  38594. const targetNode = unwrapRNode(hostNode);
  38595. if (!targetNode.hasAttribute(SKIP_HYDRATION_ATTR_NAME)) {
  38596. annotateHostElementForHydration(targetNode, hostNode, parentDeferBlockId, context);
  38597. }
  38598. }
  38599. ngh[CONTAINERS] ??= {};
  38600. ngh[CONTAINERS][noOffsetIndex] = serializeLContainer(lView[i], tNode, lView, parentDeferBlockId, context);
  38601. }
  38602. else if (Array.isArray(lView[i]) && !isLetDeclaration(tNode)) {
  38603. // This is a component, annotate the host node with an `ngh` attribute.
  38604. // Note: Let declarations that return an array are also storing an array in the LView,
  38605. // we need to exclude them.
  38606. const targetNode = unwrapRNode(lView[i][HOST]);
  38607. if (!targetNode.hasAttribute(SKIP_HYDRATION_ATTR_NAME)) {
  38608. annotateHostElementForHydration(targetNode, lView[i], parentDeferBlockId, context);
  38609. }
  38610. }
  38611. else {
  38612. // <ng-container> case
  38613. if (tNode.type & 8 /* TNodeType.ElementContainer */) {
  38614. // An <ng-container> is represented by the number of
  38615. // top-level nodes. This information is needed to skip over
  38616. // those nodes to reach a corresponding anchor node (comment node).
  38617. ngh[ELEMENT_CONTAINERS] ??= {};
  38618. ngh[ELEMENT_CONTAINERS][noOffsetIndex] = calcNumRootNodes(tView, lView, tNode.child);
  38619. }
  38620. else if (tNode.type & (16 /* TNodeType.Projection */ | 128 /* TNodeType.LetDeclaration */)) {
  38621. // Current TNode represents an `<ng-content>` slot or `@let` declaration,
  38622. // thus it has no DOM elements associated with it, so the **next sibling**
  38623. // node would not be able to find an anchor. In this case, use full path instead.
  38624. let nextTNode = tNode.next;
  38625. // Skip over all `<ng-content>` slots and `@let` declarations in a row.
  38626. while (nextTNode !== null &&
  38627. nextTNode.type & (16 /* TNodeType.Projection */ | 128 /* TNodeType.LetDeclaration */)) {
  38628. nextTNode = nextTNode.next;
  38629. }
  38630. if (nextTNode && !isInSkipHydrationBlock(nextTNode)) {
  38631. // Handle a tNode after the `<ng-content>` slot.
  38632. appendSerializedNodePath(ngh, nextTNode, lView, i18nChildren);
  38633. }
  38634. }
  38635. else if (tNode.type & 1 /* TNodeType.Text */) {
  38636. const rNode = unwrapRNode(lView[i]);
  38637. processTextNodeBeforeSerialization(context, rNode);
  38638. }
  38639. }
  38640. // Attach `jsaction` attribute to elements that have registered listeners,
  38641. // thus potentially having a need to do an event replay.
  38642. if (nativeElementsToEventTypes && tNode.type & 2 /* TNodeType.Element */) {
  38643. const nativeElement = unwrapRNode(lView[i]);
  38644. if (nativeElementsToEventTypes.has(nativeElement)) {
  38645. setJSActionAttributes(nativeElement, nativeElementsToEventTypes.get(nativeElement), parentDeferBlockId);
  38646. }
  38647. }
  38648. }
  38649. return ngh;
  38650. }
  38651. /**
  38652. * Serializes node location in cases when it's needed, specifically:
  38653. *
  38654. * 1. If `tNode.projectionNext` is different from `tNode.next` - it means that
  38655. * the next `tNode` after projection is different from the one in the original
  38656. * template. Since hydration relies on `tNode.next`, this serialized info
  38657. * is required to help runtime code find the node at the correct location.
  38658. * 2. In certain content projection-based use-cases, it's possible that only
  38659. * a content of a projected element is rendered. In this case, content nodes
  38660. * require an extra annotation, since runtime logic can't rely on parent-child
  38661. * connection to identify the location of a node.
  38662. */
  38663. function conditionallyAnnotateNodePath(ngh, tNode, lView, excludedParentNodes) {
  38664. if (isProjectionTNode(tNode)) {
  38665. // Do not annotate projection nodes (<ng-content />), since
  38666. // they don't have a corresponding DOM node representing them.
  38667. return;
  38668. }
  38669. // Handle case #1 described above.
  38670. if (tNode.projectionNext &&
  38671. tNode.projectionNext !== tNode.next &&
  38672. !isInSkipHydrationBlock(tNode.projectionNext)) {
  38673. appendSerializedNodePath(ngh, tNode.projectionNext, lView, excludedParentNodes);
  38674. }
  38675. // Handle case #2 described above.
  38676. // Note: we only do that for the first node (i.e. when `tNode.prev === null`),
  38677. // the rest of the nodes would rely on the current node location, so no extra
  38678. // annotation is needed.
  38679. if (tNode.prev === null &&
  38680. tNode.parent !== null &&
  38681. isDisconnectedNode(tNode.parent, lView) &&
  38682. !isDisconnectedNode(tNode, lView)) {
  38683. appendSerializedNodePath(ngh, tNode, lView, excludedParentNodes);
  38684. }
  38685. }
  38686. /**
  38687. * Determines whether a component instance that is represented
  38688. * by a given LView uses `ViewEncapsulation.ShadowDom`.
  38689. */
  38690. function componentUsesShadowDomEncapsulation(lView) {
  38691. const instance = lView[CONTEXT];
  38692. return instance?.constructor
  38693. ? getComponentDef(instance.constructor)?.encapsulation === ViewEncapsulation.ShadowDom
  38694. : false;
  38695. }
  38696. /**
  38697. * Annotates component host element for hydration:
  38698. * - by either adding the `ngh` attribute and collecting hydration-related info
  38699. * for the serialization and transferring to the client
  38700. * - or by adding the `ngSkipHydration` attribute in case Angular detects that
  38701. * component contents is not compatible with hydration.
  38702. *
  38703. * @param element The Host element to be annotated
  38704. * @param lView The associated LView
  38705. * @param context The hydration context
  38706. * @returns An index of serialized view from the transfer state object
  38707. * or `null` when a given component can not be serialized.
  38708. */
  38709. function annotateHostElementForHydration(element, lView, parentDeferBlockId, context) {
  38710. const renderer = lView[RENDERER];
  38711. if ((hasI18n(lView) && !isI18nHydrationSupportEnabled()) ||
  38712. componentUsesShadowDomEncapsulation(lView)) {
  38713. // Attach the skip hydration attribute if this component:
  38714. // - either has i18n blocks, since hydrating such blocks is not yet supported
  38715. // - or uses ShadowDom view encapsulation, since Domino doesn't support
  38716. // shadow DOM, so we can not guarantee that client and server representations
  38717. // would exactly match
  38718. renderer.setAttribute(element, SKIP_HYDRATION_ATTR_NAME, '');
  38719. return null;
  38720. }
  38721. else {
  38722. const ngh = serializeLView(lView, parentDeferBlockId, context);
  38723. const index = context.serializedViewCollection.add(ngh);
  38724. renderer.setAttribute(element, NGH_ATTR_NAME, index.toString());
  38725. return index;
  38726. }
  38727. }
  38728. /**
  38729. * Annotates defer block comment node for hydration:
  38730. *
  38731. * @param comment The Host element to be annotated
  38732. * @param deferBlockId the id of the target defer block
  38733. */
  38734. function annotateDeferBlockAnchorForHydration(comment, deferBlockId) {
  38735. comment.textContent = `ngh=${deferBlockId}`;
  38736. }
  38737. /**
  38738. * Physically inserts the comment nodes to ensure empty text nodes and adjacent
  38739. * text node separators are preserved after server serialization of the DOM.
  38740. * These get swapped back for empty text nodes or separators once hydration happens
  38741. * on the client.
  38742. *
  38743. * @param corruptedTextNodes The Map of text nodes to be replaced with comments
  38744. * @param doc The document
  38745. */
  38746. function insertCorruptedTextNodeMarkers(corruptedTextNodes, doc) {
  38747. for (const [textNode, marker] of corruptedTextNodes) {
  38748. textNode.after(doc.createComment(marker));
  38749. }
  38750. }
  38751. /**
  38752. * Detects whether a given TNode represents a node that
  38753. * is being content projected.
  38754. */
  38755. function isContentProjectedNode(tNode) {
  38756. let currentTNode = tNode;
  38757. while (currentTNode != null) {
  38758. // If we come across a component host node in parent nodes -
  38759. // this TNode is in the content projection section.
  38760. if (isComponentHost(currentTNode)) {
  38761. return true;
  38762. }
  38763. currentTNode = currentTNode.parent;
  38764. }
  38765. return false;
  38766. }
  38767. /**
  38768. * Incremental hydration requires that any defer block root node
  38769. * with interaction or hover triggers have all of their root nodes
  38770. * trigger hydration with those events. So we need to make sure all
  38771. * the root nodes of that block have the proper jsaction attribute
  38772. * to ensure hydration is triggered, since the content is dehydrated
  38773. */
  38774. function annotateDeferBlockRootNodesWithJsAction(tDetails, rootNodes, parentDeferBlockId, context) {
  38775. const actionList = convertHydrateTriggersToJsAction(tDetails.hydrateTriggers);
  38776. for (let et of actionList) {
  38777. context.eventTypesToReplay.regular.add(et);
  38778. }
  38779. if (actionList.length > 0) {
  38780. const elementNodes = rootNodes.filter((rn) => rn.nodeType === Node.ELEMENT_NODE);
  38781. for (let rNode of elementNodes) {
  38782. setJSActionAttributes(rNode, actionList, parentDeferBlockId);
  38783. }
  38784. }
  38785. }
  38786. /**
  38787. * Indicates whether the hydration-related code was added,
  38788. * prevents adding it multiple times.
  38789. */
  38790. let isHydrationSupportEnabled = false;
  38791. /**
  38792. * Indicates whether the i18n-related code was added,
  38793. * prevents adding it multiple times.
  38794. *
  38795. * Note: This merely controls whether the code is loaded,
  38796. * while `setIsI18nHydrationSupportEnabled` determines
  38797. * whether i18n blocks are serialized or hydrated.
  38798. */
  38799. let isI18nHydrationRuntimeSupportEnabled = false;
  38800. /**
  38801. * Indicates whether the incremental hydration code was added,
  38802. * prevents adding it multiple times.
  38803. */
  38804. let isIncrementalHydrationRuntimeSupportEnabled = false;
  38805. /**
  38806. * Defines a period of time that Angular waits for the `ApplicationRef.isStable` to emit `true`.
  38807. * If there was no event with the `true` value during this time, Angular reports a warning.
  38808. */
  38809. const APPLICATION_IS_STABLE_TIMEOUT = 10_000;
  38810. /**
  38811. * Brings the necessary hydration code in tree-shakable manner.
  38812. * The code is only present when the `provideClientHydration` is
  38813. * invoked. Otherwise, this code is tree-shaken away during the
  38814. * build optimization step.
  38815. *
  38816. * This technique allows us to swap implementations of methods so
  38817. * tree shaking works appropriately when hydration is disabled or
  38818. * enabled. It brings in the appropriate version of the method that
  38819. * supports hydration only when enabled.
  38820. */
  38821. function enableHydrationRuntimeSupport() {
  38822. if (!isHydrationSupportEnabled) {
  38823. isHydrationSupportEnabled = true;
  38824. enableRetrieveHydrationInfoImpl();
  38825. enableLocateOrCreateElementNodeImpl();
  38826. enableLocateOrCreateTextNodeImpl();
  38827. enableLocateOrCreateElementContainerNodeImpl();
  38828. enableLocateOrCreateContainerAnchorImpl();
  38829. enableLocateOrCreateContainerRefImpl();
  38830. enableFindMatchingDehydratedViewImpl();
  38831. enableApplyRootElementTransformImpl();
  38832. }
  38833. }
  38834. /**
  38835. * Brings the necessary i18n hydration code in tree-shakable manner.
  38836. * Similar to `enableHydrationRuntimeSupport`, the code is only
  38837. * present when `withI18nSupport` is invoked.
  38838. */
  38839. function enableI18nHydrationRuntimeSupport() {
  38840. if (!isI18nHydrationRuntimeSupportEnabled) {
  38841. isI18nHydrationRuntimeSupportEnabled = true;
  38842. enableLocateOrCreateI18nNodeImpl();
  38843. enablePrepareI18nBlockForHydrationImpl();
  38844. enableClaimDehydratedIcuCaseImpl();
  38845. }
  38846. }
  38847. /**
  38848. * Brings the necessary incremental hydration code in tree-shakable manner.
  38849. * Similar to `enableHydrationRuntimeSupport`, the code is only
  38850. * present when `enableIncrementalHydrationRuntimeSupport` is invoked.
  38851. */
  38852. function enableIncrementalHydrationRuntimeSupport() {
  38853. if (!isIncrementalHydrationRuntimeSupportEnabled) {
  38854. isIncrementalHydrationRuntimeSupportEnabled = true;
  38855. enableRetrieveDeferBlockDataImpl();
  38856. }
  38857. }
  38858. /**
  38859. * Outputs a message with hydration stats into a console.
  38860. */
  38861. function printHydrationStats(injector) {
  38862. const console = injector.get(Console);
  38863. const message = `Angular hydrated ${ngDevMode.hydratedComponents} component(s) ` +
  38864. `and ${ngDevMode.hydratedNodes} node(s), ` +
  38865. `${ngDevMode.componentsSkippedHydration} component(s) were skipped. ` +
  38866. (isIncrementalHydrationEnabled(injector)
  38867. ? `${ngDevMode.deferBlocksWithIncrementalHydration} defer block(s) were configured to use incremental hydration. `
  38868. : '') +
  38869. `Learn more at https://angular.dev/guide/hydration.`;
  38870. // tslint:disable-next-line:no-console
  38871. console.log(message);
  38872. }
  38873. /**
  38874. * Returns a Promise that is resolved when an application becomes stable.
  38875. */
  38876. function whenStableWithTimeout(appRef) {
  38877. const whenStablePromise = appRef.whenStable();
  38878. if (typeof ngDevMode !== 'undefined' && ngDevMode) {
  38879. const timeoutTime = APPLICATION_IS_STABLE_TIMEOUT;
  38880. const console = appRef.injector.get(Console);
  38881. const ngZone = appRef.injector.get(NgZone);
  38882. // The following call should not and does not prevent the app to become stable
  38883. // We cannot use RxJS timer here because the app would remain unstable.
  38884. // This also avoids an extra change detection cycle.
  38885. const timeoutId = ngZone.runOutsideAngular(() => {
  38886. return setTimeout(() => logWarningOnStableTimedout(timeoutTime, console), timeoutTime);
  38887. });
  38888. whenStablePromise.finally(() => clearTimeout(timeoutId));
  38889. }
  38890. return whenStablePromise;
  38891. }
  38892. /**
  38893. * Defines a name of an attribute that is added to the <body> tag
  38894. * in the `index.html` file in case a given route was configured
  38895. * with `RenderMode.Client`. 'cm' is an abbreviation for "Client Mode".
  38896. */
  38897. const CLIENT_RENDER_MODE_FLAG = 'ngcm';
  38898. /**
  38899. * Checks whether the `RenderMode.Client` was defined for the current route.
  38900. */
  38901. function isClientRenderModeEnabled() {
  38902. const doc = getDocument();
  38903. return ((typeof ngServerMode === 'undefined' || !ngServerMode) &&
  38904. doc.body.hasAttribute(CLIENT_RENDER_MODE_FLAG));
  38905. }
  38906. /**
  38907. * Returns a set of providers required to setup hydration support
  38908. * for an application that is server side rendered. This function is
  38909. * included into the `provideClientHydration` public API function from
  38910. * the `platform-browser` package.
  38911. *
  38912. * The function sets up an internal flag that would be recognized during
  38913. * the server side rendering time as well, so there is no need to
  38914. * configure or change anything in NgUniversal to enable the feature.
  38915. */
  38916. function withDomHydration() {
  38917. const providers = [
  38918. {
  38919. provide: IS_HYDRATION_DOM_REUSE_ENABLED,
  38920. useFactory: () => {
  38921. let isEnabled = true;
  38922. if (typeof ngServerMode === 'undefined' || !ngServerMode) {
  38923. // On the client, verify that the server response contains
  38924. // hydration annotations. Otherwise, keep hydration disabled.
  38925. const transferState = inject(TransferState, { optional: true });
  38926. isEnabled = !!transferState?.get(NGH_DATA_KEY, null);
  38927. }
  38928. if (isEnabled) {
  38929. performanceMarkFeature('NgHydration');
  38930. }
  38931. return isEnabled;
  38932. },
  38933. },
  38934. {
  38935. provide: ENVIRONMENT_INITIALIZER,
  38936. useValue: () => {
  38937. // i18n support is enabled by calling withI18nSupport(), but there's
  38938. // no way to turn it off (e.g. for tests), so we turn it off by default.
  38939. setIsI18nHydrationSupportEnabled(false);
  38940. if (typeof ngServerMode !== 'undefined' && ngServerMode) {
  38941. // Since this function is used across both server and client,
  38942. // make sure that the runtime code is only added when invoked
  38943. // on the client (see the `enableHydrationRuntimeSupport` function
  38944. // call below).
  38945. return;
  38946. }
  38947. if (inject(IS_HYDRATION_DOM_REUSE_ENABLED)) {
  38948. verifySsrContentsIntegrity(getDocument());
  38949. enableHydrationRuntimeSupport();
  38950. }
  38951. else if (typeof ngDevMode !== 'undefined' && ngDevMode && !isClientRenderModeEnabled()) {
  38952. const console = inject(Console);
  38953. const message = formatRuntimeError(-505 /* RuntimeErrorCode.MISSING_HYDRATION_ANNOTATIONS */, 'Angular hydration was requested on the client, but there was no ' +
  38954. 'serialized information present in the server response, ' +
  38955. 'thus hydration was not enabled. ' +
  38956. 'Make sure the `provideClientHydration()` is included into the list ' +
  38957. 'of providers in the server part of the application configuration.');
  38958. console.warn(message);
  38959. }
  38960. },
  38961. multi: true,
  38962. },
  38963. ];
  38964. if (typeof ngServerMode === 'undefined' || !ngServerMode) {
  38965. providers.push({
  38966. provide: PRESERVE_HOST_CONTENT,
  38967. useFactory: () => {
  38968. // Preserve host element content only in a browser
  38969. // environment and when hydration is configured properly.
  38970. // On a server, an application is rendered from scratch,
  38971. // so the host content needs to be empty.
  38972. return inject(IS_HYDRATION_DOM_REUSE_ENABLED);
  38973. },
  38974. }, {
  38975. provide: APP_BOOTSTRAP_LISTENER,
  38976. useFactory: () => {
  38977. if (inject(IS_HYDRATION_DOM_REUSE_ENABLED)) {
  38978. const appRef = inject(ApplicationRef);
  38979. return () => {
  38980. // Wait until an app becomes stable and cleanup all views that
  38981. // were not claimed during the application bootstrap process.
  38982. // The timing is similar to when we start the serialization process
  38983. // on the server.
  38984. //
  38985. // Note: the cleanup task *MUST* be scheduled within the Angular zone in Zone apps
  38986. // to ensure that change detection is properly run afterward.
  38987. whenStableWithTimeout(appRef).then(() => {
  38988. // Note: we have to check whether the application is destroyed before
  38989. // performing other operations with the `injector`.
  38990. // The application may be destroyed **before** it becomes stable, so when
  38991. // the `whenStableWithTimeout` resolves, the injector might already be in
  38992. // a destroyed state. Thus, calling `injector.get` would throw an error
  38993. // indicating that the injector has already been destroyed.
  38994. if (appRef.destroyed) {
  38995. return;
  38996. }
  38997. cleanupDehydratedViews(appRef);
  38998. if (typeof ngDevMode !== 'undefined' && ngDevMode) {
  38999. countBlocksSkippedByHydration(appRef.injector);
  39000. printHydrationStats(appRef.injector);
  39001. }
  39002. });
  39003. };
  39004. }
  39005. return () => { }; // noop
  39006. },
  39007. multi: true,
  39008. });
  39009. }
  39010. return makeEnvironmentProviders(providers);
  39011. }
  39012. /**
  39013. * Returns a set of providers required to setup support for i18n hydration.
  39014. * Requires hydration to be enabled separately.
  39015. */
  39016. function withI18nSupport() {
  39017. return [
  39018. {
  39019. provide: IS_I18N_HYDRATION_ENABLED,
  39020. useFactory: () => inject(IS_HYDRATION_DOM_REUSE_ENABLED),
  39021. },
  39022. {
  39023. provide: ENVIRONMENT_INITIALIZER,
  39024. useValue: () => {
  39025. if (inject(IS_HYDRATION_DOM_REUSE_ENABLED)) {
  39026. enableI18nHydrationRuntimeSupport();
  39027. setIsI18nHydrationSupportEnabled(true);
  39028. performanceMarkFeature('NgI18nHydration');
  39029. }
  39030. },
  39031. multi: true,
  39032. },
  39033. ];
  39034. }
  39035. /**
  39036. * Returns a set of providers required to setup support for incremental hydration.
  39037. * Requires hydration to be enabled separately.
  39038. * Enabling incremental hydration also enables event replay for the entire app.
  39039. *
  39040. * @developerPreview
  39041. */
  39042. function withIncrementalHydration() {
  39043. const providers = [
  39044. withEventReplay(),
  39045. {
  39046. provide: IS_INCREMENTAL_HYDRATION_ENABLED,
  39047. useValue: true,
  39048. },
  39049. {
  39050. provide: DEHYDRATED_BLOCK_REGISTRY,
  39051. useClass: DehydratedBlockRegistry,
  39052. },
  39053. {
  39054. provide: ENVIRONMENT_INITIALIZER,
  39055. useValue: () => {
  39056. enableIncrementalHydrationRuntimeSupport();
  39057. performanceMarkFeature('NgIncrementalHydration');
  39058. },
  39059. multi: true,
  39060. },
  39061. ];
  39062. if (typeof ngServerMode === 'undefined' || !ngServerMode) {
  39063. providers.push({
  39064. provide: APP_BOOTSTRAP_LISTENER,
  39065. useFactory: () => {
  39066. const injector = inject(Injector);
  39067. const doc = getDocument();
  39068. return () => {
  39069. const deferBlockData = processBlockData(injector);
  39070. const commentsByBlockId = gatherDeferBlocksCommentNodes(doc, doc.body);
  39071. processAndInitTriggers(injector, deferBlockData, commentsByBlockId);
  39072. appendDeferBlocksToJSActionMap(doc, injector);
  39073. };
  39074. },
  39075. multi: true,
  39076. });
  39077. }
  39078. return providers;
  39079. }
  39080. /**
  39081. *
  39082. * @param time The time in ms until the stable timedout warning message is logged
  39083. */
  39084. function logWarningOnStableTimedout(time, console) {
  39085. const message = `Angular hydration expected the ApplicationRef.isStable() to emit \`true\`, but it ` +
  39086. `didn't happen within ${time}ms. Angular hydration logic depends on the application becoming stable ` +
  39087. `as a signal to complete hydration process.`;
  39088. console.warn(formatRuntimeError(-506 /* RuntimeErrorCode.HYDRATION_STABLE_TIMEDOUT */, message));
  39089. }
  39090. /**
  39091. * Transforms a value (typically a string) to a boolean.
  39092. * Intended to be used as a transform function of an input.
  39093. *
  39094. * @usageNotes
  39095. * ```ts
  39096. * @Input({ transform: booleanAttribute }) status!: boolean;
  39097. * ```
  39098. * @param value Value to be transformed.
  39099. *
  39100. * @publicApi
  39101. */
  39102. function booleanAttribute(value) {
  39103. return typeof value === 'boolean' ? value : value != null && value !== 'false';
  39104. }
  39105. /**
  39106. * Transforms a value (typically a string) to a number.
  39107. * Intended to be used as a transform function of an input.
  39108. * @param value Value to be transformed.
  39109. * @param fallbackValue Value to use if the provided value can't be parsed as a number.
  39110. *
  39111. * @usageNotes
  39112. * ```ts
  39113. * @Input({ transform: numberAttribute }) id!: number;
  39114. * ```
  39115. *
  39116. * @publicApi
  39117. */
  39118. function numberAttribute(value, fallbackValue = NaN) {
  39119. // parseFloat(value) handles most of the cases we're interested in (it treats null, empty string,
  39120. // and other non-number values as NaN, where Number just uses 0) but it considers the string
  39121. // '123hello' to be a valid number. Therefore we also check if Number(value) is NaN.
  39122. const isNumberValue = !isNaN(parseFloat(value)) && !isNaN(Number(value));
  39123. return isNumberValue ? Number(value) : fallbackValue;
  39124. }
  39125. const PERFORMANCE_MARK_PREFIX = '🅰️';
  39126. let enablePerfLogging = false;
  39127. /**
  39128. * Function that will start measuring against the performance API
  39129. * Should be used in pair with stopMeasuring
  39130. */
  39131. function startMeasuring(label) {
  39132. if (!enablePerfLogging) {
  39133. return;
  39134. }
  39135. const { startLabel } = labels(label);
  39136. /* tslint:disable:ban */
  39137. performance.mark(startLabel);
  39138. /* tslint:enable:ban */
  39139. }
  39140. /**
  39141. * Function that will stop measuring against the performance API
  39142. * Should be used in pair with stopMeasuring
  39143. */
  39144. function stopMeasuring(label) {
  39145. if (!enablePerfLogging) {
  39146. return;
  39147. }
  39148. const { startLabel, labelName, endLabel } = labels(label);
  39149. /* tslint:disable:ban */
  39150. performance.mark(endLabel);
  39151. performance.measure(labelName, startLabel, endLabel);
  39152. performance.clearMarks(startLabel);
  39153. performance.clearMarks(endLabel);
  39154. /* tslint:enable:ban */
  39155. }
  39156. function labels(label) {
  39157. const labelName = `${PERFORMANCE_MARK_PREFIX}:${label}`;
  39158. return {
  39159. labelName,
  39160. startLabel: `start:${labelName}`,
  39161. endLabel: `end:${labelName}`,
  39162. };
  39163. }
  39164. let warningLogged = false;
  39165. /**
  39166. * This enables an internal performance profiler
  39167. *
  39168. * It should not be imported in application code
  39169. */
  39170. function enableProfiling() {
  39171. if (!warningLogged &&
  39172. (typeof performance === 'undefined' || !performance.mark || !performance.measure)) {
  39173. warningLogged = true;
  39174. console.warn('Performance API is not supported on this platform');
  39175. return;
  39176. }
  39177. enablePerfLogging = true;
  39178. }
  39179. function disableProfiling() {
  39180. enablePerfLogging = false;
  39181. }
  39182. /**
  39183. * Execute an arbitrary function in a non-reactive (non-tracking) context. The executed function
  39184. * can, optionally, return a value.
  39185. */
  39186. function untracked(nonReactiveReadsFn) {
  39187. return untracked$1(nonReactiveReadsFn);
  39188. }
  39189. /**
  39190. * Create a computed `Signal` which derives a reactive value from an expression.
  39191. */
  39192. function computed(computation, options) {
  39193. const getter = createComputed(computation, options?.equal);
  39194. if (ngDevMode) {
  39195. getter.toString = () => `[Computed: ${getter()}]`;
  39196. getter[SIGNAL].debugName = options?.debugName;
  39197. }
  39198. return getter;
  39199. }
  39200. class MicrotaskEffectScheduler extends ZoneAwareEffectScheduler {
  39201. pendingTasks = inject(PendingTasksInternal);
  39202. taskId = null;
  39203. schedule(effect) {
  39204. // Check whether there are any pending effects _before_ queueing in the base class.
  39205. super.schedule(effect);
  39206. if (this.taskId === null) {
  39207. this.taskId = this.pendingTasks.add();
  39208. queueMicrotask(() => this.flush());
  39209. }
  39210. }
  39211. flush() {
  39212. try {
  39213. super.flush();
  39214. }
  39215. finally {
  39216. if (this.taskId !== null) {
  39217. this.pendingTasks.remove(this.taskId);
  39218. this.taskId = null;
  39219. }
  39220. }
  39221. }
  39222. /** @nocollapse */
  39223. static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
  39224. token: MicrotaskEffectScheduler,
  39225. providedIn: 'root',
  39226. factory: () => new MicrotaskEffectScheduler(),
  39227. });
  39228. }
  39229. /**
  39230. * Core reactive node for an Angular effect.
  39231. *
  39232. * `EffectHandle` combines the reactive graph's `Watch` base node for effects with the framework's
  39233. * scheduling abstraction (`MicrotaskEffectScheduler`) as well as automatic cleanup via `DestroyRef`
  39234. * if available/requested.
  39235. */
  39236. class EffectHandle {
  39237. scheduler;
  39238. effectFn;
  39239. zone;
  39240. injector;
  39241. unregisterOnDestroy;
  39242. watcher;
  39243. constructor(scheduler, effectFn, zone, destroyRef, injector, allowSignalWrites) {
  39244. this.scheduler = scheduler;
  39245. this.effectFn = effectFn;
  39246. this.zone = zone;
  39247. this.injector = injector;
  39248. this.watcher = createWatch((onCleanup) => this.runEffect(onCleanup), () => this.schedule(), allowSignalWrites);
  39249. this.unregisterOnDestroy = destroyRef?.onDestroy(() => this.destroy());
  39250. }
  39251. runEffect(onCleanup) {
  39252. try {
  39253. this.effectFn(onCleanup);
  39254. }
  39255. catch (err) {
  39256. // Inject the `ErrorHandler` here in order to avoid circular DI error
  39257. // if the effect is used inside of a custom `ErrorHandler`.
  39258. const errorHandler = this.injector.get(ErrorHandler, null, { optional: true });
  39259. errorHandler?.handleError(err);
  39260. }
  39261. }
  39262. run() {
  39263. this.watcher.run();
  39264. }
  39265. schedule() {
  39266. this.scheduler.schedule(this);
  39267. }
  39268. destroy() {
  39269. this.watcher.destroy();
  39270. this.unregisterOnDestroy?.();
  39271. // Note: if the effect is currently scheduled, it's not un-scheduled, and so the scheduler will
  39272. // retain a reference to it. Attempting to execute it will be a no-op.
  39273. }
  39274. }
  39275. // Just used for the name for the debug error below.
  39276. function effect$1() { }
  39277. /**
  39278. * Create a global `Effect` for the given reactive function.
  39279. */
  39280. function microtaskEffect(effectFn, options) {
  39281. ngDevMode &&
  39282. assertNotInReactiveContext(effect$1, 'Call `effect` outside of a reactive context. For example, schedule the ' +
  39283. 'effect inside the component constructor.');
  39284. !options?.injector && assertInInjectionContext(effect$1);
  39285. const injector = options?.injector ?? inject(Injector);
  39286. const destroyRef = options?.manualCleanup !== true ? injector.get(DestroyRef) : null;
  39287. const handle = new EffectHandle(injector.get(MicrotaskEffectScheduler), effectFn, typeof Zone === 'undefined' ? null : Zone.current, destroyRef, injector, options?.allowSignalWrites ?? false);
  39288. // Effects need to be marked dirty manually to trigger their initial run. The timing of this
  39289. // marking matters, because the effects may read signals that track component inputs, which are
  39290. // only available after those components have had their first update pass.
  39291. //
  39292. // We inject `ChangeDetectorRef` optionally, to determine whether this effect is being created in
  39293. // the context of a component or not. If it is, then we check whether the component has already
  39294. // run its update pass, and defer the effect's initial scheduling until the update pass if it
  39295. // hasn't already run.
  39296. const cdr = injector.get(ChangeDetectorRef, null, { optional: true });
  39297. if (!cdr || !(cdr._lView[FLAGS] & 8 /* LViewFlags.FirstLViewPass */)) {
  39298. // This effect is either not running in a view injector, or the view has already
  39299. // undergone its first change detection pass, which is necessary for any required inputs to be
  39300. // set.
  39301. handle.watcher.notify();
  39302. }
  39303. else {
  39304. // Delay the initialization of the effect until the view is fully initialized.
  39305. (cdr._lView[EFFECTS_TO_SCHEDULE] ??= []).push(handle.watcher.notify);
  39306. }
  39307. return handle;
  39308. }
  39309. class EffectRefImpl {
  39310. [SIGNAL];
  39311. constructor(node) {
  39312. this[SIGNAL] = node;
  39313. }
  39314. destroy() {
  39315. this[SIGNAL].destroy();
  39316. }
  39317. }
  39318. /**
  39319. * Registers an "effect" that will be scheduled & executed whenever the signals that it reads
  39320. * changes.
  39321. *
  39322. * Angular has two different kinds of effect: component effects and root effects. Component effects
  39323. * are created when `effect()` is called from a component, directive, or within a service of a
  39324. * component/directive. Root effects are created when `effect()` is called from outside the
  39325. * component tree, such as in a root service, or when the `forceRoot` option is provided.
  39326. *
  39327. * The two effect types differ in their timing. Component effects run as a component lifecycle
  39328. * event during Angular's synchronization (change detection) process, and can safely read input
  39329. * signals or create/destroy views that depend on component state. Root effects run as microtasks
  39330. * and have no connection to the component tree or change detection.
  39331. *
  39332. * `effect()` must be run in injection context, unless the `injector` option is manually specified.
  39333. *
  39334. * @developerPreview
  39335. */
  39336. function effect(effectFn, options) {
  39337. ngDevMode &&
  39338. assertNotInReactiveContext(effect, 'Call `effect` outside of a reactive context. For example, schedule the ' +
  39339. 'effect inside the component constructor.');
  39340. !options?.injector && assertInInjectionContext(effect);
  39341. if (ngDevMode && options?.allowSignalWrites !== undefined) {
  39342. console.warn(`The 'allowSignalWrites' flag is deprecated and no longer impacts effect() (writes are always allowed)`);
  39343. }
  39344. const injector = options?.injector ?? inject(Injector);
  39345. let destroyRef = options?.manualCleanup !== true ? injector.get(DestroyRef) : null;
  39346. let node;
  39347. const viewContext = injector.get(ViewContext, null, { optional: true });
  39348. const notifier = injector.get(ChangeDetectionScheduler);
  39349. if (viewContext !== null && !options?.forceRoot) {
  39350. // This effect was created in the context of a view, and will be associated with the view.
  39351. node = createViewEffect(viewContext.view, notifier, effectFn);
  39352. if (destroyRef instanceof NodeInjectorDestroyRef && destroyRef._lView === viewContext.view) {
  39353. // The effect is being created in the same view as the `DestroyRef` references, so it will be
  39354. // automatically destroyed without the need for an explicit `DestroyRef` registration.
  39355. destroyRef = null;
  39356. }
  39357. }
  39358. else {
  39359. // This effect was created outside the context of a view, and will be scheduled independently.
  39360. node = createRootEffect(effectFn, injector.get(EffectScheduler), notifier);
  39361. }
  39362. node.injector = injector;
  39363. if (destroyRef !== null) {
  39364. // If we need to register for cleanup, do that here.
  39365. node.onDestroyFn = destroyRef.onDestroy(() => node.destroy());
  39366. }
  39367. const effectRef = new EffectRefImpl(node);
  39368. if (ngDevMode) {
  39369. node.debugName = options?.debugName ?? '';
  39370. const prevInjectorProfilerContext = setInjectorProfilerContext({ injector, token: null });
  39371. try {
  39372. emitEffectCreatedEvent(effectRef);
  39373. }
  39374. finally {
  39375. setInjectorProfilerContext(prevInjectorProfilerContext);
  39376. }
  39377. }
  39378. return effectRef;
  39379. }
  39380. const BASE_EFFECT_NODE =
  39381. /* @__PURE__ */ (() => ({
  39382. ...REACTIVE_NODE,
  39383. consumerIsAlwaysLive: true,
  39384. consumerAllowSignalWrites: true,
  39385. dirty: true,
  39386. hasRun: false,
  39387. cleanupFns: undefined,
  39388. zone: null,
  39389. kind: 'effect',
  39390. onDestroyFn: noop,
  39391. run() {
  39392. this.dirty = false;
  39393. if (ngDevMode && isInNotificationPhase()) {
  39394. throw new Error(`Schedulers cannot synchronously execute watches while scheduling.`);
  39395. }
  39396. if (this.hasRun && !consumerPollProducersForChange(this)) {
  39397. return;
  39398. }
  39399. this.hasRun = true;
  39400. const registerCleanupFn = (cleanupFn) => (this.cleanupFns ??= []).push(cleanupFn);
  39401. const prevNode = consumerBeforeComputation(this);
  39402. // We clear `setIsRefreshingViews` so that `markForCheck()` within the body of an effect will
  39403. // cause CD to reach the component in question.
  39404. const prevRefreshingViews = setIsRefreshingViews(false);
  39405. try {
  39406. this.maybeCleanup();
  39407. this.fn(registerCleanupFn);
  39408. }
  39409. finally {
  39410. setIsRefreshingViews(prevRefreshingViews);
  39411. consumerAfterComputation(this, prevNode);
  39412. }
  39413. },
  39414. maybeCleanup() {
  39415. if (!this.cleanupFns?.length) {
  39416. return;
  39417. }
  39418. try {
  39419. // Attempt to run the cleanup functions. Regardless of failure or success, we consider
  39420. // cleanup "completed" and clear the list for the next run of the effect. Note that an error
  39421. // from the cleanup function will still crash the current run of the effect.
  39422. while (this.cleanupFns.length) {
  39423. this.cleanupFns.pop()();
  39424. }
  39425. }
  39426. finally {
  39427. this.cleanupFns = [];
  39428. }
  39429. },
  39430. }))();
  39431. const ROOT_EFFECT_NODE =
  39432. /* @__PURE__ */ (() => ({
  39433. ...BASE_EFFECT_NODE,
  39434. consumerMarkedDirty() {
  39435. this.scheduler.schedule(this);
  39436. this.notifier.notify(12 /* NotificationSource.RootEffect */);
  39437. },
  39438. destroy() {
  39439. consumerDestroy(this);
  39440. this.onDestroyFn();
  39441. this.maybeCleanup();
  39442. this.scheduler.remove(this);
  39443. },
  39444. }))();
  39445. const VIEW_EFFECT_NODE =
  39446. /* @__PURE__ */ (() => ({
  39447. ...BASE_EFFECT_NODE,
  39448. consumerMarkedDirty() {
  39449. this.view[FLAGS] |= 8192 /* LViewFlags.HasChildViewsToRefresh */;
  39450. markAncestorsForTraversal(this.view);
  39451. this.notifier.notify(13 /* NotificationSource.ViewEffect */);
  39452. },
  39453. destroy() {
  39454. consumerDestroy(this);
  39455. this.onDestroyFn();
  39456. this.maybeCleanup();
  39457. this.view[EFFECTS]?.delete(this);
  39458. },
  39459. }))();
  39460. function createViewEffect(view, notifier, fn) {
  39461. const node = Object.create(VIEW_EFFECT_NODE);
  39462. node.view = view;
  39463. node.zone = typeof Zone !== 'undefined' ? Zone.current : null;
  39464. node.notifier = notifier;
  39465. node.fn = fn;
  39466. view[EFFECTS] ??= new Set();
  39467. view[EFFECTS].add(node);
  39468. node.consumerMarkedDirty(node);
  39469. return node;
  39470. }
  39471. function createRootEffect(fn, scheduler, notifier) {
  39472. const node = Object.create(ROOT_EFFECT_NODE);
  39473. node.fn = fn;
  39474. node.scheduler = scheduler;
  39475. node.notifier = notifier;
  39476. node.zone = typeof Zone !== 'undefined' ? Zone.current : null;
  39477. node.scheduler.schedule(node);
  39478. node.notifier.notify(12 /* NotificationSource.RootEffect */);
  39479. return node;
  39480. }
  39481. /**
  39482. * Status of a `Resource`.
  39483. *
  39484. * @experimental
  39485. */
  39486. var ResourceStatus;
  39487. (function (ResourceStatus) {
  39488. /**
  39489. * The resource has no valid request and will not perform any loading.
  39490. *
  39491. * `value()` will be `undefined`.
  39492. */
  39493. ResourceStatus[ResourceStatus["Idle"] = 0] = "Idle";
  39494. /**
  39495. * Loading failed with an error.
  39496. *
  39497. * `value()` will be `undefined`.
  39498. */
  39499. ResourceStatus[ResourceStatus["Error"] = 1] = "Error";
  39500. /**
  39501. * The resource is currently loading a new value as a result of a change in its `request`.
  39502. *
  39503. * `value()` will be `undefined`.
  39504. */
  39505. ResourceStatus[ResourceStatus["Loading"] = 2] = "Loading";
  39506. /**
  39507. * The resource is currently reloading a fresh value for the same request.
  39508. *
  39509. * `value()` will continue to return the previously fetched value during the reloading operation.
  39510. */
  39511. ResourceStatus[ResourceStatus["Reloading"] = 3] = "Reloading";
  39512. /**
  39513. * Loading has completed and the resource has the value returned from the loader.
  39514. */
  39515. ResourceStatus[ResourceStatus["Resolved"] = 4] = "Resolved";
  39516. /**
  39517. * The resource's value was set locally via `.set()` or `.update()`.
  39518. */
  39519. ResourceStatus[ResourceStatus["Local"] = 5] = "Local";
  39520. })(ResourceStatus || (ResourceStatus = {}));
  39521. const identityFn = (v) => v;
  39522. function linkedSignal(optionsOrComputation, options) {
  39523. if (typeof optionsOrComputation === 'function') {
  39524. const getter = createLinkedSignal(optionsOrComputation, (identityFn), options?.equal);
  39525. return upgradeLinkedSignalGetter(getter);
  39526. }
  39527. else {
  39528. const getter = createLinkedSignal(optionsOrComputation.source, optionsOrComputation.computation, optionsOrComputation.equal);
  39529. return upgradeLinkedSignalGetter(getter);
  39530. }
  39531. }
  39532. function upgradeLinkedSignalGetter(getter) {
  39533. if (ngDevMode) {
  39534. getter.toString = () => `[LinkedSignal: ${getter()}]`;
  39535. }
  39536. const node = getter[SIGNAL];
  39537. const upgradedGetter = getter;
  39538. upgradedGetter.set = (newValue) => linkedSignalSetFn(node, newValue);
  39539. upgradedGetter.update = (updateFn) => linkedSignalUpdateFn(node, updateFn);
  39540. upgradedGetter.asReadonly = signalAsReadonlyFn.bind(getter);
  39541. return upgradedGetter;
  39542. }
  39543. function resource(options) {
  39544. options?.injector || assertInInjectionContext(resource);
  39545. const request = (options.request ?? (() => null));
  39546. return new ResourceImpl(request, getLoader(options), options.defaultValue, options.equal ? wrapEqualityFn(options.equal) : undefined, options.injector ?? inject(Injector));
  39547. }
  39548. /**
  39549. * Base class which implements `.value` as a `WritableSignal` by delegating `.set` and `.update`.
  39550. */
  39551. class BaseWritableResource {
  39552. value;
  39553. constructor(value) {
  39554. this.value = value;
  39555. this.value.set = this.set.bind(this);
  39556. this.value.update = this.update.bind(this);
  39557. this.value.asReadonly = signalAsReadonlyFn;
  39558. }
  39559. update(updateFn) {
  39560. this.set(updateFn(untracked(this.value)));
  39561. }
  39562. isLoading = computed(() => this.status() === ResourceStatus.Loading || this.status() === ResourceStatus.Reloading);
  39563. hasValue() {
  39564. return this.value() !== undefined;
  39565. }
  39566. asReadonly() {
  39567. return this;
  39568. }
  39569. }
  39570. /**
  39571. * Implementation for `resource()` which uses a `linkedSignal` to manage the resource's state.
  39572. */
  39573. class ResourceImpl extends BaseWritableResource {
  39574. loaderFn;
  39575. defaultValue;
  39576. equal;
  39577. pendingTasks;
  39578. /**
  39579. * The current state of the resource. Status, value, and error are derived from this.
  39580. */
  39581. state;
  39582. /**
  39583. * Combines the current request with a reload counter which allows the resource to be reloaded on
  39584. * imperative command.
  39585. */
  39586. extRequest;
  39587. effectRef;
  39588. pendingController;
  39589. resolvePendingTask = undefined;
  39590. destroyed = false;
  39591. constructor(request, loaderFn, defaultValue, equal, injector) {
  39592. super(
  39593. // Feed a computed signal for the value to `BaseWritableResource`, which will upgrade it to a
  39594. // `WritableSignal` that delegates to `ResourceImpl.set`.
  39595. computed(() => {
  39596. const streamValue = this.state().stream?.();
  39597. return streamValue && isResolved(streamValue) ? streamValue.value : this.defaultValue;
  39598. }, { equal }));
  39599. this.loaderFn = loaderFn;
  39600. this.defaultValue = defaultValue;
  39601. this.equal = equal;
  39602. // Extend `request()` to include a writable reload signal.
  39603. this.extRequest = linkedSignal({
  39604. source: request,
  39605. computation: (request) => ({ request, reload: 0 }),
  39606. });
  39607. // The main resource state is managed in a `linkedSignal`, which allows the resource to change
  39608. // state instantaneously when the request signal changes.
  39609. this.state = linkedSignal({
  39610. // Whenever the request changes,
  39611. source: this.extRequest,
  39612. // Compute the state of the resource given a change in status.
  39613. computation: (extRequest, previous) => {
  39614. const status = extRequest.request === undefined ? ResourceStatus.Idle : ResourceStatus.Loading;
  39615. if (!previous) {
  39616. return {
  39617. extRequest,
  39618. status,
  39619. previousStatus: ResourceStatus.Idle,
  39620. stream: undefined,
  39621. };
  39622. }
  39623. else {
  39624. return {
  39625. extRequest,
  39626. status,
  39627. previousStatus: projectStatusOfState(previous.value),
  39628. // If the request hasn't changed, keep the previous stream.
  39629. stream: previous.value.extRequest.request === extRequest.request
  39630. ? previous.value.stream
  39631. : undefined,
  39632. };
  39633. }
  39634. },
  39635. });
  39636. this.effectRef = effect(this.loadEffect.bind(this), {
  39637. injector,
  39638. manualCleanup: true,
  39639. });
  39640. this.pendingTasks = injector.get(PendingTasks);
  39641. // Cancel any pending request when the resource itself is destroyed.
  39642. injector.get(DestroyRef).onDestroy(() => this.destroy());
  39643. }
  39644. status = computed(() => projectStatusOfState(this.state()));
  39645. error = computed(() => {
  39646. const stream = this.state().stream?.();
  39647. return stream && !isResolved(stream) ? stream.error : undefined;
  39648. });
  39649. /**
  39650. * Called either directly via `WritableResource.set` or via `.value.set()`.
  39651. */
  39652. set(value) {
  39653. if (this.destroyed) {
  39654. return;
  39655. }
  39656. const current = untracked(this.value);
  39657. const state = untracked(this.state);
  39658. if (state.status === ResourceStatus.Local &&
  39659. (this.equal ? this.equal(current, value) : current === value)) {
  39660. return;
  39661. }
  39662. // Enter Local state with the user-defined value.
  39663. this.state.set({
  39664. extRequest: state.extRequest,
  39665. status: ResourceStatus.Local,
  39666. previousStatus: ResourceStatus.Local,
  39667. stream: signal({ value }),
  39668. });
  39669. // We're departing from whatever state the resource was in previously, so cancel any in-progress
  39670. // loading operations.
  39671. this.abortInProgressLoad();
  39672. }
  39673. reload() {
  39674. // We don't want to restart in-progress loads.
  39675. const { status } = untracked(this.state);
  39676. if (status === ResourceStatus.Idle || status === ResourceStatus.Loading) {
  39677. return false;
  39678. }
  39679. // Increment the request reload to trigger the `state` linked signal to switch us to `Reload`
  39680. this.extRequest.update(({ request, reload }) => ({ request, reload: reload + 1 }));
  39681. return true;
  39682. }
  39683. destroy() {
  39684. this.destroyed = true;
  39685. this.effectRef.destroy();
  39686. this.abortInProgressLoad();
  39687. // Destroyed resources enter Idle state.
  39688. this.state.set({
  39689. extRequest: { request: undefined, reload: 0 },
  39690. status: ResourceStatus.Idle,
  39691. previousStatus: ResourceStatus.Idle,
  39692. stream: undefined,
  39693. });
  39694. }
  39695. async loadEffect() {
  39696. const extRequest = this.extRequest();
  39697. // Capture the previous status before any state transitions. Note that this is `untracked` since
  39698. // we do not want the effect to depend on the state of the resource, only on the request.
  39699. const { status: currentStatus, previousStatus } = untracked(this.state);
  39700. if (extRequest.request === undefined) {
  39701. // Nothing to load (and we should already be in a non-loading state).
  39702. return;
  39703. }
  39704. else if (currentStatus !== ResourceStatus.Loading) {
  39705. // We're not in a loading or reloading state, so this loading request is stale.
  39706. return;
  39707. }
  39708. // Cancel any previous loading attempts.
  39709. this.abortInProgressLoad();
  39710. // Capturing _this_ load's pending task in a local variable is important here. We may attempt to
  39711. // resolve it twice:
  39712. //
  39713. // 1. when the loading function promise resolves/rejects
  39714. // 2. when cancelling the loading operation
  39715. //
  39716. // After the loading operation is cancelled, `this.resolvePendingTask` no longer represents this
  39717. // particular task, but this `await` may eventually resolve/reject. Thus, when we cancel in
  39718. // response to (1) below, we need to cancel the locally saved task.
  39719. let resolvePendingTask = (this.resolvePendingTask =
  39720. this.pendingTasks.add());
  39721. const { signal: abortSignal } = (this.pendingController = new AbortController());
  39722. try {
  39723. // The actual loading is run through `untracked` - only the request side of `resource` is
  39724. // reactive. This avoids any confusion with signals tracking or not tracking depending on
  39725. // which side of the `await` they are.
  39726. const stream = await untracked(() => {
  39727. return this.loaderFn({
  39728. request: extRequest.request,
  39729. abortSignal,
  39730. previous: {
  39731. status: previousStatus,
  39732. },
  39733. });
  39734. });
  39735. // If this request has been aborted, or the current request no longer
  39736. // matches this load, then we should ignore this resolution.
  39737. if (abortSignal.aborted || untracked(this.extRequest) !== extRequest) {
  39738. return;
  39739. }
  39740. this.state.set({
  39741. extRequest,
  39742. status: ResourceStatus.Resolved,
  39743. previousStatus: ResourceStatus.Resolved,
  39744. stream,
  39745. });
  39746. }
  39747. catch (err) {
  39748. if (abortSignal.aborted || untracked(this.extRequest) !== extRequest) {
  39749. return;
  39750. }
  39751. this.state.set({
  39752. extRequest,
  39753. status: ResourceStatus.Resolved,
  39754. previousStatus: ResourceStatus.Error,
  39755. stream: signal({ error: err }),
  39756. });
  39757. }
  39758. finally {
  39759. // Resolve the pending task now that the resource has a value.
  39760. resolvePendingTask?.();
  39761. resolvePendingTask = undefined;
  39762. }
  39763. }
  39764. abortInProgressLoad() {
  39765. untracked(() => this.pendingController?.abort());
  39766. this.pendingController = undefined;
  39767. // Once the load is aborted, we no longer want to block stability on its resolution.
  39768. this.resolvePendingTask?.();
  39769. this.resolvePendingTask = undefined;
  39770. }
  39771. }
  39772. /**
  39773. * Wraps an equality function to handle either value being `undefined`.
  39774. */
  39775. function wrapEqualityFn(equal) {
  39776. return (a, b) => (a === undefined || b === undefined ? a === b : equal(a, b));
  39777. }
  39778. function getLoader(options) {
  39779. if (isStreamingResourceOptions(options)) {
  39780. return options.stream;
  39781. }
  39782. return async (params) => {
  39783. try {
  39784. return signal({ value: await options.loader(params) });
  39785. }
  39786. catch (err) {
  39787. return signal({ error: err });
  39788. }
  39789. };
  39790. }
  39791. function isStreamingResourceOptions(options) {
  39792. return !!options.stream;
  39793. }
  39794. /**
  39795. * Project from a state with `ResourceInternalStatus` to the user-facing `ResourceStatus`
  39796. */
  39797. function projectStatusOfState(state) {
  39798. switch (state.status) {
  39799. case ResourceStatus.Loading:
  39800. return state.extRequest.reload === 0 ? ResourceStatus.Loading : ResourceStatus.Reloading;
  39801. case ResourceStatus.Resolved:
  39802. return isResolved(untracked(state.stream)) ? ResourceStatus.Resolved : ResourceStatus.Error;
  39803. default:
  39804. return state.status;
  39805. }
  39806. }
  39807. function isResolved(state) {
  39808. return state.error === undefined;
  39809. }
  39810. /*!
  39811. * @license
  39812. * Copyright Google LLC All Rights Reserved.
  39813. *
  39814. * Use of this source code is governed by an MIT-style license that can be
  39815. * found in the LICENSE file at https://angular.dev/license
  39816. */
  39817. /**
  39818. * Gets the class name of the closest component to a node.
  39819. * Warning! this function will return minified names if the name of the component is minified. The
  39820. * consumer of the function is responsible for resolving the minified name to its original name.
  39821. * @param node Node from which to start the search.
  39822. */
  39823. function getClosestComponentName(node) {
  39824. let currentNode = node;
  39825. while (currentNode) {
  39826. const lView = readPatchedLView(currentNode);
  39827. if (lView !== null) {
  39828. for (let i = HEADER_OFFSET; i < lView.length; i++) {
  39829. const current = lView[i];
  39830. if ((!isLView(current) && !isLContainer(current)) || current[HOST] !== currentNode) {
  39831. continue;
  39832. }
  39833. const tView = lView[TVIEW];
  39834. const tNode = getTNode(tView, i);
  39835. if (isComponentHost(tNode)) {
  39836. const def = tView.data[tNode.directiveStart + tNode.componentOffset];
  39837. const name = def.debugInfo?.className || def.type.name;
  39838. // Note: the name may be an empty string if the class name is
  39839. // dropped due to minification. In such cases keep going up the tree.
  39840. if (name) {
  39841. return name;
  39842. }
  39843. else {
  39844. break;
  39845. }
  39846. }
  39847. }
  39848. }
  39849. currentNode = currentNode.parentNode;
  39850. }
  39851. return null;
  39852. }
  39853. /**
  39854. * Compiles a partial directive declaration object into a full directive definition object.
  39855. *
  39856. * @codeGenApi
  39857. */
  39858. function ɵɵngDeclareDirective(decl) {
  39859. const compiler = getCompilerFacade({
  39860. usage: 1 /* JitCompilerUsage.PartialDeclaration */,
  39861. kind: 'directive',
  39862. type: decl.type,
  39863. });
  39864. return compiler.compileDirectiveDeclaration(angularCoreEnv, `ng:///${decl.type.name}/ɵfac.js`, decl);
  39865. }
  39866. /**
  39867. * Evaluates the class metadata declaration.
  39868. *
  39869. * @codeGenApi
  39870. */
  39871. function ɵɵngDeclareClassMetadata(decl) {
  39872. setClassMetadata(decl.type, decl.decorators, decl.ctorParameters ?? null, decl.propDecorators ?? null);
  39873. }
  39874. /**
  39875. * Evaluates the class metadata of a component that contains deferred blocks.
  39876. *
  39877. * @codeGenApi
  39878. */
  39879. function ɵɵngDeclareClassMetadataAsync(decl) {
  39880. setClassMetadataAsync(decl.type, decl.resolveDeferredDeps, (...types) => {
  39881. const meta = decl.resolveMetadata(...types);
  39882. setClassMetadata(decl.type, meta.decorators, meta.ctorParameters, meta.propDecorators);
  39883. });
  39884. }
  39885. /**
  39886. * Compiles a partial component declaration object into a full component definition object.
  39887. *
  39888. * @codeGenApi
  39889. */
  39890. function ɵɵngDeclareComponent(decl) {
  39891. const compiler = getCompilerFacade({
  39892. usage: 1 /* JitCompilerUsage.PartialDeclaration */,
  39893. kind: 'component',
  39894. type: decl.type,
  39895. });
  39896. return compiler.compileComponentDeclaration(angularCoreEnv, `ng:///${decl.type.name}/ɵcmp.js`, decl);
  39897. }
  39898. /**
  39899. * Compiles a partial pipe declaration object into a full pipe definition object.
  39900. *
  39901. * @codeGenApi
  39902. */
  39903. function ɵɵngDeclareFactory(decl) {
  39904. const compiler = getCompilerFacade({
  39905. usage: 1 /* JitCompilerUsage.PartialDeclaration */,
  39906. kind: getFactoryKind(decl.target),
  39907. type: decl.type,
  39908. });
  39909. return compiler.compileFactoryDeclaration(angularCoreEnv, `ng:///${decl.type.name}/ɵfac.js`, decl);
  39910. }
  39911. function getFactoryKind(target) {
  39912. switch (target) {
  39913. case FactoryTarget.Directive:
  39914. return 'directive';
  39915. case FactoryTarget.Component:
  39916. return 'component';
  39917. case FactoryTarget.Injectable:
  39918. return 'injectable';
  39919. case FactoryTarget.Pipe:
  39920. return 'pipe';
  39921. case FactoryTarget.NgModule:
  39922. return 'NgModule';
  39923. }
  39924. }
  39925. /**
  39926. * Compiles a partial injectable declaration object into a full injectable definition object.
  39927. *
  39928. * @codeGenApi
  39929. */
  39930. function ɵɵngDeclareInjectable(decl) {
  39931. const compiler = getCompilerFacade({
  39932. usage: 1 /* JitCompilerUsage.PartialDeclaration */,
  39933. kind: 'injectable',
  39934. type: decl.type,
  39935. });
  39936. return compiler.compileInjectableDeclaration(angularCoreEnv, `ng:///${decl.type.name}/ɵprov.js`, decl);
  39937. }
  39938. /**
  39939. * Compiles a partial injector declaration object into a full injector definition object.
  39940. *
  39941. * @codeGenApi
  39942. */
  39943. function ɵɵngDeclareInjector(decl) {
  39944. const compiler = getCompilerFacade({
  39945. usage: 1 /* JitCompilerUsage.PartialDeclaration */,
  39946. kind: 'NgModule',
  39947. type: decl.type,
  39948. });
  39949. return compiler.compileInjectorDeclaration(angularCoreEnv, `ng:///${decl.type.name}/ɵinj.js`, decl);
  39950. }
  39951. /**
  39952. * Compiles a partial NgModule declaration object into a full NgModule definition object.
  39953. *
  39954. * @codeGenApi
  39955. */
  39956. function ɵɵngDeclareNgModule(decl) {
  39957. const compiler = getCompilerFacade({
  39958. usage: 1 /* JitCompilerUsage.PartialDeclaration */,
  39959. kind: 'NgModule',
  39960. type: decl.type,
  39961. });
  39962. return compiler.compileNgModuleDeclaration(angularCoreEnv, `ng:///${decl.type.name}/ɵmod.js`, decl);
  39963. }
  39964. /**
  39965. * Compiles a partial pipe declaration object into a full pipe definition object.
  39966. *
  39967. * @codeGenApi
  39968. */
  39969. function ɵɵngDeclarePipe(decl) {
  39970. const compiler = getCompilerFacade({
  39971. usage: 1 /* JitCompilerUsage.PartialDeclaration */,
  39972. kind: 'pipe',
  39973. type: decl.type,
  39974. });
  39975. return compiler.compilePipeDeclaration(angularCoreEnv, `ng:///${decl.type.name}/ɵpipe.js`, decl);
  39976. }
  39977. const NOT_SET = /* @__PURE__ */ Symbol('NOT_SET');
  39978. const EMPTY_CLEANUP_SET = /* @__PURE__ */ new Set();
  39979. const AFTER_RENDER_PHASE_EFFECT_NODE = /* @__PURE__ */ (() => ({
  39980. ...SIGNAL_NODE,
  39981. consumerIsAlwaysLive: true,
  39982. consumerAllowSignalWrites: true,
  39983. value: NOT_SET,
  39984. cleanup: null,
  39985. /** Called when the effect becomes dirty */
  39986. consumerMarkedDirty() {
  39987. if (this.sequence.impl.executing) {
  39988. // If hooks are in the middle of executing, then it matters whether this node has yet been
  39989. // executed within its sequence. If not, then we don't want to notify the scheduler since
  39990. // this node will be reached naturally.
  39991. if (this.sequence.lastPhase === null || this.sequence.lastPhase < this.phase) {
  39992. return;
  39993. }
  39994. // If during the execution of a later phase an earlier phase became dirty, then we should not
  39995. // run any further phases until the earlier one reruns.
  39996. this.sequence.erroredOrDestroyed = true;
  39997. }
  39998. // Either hooks are not running, or we're marking a node dirty that has already run within its
  39999. // sequence.
  40000. this.sequence.scheduler.notify(7 /* NotificationSource.RenderHook */);
  40001. },
  40002. phaseFn(previousValue) {
  40003. this.sequence.lastPhase = this.phase;
  40004. if (!this.dirty) {
  40005. return this.signal;
  40006. }
  40007. this.dirty = false;
  40008. if (this.value !== NOT_SET && !consumerPollProducersForChange(this)) {
  40009. // None of our producers report a change since the last time they were read, so no
  40010. // recomputation of our value is necessary.
  40011. return this.signal;
  40012. }
  40013. // Run any needed cleanup functions.
  40014. try {
  40015. for (const cleanupFn of this.cleanup ?? EMPTY_CLEANUP_SET) {
  40016. cleanupFn();
  40017. }
  40018. }
  40019. finally {
  40020. // Even if a cleanup function errors, ensure it's cleared.
  40021. this.cleanup?.clear();
  40022. }
  40023. // Prepare to call the user's effect callback. If there was a previous phase, then it gave us
  40024. // its value as a `Signal`, otherwise `previousValue` will be `undefined`.
  40025. const args = [];
  40026. if (previousValue !== undefined) {
  40027. args.push(previousValue);
  40028. }
  40029. args.push(this.registerCleanupFn);
  40030. // Call the user's callback in our reactive context.
  40031. const prevConsumer = consumerBeforeComputation(this);
  40032. let newValue;
  40033. try {
  40034. newValue = this.userFn.apply(null, args);
  40035. }
  40036. finally {
  40037. consumerAfterComputation(this, prevConsumer);
  40038. }
  40039. if (this.value === NOT_SET || !this.equal(this.value, newValue)) {
  40040. this.value = newValue;
  40041. this.version++;
  40042. }
  40043. return this.signal;
  40044. },
  40045. }))();
  40046. /**
  40047. * An `AfterRenderSequence` that manages an `afterRenderEffect`'s phase effects.
  40048. */
  40049. class AfterRenderEffectSequence extends AfterRenderSequence {
  40050. scheduler;
  40051. /**
  40052. * While this sequence is executing, this tracks the last phase which was called by the
  40053. * `afterRender` machinery.
  40054. *
  40055. * When a phase effect is marked dirty, this is used to determine whether it's already run or not.
  40056. */
  40057. lastPhase = null;
  40058. /**
  40059. * The reactive nodes for each phase, if a phase effect is defined for that phase.
  40060. *
  40061. * These are initialized to `undefined` but set in the constructor.
  40062. */
  40063. nodes = [undefined, undefined, undefined, undefined];
  40064. constructor(impl, effectHooks, view, scheduler, destroyRef, snapshot = null) {
  40065. // Note that we also initialize the underlying `AfterRenderSequence` hooks to `undefined` and
  40066. // populate them as we create reactive nodes below.
  40067. super(impl, [undefined, undefined, undefined, undefined], view, false, destroyRef, snapshot);
  40068. this.scheduler = scheduler;
  40069. // Setup a reactive node for each phase.
  40070. for (const phase of AFTER_RENDER_PHASES) {
  40071. const effectHook = effectHooks[phase];
  40072. if (effectHook === undefined) {
  40073. continue;
  40074. }
  40075. const node = Object.create(AFTER_RENDER_PHASE_EFFECT_NODE);
  40076. node.sequence = this;
  40077. node.phase = phase;
  40078. node.userFn = effectHook;
  40079. node.dirty = true;
  40080. node.signal = (() => {
  40081. producerAccessed(node);
  40082. return node.value;
  40083. });
  40084. node.signal[SIGNAL] = node;
  40085. node.registerCleanupFn = (fn) => (node.cleanup ??= new Set()).add(fn);
  40086. this.nodes[phase] = node;
  40087. // Install the upstream hook which runs the `phaseFn` for this phase.
  40088. this.hooks[phase] = (value) => node.phaseFn(value);
  40089. }
  40090. }
  40091. afterRun() {
  40092. super.afterRun();
  40093. // We're done running this sequence, so reset `lastPhase`.
  40094. this.lastPhase = null;
  40095. }
  40096. destroy() {
  40097. super.destroy();
  40098. // Run the cleanup functions for each node.
  40099. for (const node of this.nodes) {
  40100. for (const fn of node?.cleanup ?? EMPTY_CLEANUP_SET) {
  40101. fn();
  40102. }
  40103. }
  40104. }
  40105. }
  40106. /**
  40107. * @experimental
  40108. */
  40109. function afterRenderEffect(callbackOrSpec, options) {
  40110. ngDevMode &&
  40111. assertNotInReactiveContext(afterRenderEffect, 'Call `afterRenderEffect` outside of a reactive context. For example, create the render ' +
  40112. 'effect inside the component constructor`.');
  40113. !options?.injector && assertInInjectionContext(afterRenderEffect);
  40114. if (typeof ngServerMode !== 'undefined' && ngServerMode) {
  40115. return NOOP_AFTER_RENDER_REF;
  40116. }
  40117. const injector = options?.injector ?? inject(Injector);
  40118. const scheduler = injector.get(ChangeDetectionScheduler);
  40119. const manager = injector.get(AfterRenderManager);
  40120. const tracing = injector.get(TracingService, null, { optional: true });
  40121. manager.impl ??= injector.get(AfterRenderImpl);
  40122. let spec = callbackOrSpec;
  40123. if (typeof spec === 'function') {
  40124. spec = { mixedReadWrite: callbackOrSpec };
  40125. }
  40126. const viewContext = injector.get(ViewContext, null, { optional: true });
  40127. const sequence = new AfterRenderEffectSequence(manager.impl, [spec.earlyRead, spec.write, spec.mixedReadWrite, spec.read], viewContext?.view, scheduler, injector.get(DestroyRef), tracing?.snapshot(null));
  40128. manager.impl.register(sequence);
  40129. return sequence;
  40130. }
  40131. /**
  40132. * Creates a `ComponentRef` instance based on provided component type and a set of options.
  40133. *
  40134. * @usageNotes
  40135. *
  40136. * The example below demonstrates how the `createComponent` function can be used
  40137. * to create an instance of a ComponentRef dynamically and attach it to an ApplicationRef,
  40138. * so that it gets included into change detection cycles.
  40139. *
  40140. * Note: the example uses standalone components, but the function can also be used for
  40141. * non-standalone components (declared in an NgModule) as well.
  40142. *
  40143. * ```angular-ts
  40144. * @Component({
  40145. * standalone: true,
  40146. * template: `Hello {{ name }}!`
  40147. * })
  40148. * class HelloComponent {
  40149. * name = 'Angular';
  40150. * }
  40151. *
  40152. * @Component({
  40153. * standalone: true,
  40154. * template: `<div id="hello-component-host"></div>`
  40155. * })
  40156. * class RootComponent {}
  40157. *
  40158. * // Bootstrap an application.
  40159. * const applicationRef = await bootstrapApplication(RootComponent);
  40160. *
  40161. * // Locate a DOM node that would be used as a host.
  40162. * const hostElement = document.getElementById('hello-component-host');
  40163. *
  40164. * // Get an `EnvironmentInjector` instance from the `ApplicationRef`.
  40165. * const environmentInjector = applicationRef.injector;
  40166. *
  40167. * // We can now create a `ComponentRef` instance.
  40168. * const componentRef = createComponent(HelloComponent, {hostElement, environmentInjector});
  40169. *
  40170. * // Last step is to register the newly created ref using the `ApplicationRef` instance
  40171. * // to include the component view into change detection cycles.
  40172. * applicationRef.attachView(componentRef.hostView);
  40173. * componentRef.changeDetectorRef.detectChanges();
  40174. * ```
  40175. *
  40176. * @param component Component class reference.
  40177. * @param options Set of options to use:
  40178. * * `environmentInjector`: An `EnvironmentInjector` instance to be used for the component.
  40179. * * `hostElement` (optional): A DOM node that should act as a host node for the component. If not
  40180. * provided, Angular creates one based on the tag name used in the component selector (and falls
  40181. * back to using `div` if selector doesn't have tag name info).
  40182. * * `elementInjector` (optional): An `ElementInjector` instance, see additional info about it
  40183. * [here](guide/di/hierarchical-dependency-injection#elementinjector).
  40184. * * `projectableNodes` (optional): A list of DOM nodes that should be projected through
  40185. * [`<ng-content>`](api/core/ng-content) of the new component instance, e.g.,
  40186. * `[[element1, element2]]`: projects `element1` and `element2` into the same `<ng-content>`.
  40187. * `[[element1, element2], [element3]]`: projects `element1` and `element2` into one `<ng-content>`,
  40188. * and `element3` into a separate `<ng-content>`.
  40189. * @returns ComponentRef instance that represents a given Component.
  40190. *
  40191. * @publicApi
  40192. */
  40193. function createComponent(component, options) {
  40194. ngDevMode && assertComponentDef(component);
  40195. const componentDef = getComponentDef(component);
  40196. const elementInjector = options.elementInjector || getNullInjector();
  40197. const factory = new ComponentFactory(componentDef);
  40198. return factory.create(elementInjector, options.projectableNodes, options.hostElement, options.environmentInjector);
  40199. }
  40200. /**
  40201. * Creates an object that allows to retrieve component metadata.
  40202. *
  40203. * @usageNotes
  40204. *
  40205. * The example below demonstrates how to use the function and how the fields
  40206. * of the returned object map to the component metadata.
  40207. *
  40208. * ```angular-ts
  40209. * @Component({
  40210. * standalone: true,
  40211. * selector: 'foo-component',
  40212. * template: `
  40213. * <ng-content></ng-content>
  40214. * <ng-content select="content-selector-a"></ng-content>
  40215. * `,
  40216. * })
  40217. * class FooComponent {
  40218. * @Input('inputName') inputPropName: string;
  40219. * @Output('outputName') outputPropName = new EventEmitter<void>();
  40220. * }
  40221. *
  40222. * const mirror = reflectComponentType(FooComponent);
  40223. * expect(mirror.type).toBe(FooComponent);
  40224. * expect(mirror.selector).toBe('foo-component');
  40225. * expect(mirror.isStandalone).toBe(true);
  40226. * expect(mirror.inputs).toEqual([{propName: 'inputName', templateName: 'inputPropName'}]);
  40227. * expect(mirror.outputs).toEqual([{propName: 'outputName', templateName: 'outputPropName'}]);
  40228. * expect(mirror.ngContentSelectors).toEqual([
  40229. * '*', // first `<ng-content>` in a template, the selector defaults to `*`
  40230. * 'content-selector-a' // second `<ng-content>` in a template
  40231. * ]);
  40232. * ```
  40233. *
  40234. * @param component Component class reference.
  40235. * @returns An object that allows to retrieve component metadata.
  40236. *
  40237. * @publicApi
  40238. */
  40239. function reflectComponentType(component) {
  40240. const componentDef = getComponentDef(component);
  40241. if (!componentDef)
  40242. return null;
  40243. const factory = new ComponentFactory(componentDef);
  40244. return {
  40245. get selector() {
  40246. return factory.selector;
  40247. },
  40248. get type() {
  40249. return factory.componentType;
  40250. },
  40251. get inputs() {
  40252. return factory.inputs;
  40253. },
  40254. get outputs() {
  40255. return factory.outputs;
  40256. },
  40257. get ngContentSelectors() {
  40258. return factory.ngContentSelectors;
  40259. },
  40260. get isStandalone() {
  40261. return componentDef.standalone;
  40262. },
  40263. get isSignal() {
  40264. return componentDef.signals;
  40265. },
  40266. };
  40267. }
  40268. /**
  40269. * Merge multiple application configurations from left to right.
  40270. *
  40271. * @param configs Two or more configurations to be merged.
  40272. * @returns A merged [ApplicationConfig](api/core/ApplicationConfig).
  40273. *
  40274. * @publicApi
  40275. */
  40276. function mergeApplicationConfig(...configs) {
  40277. return configs.reduce((prev, curr) => {
  40278. return Object.assign(prev, curr, { providers: [...prev.providers, ...curr.providers] });
  40279. }, { providers: [] });
  40280. }
  40281. /**
  40282. * Injection token representing the current HTTP request object.
  40283. *
  40284. * Use this token to access the current request when handling server-side
  40285. * rendering (SSR).
  40286. *
  40287. * @remarks
  40288. * This token may be `null` in the following scenarios:
  40289. *
  40290. * * During the build processes.
  40291. * * When the application is rendered in the browser (client-side rendering).
  40292. * * When performing static site generation (SSG).
  40293. * * During route extraction in development (at the time of the request).
  40294. *
  40295. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Request | `Request` on MDN}
  40296. *
  40297. * @developerPreview
  40298. */
  40299. const REQUEST = new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'REQUEST' : '', {
  40300. providedIn: 'platform',
  40301. factory: () => null,
  40302. });
  40303. /**
  40304. * Injection token for response initialization options.
  40305. *
  40306. * Use this token to provide response options for configuring or initializing
  40307. * HTTP responses in server-side rendering or API endpoints.
  40308. *
  40309. * @remarks
  40310. * This token may be `null` in the following scenarios:
  40311. *
  40312. * * During the build processes.
  40313. * * When the application is rendered in the browser (client-side rendering).
  40314. * * When performing static site generation (SSG).
  40315. * * During route extraction in development (at the time of the request).
  40316. *
  40317. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Response/Response | `ResponseInit` on MDN}
  40318. *
  40319. * @developerPreview
  40320. */
  40321. const RESPONSE_INIT = new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'RESPONSE_INIT' : '', {
  40322. providedIn: 'platform',
  40323. factory: () => null,
  40324. });
  40325. /**
  40326. * Injection token for additional request context.
  40327. *
  40328. * Use this token to pass custom metadata or context related to the current request in server-side rendering.
  40329. *
  40330. * @remarks
  40331. * This token is only available during server-side rendering and will be `null` in other contexts.
  40332. *
  40333. * @developerPreview
  40334. */
  40335. const REQUEST_CONTEXT = new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'REQUEST_CONTEXT' : '', {
  40336. providedIn: 'platform',
  40337. factory: () => null,
  40338. });
  40339. 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, CLIENT_RENDER_MODE_FLAG as ɵCLIENT_RENDER_MODE_FLAG, 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, DEHYDRATED_BLOCK_REGISTRY as ɵDEHYDRATED_BLOCK_REGISTRY, DeferBlockBehavior as ɵDeferBlockBehavior, DeferBlockState as ɵDeferBlockState, ENABLE_ROOT_COMPONENT_BOOTSTRAP as ɵENABLE_ROOT_COMPONENT_BOOTSTRAP, EffectScheduler as ɵEffectScheduler, HydrationStatus as ɵHydrationStatus, 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_BLOCK_ELEMENT_MAP as ɵJSACTION_BLOCK_ELEMENT_MAP, 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, R3Injector as ɵR3Injector, 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, TimerScheduler as ɵTimerScheduler, 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, createOrReusePlatformInjector as ɵcreateOrReusePlatformInjector, 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, getComponentDef as ɵgetComponentDef, getDebugNode as ɵgetDebugNode, getDeferBlocks$1 as ɵgetDeferBlocks, getDirectives as ɵgetDirectives, getDocument as ɵgetDocument, 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, ɵɵgetReplaceMetadataURL, ɵɵ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 };
  40340. //# sourceMappingURL=core.mjs.map